blob: 3d7840403c1dc648a8cd94452f693c0d7a4d83f3 [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
Walter Dörwald16807132007-05-25 13:52:07 +0000166/* This dictionary holds all interned unicode strings. Note that references
167 to strings in this dictionary are *not* counted in the string's ob_refcnt.
168 When the interned string reaches a refcnt of 0 the string deallocation
169 function will delete the reference from this dictionary.
170
171 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000172 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000173*/
Serhiy Storchaka05997252013-01-26 12:14:02 +0200174static PyObject *interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +0000175
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000176/* The empty Unicode object is shared to improve performance. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200177static PyObject *unicode_empty = NULL;
Serhiy Storchaka05997252013-01-26 12:14:02 +0200178
Serhiy Storchaka678db842013-01-26 12:16:36 +0200179#define _Py_INCREF_UNICODE_EMPTY() \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200180 do { \
181 if (unicode_empty != NULL) \
182 Py_INCREF(unicode_empty); \
183 else { \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200184 unicode_empty = PyUnicode_New(0, 0); \
185 if (unicode_empty != NULL) { \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200186 Py_INCREF(unicode_empty); \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200187 assert(_PyUnicode_CheckConsistency(unicode_empty, 1)); \
188 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200189 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200190 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000191
Serhiy Storchaka678db842013-01-26 12:16:36 +0200192#define _Py_RETURN_UNICODE_EMPTY() \
193 do { \
194 _Py_INCREF_UNICODE_EMPTY(); \
195 return unicode_empty; \
196 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000197
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200198/* Forward declaration */
199Py_LOCAL_INLINE(int)
200_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch);
201
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200202/* List of static strings. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200203static _Py_Identifier *static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200204
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000205/* Single character Unicode strings in the Latin-1 range are being
206 shared as well. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200207static PyObject *unicode_latin1[256] = {NULL};
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000208
Christian Heimes190d79e2008-01-30 11:58:22 +0000209/* Fast detection of the most frequent whitespace characters */
210const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000211 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000212/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000213/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000214/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000215/* case 0x000C: * FORM FEED */
216/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000217 0, 1, 1, 1, 1, 1, 0, 0,
218 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000219/* case 0x001C: * FILE SEPARATOR */
220/* case 0x001D: * GROUP SEPARATOR */
221/* case 0x001E: * RECORD SEPARATOR */
222/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000223 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000224/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000225 1, 0, 0, 0, 0, 0, 0, 0,
226 0, 0, 0, 0, 0, 0, 0, 0,
227 0, 0, 0, 0, 0, 0, 0, 0,
228 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000229
Benjamin Peterson14339b62009-01-31 16:36:08 +0000230 0, 0, 0, 0, 0, 0, 0, 0,
231 0, 0, 0, 0, 0, 0, 0, 0,
232 0, 0, 0, 0, 0, 0, 0, 0,
233 0, 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,
237 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000238};
239
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200240/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200241static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200242static PyObject* get_latin1_char(unsigned char ch);
Victor Stinner488fa492011-12-12 00:01:39 +0100243static int unicode_modifiable(PyObject *unicode);
244
Victor Stinnerfe226c02011-10-03 03:52:20 +0200245
Alexander Belopolsky40018472011-02-26 01:02:56 +0000246static PyObject *
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100247_PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200248static PyObject *
249_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
250static PyObject *
251_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
252
253static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000254unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000255 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100256 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000257 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
258
Alexander Belopolsky40018472011-02-26 01:02:56 +0000259static void
260raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300261 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100262 PyObject *unicode,
263 Py_ssize_t startpos, Py_ssize_t endpos,
264 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000265
Christian Heimes190d79e2008-01-30 11:58:22 +0000266/* Same for linebreaks */
267static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000268 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000269/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000270/* 0x000B, * LINE TABULATION */
271/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000272/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000273 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000274 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000275/* 0x001C, * FILE SEPARATOR */
276/* 0x001D, * GROUP SEPARATOR */
277/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000278 0, 0, 0, 0, 1, 1, 1, 0,
279 0, 0, 0, 0, 0, 0, 0, 0,
280 0, 0, 0, 0, 0, 0, 0, 0,
281 0, 0, 0, 0, 0, 0, 0, 0,
282 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000283
Benjamin Peterson14339b62009-01-31 16:36:08 +0000284 0, 0, 0, 0, 0, 0, 0, 0,
285 0, 0, 0, 0, 0, 0, 0, 0,
286 0, 0, 0, 0, 0, 0, 0, 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,
291 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000292};
293
Serhiy Storchaka1009bf12015-04-03 23:53:51 +0300294#include "clinic/unicodeobject.c.h"
295
Victor Stinner50149202015-09-22 00:26:54 +0200296typedef enum {
297 _Py_ERROR_UNKNOWN=0,
298 _Py_ERROR_STRICT,
299 _Py_ERROR_SURROGATEESCAPE,
Victor Stinner01ada392015-10-01 21:54:51 +0200300 _Py_ERROR_SURROGATEPASS,
Victor Stinner50149202015-09-22 00:26:54 +0200301 _Py_ERROR_REPLACE,
302 _Py_ERROR_IGNORE,
303 _Py_ERROR_XMLCHARREFREPLACE,
304 _Py_ERROR_OTHER
305} _Py_error_handler;
306
307static _Py_error_handler
308get_error_handler(const char *errors)
309{
310 if (errors == NULL)
311 return _Py_ERROR_STRICT;
312 if (strcmp(errors, "strict") == 0)
313 return _Py_ERROR_STRICT;
314 if (strcmp(errors, "surrogateescape") == 0)
315 return _Py_ERROR_SURROGATEESCAPE;
Victor Stinner01ada392015-10-01 21:54:51 +0200316 if (strcmp(errors, "surrogatepass") == 0)
317 return _Py_ERROR_SURROGATEPASS;
Victor Stinner50149202015-09-22 00:26:54 +0200318 if (strcmp(errors, "ignore") == 0)
319 return _Py_ERROR_IGNORE;
320 if (strcmp(errors, "replace") == 0)
321 return _Py_ERROR_REPLACE;
322 if (strcmp(errors, "xmlcharrefreplace") == 0)
323 return _Py_ERROR_XMLCHARREFREPLACE;
324 return _Py_ERROR_OTHER;
325}
326
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300327/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
328 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000329Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000330PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000331{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000332#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000333 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000334#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000335 /* This is actually an illegal character, so it should
336 not be passed to unichr. */
337 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000338#endif
339}
340
Victor Stinner910337b2011-10-03 03:20:16 +0200341#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200342int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100343_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200344{
345 PyASCIIObject *ascii;
346 unsigned int kind;
347
348 assert(PyUnicode_Check(op));
349
350 ascii = (PyASCIIObject *)op;
351 kind = ascii->state.kind;
352
Victor Stinnera3b334d2011-10-03 13:53:37 +0200353 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200354 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200355 assert(ascii->state.ready == 1);
356 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200357 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200358 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200359 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200360
Victor Stinnera41463c2011-10-04 01:05:08 +0200361 if (ascii->state.compact == 1) {
362 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200363 assert(kind == PyUnicode_1BYTE_KIND
364 || kind == PyUnicode_2BYTE_KIND
365 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200366 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200367 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200368 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100369 }
370 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200371 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
372
373 data = unicode->data.any;
374 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100375 assert(ascii->length == 0);
376 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200377 assert(ascii->state.compact == 0);
378 assert(ascii->state.ascii == 0);
379 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100380 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200381 assert(ascii->wstr != NULL);
382 assert(data == NULL);
383 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200384 }
385 else {
386 assert(kind == PyUnicode_1BYTE_KIND
387 || kind == PyUnicode_2BYTE_KIND
388 || kind == PyUnicode_4BYTE_KIND);
389 assert(ascii->state.compact == 0);
390 assert(ascii->state.ready == 1);
391 assert(data != NULL);
392 if (ascii->state.ascii) {
393 assert (compact->utf8 == data);
394 assert (compact->utf8_length == ascii->length);
395 }
396 else
397 assert (compact->utf8 != data);
398 }
399 }
400 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200401 if (
402#if SIZEOF_WCHAR_T == 2
403 kind == PyUnicode_2BYTE_KIND
404#else
405 kind == PyUnicode_4BYTE_KIND
406#endif
407 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200408 {
409 assert(ascii->wstr == data);
410 assert(compact->wstr_length == ascii->length);
411 } else
412 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200413 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200414
415 if (compact->utf8 == NULL)
416 assert(compact->utf8_length == 0);
417 if (ascii->wstr == NULL)
418 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200419 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200420 /* check that the best kind is used */
421 if (check_content && kind != PyUnicode_WCHAR_KIND)
422 {
423 Py_ssize_t i;
424 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200425 void *data;
426 Py_UCS4 ch;
427
428 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200429 for (i=0; i < ascii->length; i++)
430 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200431 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200432 if (ch > maxchar)
433 maxchar = ch;
434 }
435 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100436 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200437 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100438 assert(maxchar <= 255);
439 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200440 else
441 assert(maxchar < 128);
442 }
Victor Stinner77faf692011-11-20 18:56:05 +0100443 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200444 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100445 assert(maxchar <= 0xFFFF);
446 }
447 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200448 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100449 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100450 }
Victor Stinner718fbf02012-04-26 00:39:37 +0200451 assert(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200452 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400453 return 1;
454}
Victor Stinner910337b2011-10-03 03:20:16 +0200455#endif
456
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100457static PyObject*
458unicode_result_wchar(PyObject *unicode)
459{
460#ifndef Py_DEBUG
461 Py_ssize_t len;
462
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100463 len = _PyUnicode_WSTR_LENGTH(unicode);
464 if (len == 0) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100465 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200466 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100467 }
468
469 if (len == 1) {
470 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100471 if ((Py_UCS4)ch < 256) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100472 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
473 Py_DECREF(unicode);
474 return latin1_char;
475 }
476 }
477
478 if (_PyUnicode_Ready(unicode) < 0) {
Victor Stinneraa771272012-10-04 02:32:58 +0200479 Py_DECREF(unicode);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100480 return NULL;
481 }
482#else
Victor Stinneraa771272012-10-04 02:32:58 +0200483 assert(Py_REFCNT(unicode) == 1);
484
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100485 /* don't make the result ready in debug mode to ensure that the caller
486 makes the string ready before using it */
487 assert(_PyUnicode_CheckConsistency(unicode, 1));
488#endif
489 return unicode;
490}
491
492static PyObject*
493unicode_result_ready(PyObject *unicode)
494{
495 Py_ssize_t length;
496
497 length = PyUnicode_GET_LENGTH(unicode);
498 if (length == 0) {
499 if (unicode != unicode_empty) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100500 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200501 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100502 }
503 return unicode_empty;
504 }
505
506 if (length == 1) {
Victor Stinner69ed0f42013-04-09 21:48:24 +0200507 void *data = PyUnicode_DATA(unicode);
508 int kind = PyUnicode_KIND(unicode);
509 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100510 if (ch < 256) {
511 PyObject *latin1_char = unicode_latin1[ch];
512 if (latin1_char != NULL) {
513 if (unicode != latin1_char) {
514 Py_INCREF(latin1_char);
515 Py_DECREF(unicode);
516 }
517 return latin1_char;
518 }
519 else {
520 assert(_PyUnicode_CheckConsistency(unicode, 1));
521 Py_INCREF(unicode);
522 unicode_latin1[ch] = unicode;
523 return unicode;
524 }
525 }
526 }
527
528 assert(_PyUnicode_CheckConsistency(unicode, 1));
529 return unicode;
530}
531
532static PyObject*
533unicode_result(PyObject *unicode)
534{
535 assert(_PyUnicode_CHECK(unicode));
536 if (PyUnicode_IS_READY(unicode))
537 return unicode_result_ready(unicode);
538 else
539 return unicode_result_wchar(unicode);
540}
541
Victor Stinnerc4b49542011-12-11 22:44:26 +0100542static PyObject*
543unicode_result_unchanged(PyObject *unicode)
544{
545 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500546 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100547 return NULL;
548 Py_INCREF(unicode);
549 return unicode;
550 }
551 else
552 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100553 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100554}
555
Thomas Wouters477c8d52006-05-27 19:21:47 +0000556/* --- Bloom Filters ----------------------------------------------------- */
557
558/* stuff to implement simple "bloom filters" for Unicode characters.
559 to keep things simple, we use a single bitmask, using the least 5
560 bits from each unicode characters as the bit index. */
561
562/* the linebreak mask is set up by Unicode_Init below */
563
Antoine Pitrouf068f942010-01-13 14:19:12 +0000564#if LONG_BIT >= 128
565#define BLOOM_WIDTH 128
566#elif LONG_BIT >= 64
567#define BLOOM_WIDTH 64
568#elif LONG_BIT >= 32
569#define BLOOM_WIDTH 32
570#else
571#error "LONG_BIT is smaller than 32"
572#endif
573
Thomas Wouters477c8d52006-05-27 19:21:47 +0000574#define BLOOM_MASK unsigned long
575
Serhiy Storchaka05997252013-01-26 12:14:02 +0200576static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000577
Antoine Pitrouf068f942010-01-13 14:19:12 +0000578#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000579
Benjamin Peterson29060642009-01-31 22:14:21 +0000580#define BLOOM_LINEBREAK(ch) \
581 ((ch) < 128U ? ascii_linebreak[(ch)] : \
582 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000583
Alexander Belopolsky40018472011-02-26 01:02:56 +0000584Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200585make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000586{
Victor Stinnera85af502013-04-09 21:53:54 +0200587#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
588 do { \
589 TYPE *data = (TYPE *)PTR; \
590 TYPE *end = data + LEN; \
591 Py_UCS4 ch; \
592 for (; data != end; data++) { \
593 ch = *data; \
594 MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
595 } \
596 break; \
597 } while (0)
598
Thomas Wouters477c8d52006-05-27 19:21:47 +0000599 /* calculate simple bloom-style bitmask for a given unicode string */
600
Antoine Pitrouf068f942010-01-13 14:19:12 +0000601 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000602
603 mask = 0;
Victor Stinnera85af502013-04-09 21:53:54 +0200604 switch (kind) {
605 case PyUnicode_1BYTE_KIND:
606 BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
607 break;
608 case PyUnicode_2BYTE_KIND:
609 BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
610 break;
611 case PyUnicode_4BYTE_KIND:
612 BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
613 break;
614 default:
615 assert(0);
616 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000617 return mask;
Victor Stinnera85af502013-04-09 21:53:54 +0200618
619#undef BLOOM_UPDATE
Thomas Wouters477c8d52006-05-27 19:21:47 +0000620}
621
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200622/* Compilation of templated routines */
623
624#include "stringlib/asciilib.h"
625#include "stringlib/fastsearch.h"
626#include "stringlib/partition.h"
627#include "stringlib/split.h"
628#include "stringlib/count.h"
629#include "stringlib/find.h"
630#include "stringlib/find_max_char.h"
631#include "stringlib/localeutil.h"
632#include "stringlib/undef.h"
633
634#include "stringlib/ucs1lib.h"
635#include "stringlib/fastsearch.h"
636#include "stringlib/partition.h"
637#include "stringlib/split.h"
638#include "stringlib/count.h"
639#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300640#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200641#include "stringlib/find_max_char.h"
642#include "stringlib/localeutil.h"
643#include "stringlib/undef.h"
644
645#include "stringlib/ucs2lib.h"
646#include "stringlib/fastsearch.h"
647#include "stringlib/partition.h"
648#include "stringlib/split.h"
649#include "stringlib/count.h"
650#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300651#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200652#include "stringlib/find_max_char.h"
653#include "stringlib/localeutil.h"
654#include "stringlib/undef.h"
655
656#include "stringlib/ucs4lib.h"
657#include "stringlib/fastsearch.h"
658#include "stringlib/partition.h"
659#include "stringlib/split.h"
660#include "stringlib/count.h"
661#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300662#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200663#include "stringlib/find_max_char.h"
664#include "stringlib/localeutil.h"
665#include "stringlib/undef.h"
666
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200667#include "stringlib/unicodedefs.h"
668#include "stringlib/fastsearch.h"
669#include "stringlib/count.h"
670#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100671#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200672
Guido van Rossumd57fd912000-03-10 22:53:23 +0000673/* --- Unicode Object ----------------------------------------------------- */
674
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200675static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200676fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200677
Serhiy Storchakad9d769f2015-03-24 21:55:47 +0200678Py_LOCAL_INLINE(Py_ssize_t) findchar(const void *s, int kind,
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200679 Py_ssize_t size, Py_UCS4 ch,
680 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200681{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200682 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
683
684 switch (kind) {
685 case PyUnicode_1BYTE_KIND:
686 {
687 Py_UCS1 ch1 = (Py_UCS1) ch;
688 if (ch1 == ch)
689 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
690 else
691 return -1;
692 }
693 case PyUnicode_2BYTE_KIND:
694 {
695 Py_UCS2 ch2 = (Py_UCS2) ch;
696 if (ch2 == ch)
697 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
698 else
699 return -1;
700 }
701 case PyUnicode_4BYTE_KIND:
702 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
703 default:
704 assert(0);
705 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200706 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200707}
708
Victor Stinnerafffce42012-10-03 23:03:17 +0200709#ifdef Py_DEBUG
710/* Fill the data of an Unicode string with invalid characters to detect bugs
711 earlier.
712
713 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
714 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
715 invalid character in Unicode 6.0. */
716static void
717unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
718{
719 int kind = PyUnicode_KIND(unicode);
720 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
721 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
722 if (length <= old_length)
723 return;
724 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
725}
726#endif
727
Victor Stinnerfe226c02011-10-03 03:52:20 +0200728static PyObject*
729resize_compact(PyObject *unicode, Py_ssize_t length)
730{
731 Py_ssize_t char_size;
732 Py_ssize_t struct_size;
733 Py_ssize_t new_size;
734 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100735 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +0200736#ifdef Py_DEBUG
737 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
738#endif
739
Victor Stinner79891572012-05-03 13:43:07 +0200740 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200741 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100742 assert(PyUnicode_IS_COMPACT(unicode));
743
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200744 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100745 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200746 struct_size = sizeof(PyASCIIObject);
747 else
748 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200749 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200750
Victor Stinnerfe226c02011-10-03 03:52:20 +0200751 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
752 PyErr_NoMemory();
753 return NULL;
754 }
755 new_size = (struct_size + (length + 1) * char_size);
756
Victor Stinner84def372011-12-11 20:04:56 +0100757 _Py_DEC_REFTOTAL;
758 _Py_ForgetReference(unicode);
759
Serhiy Storchaka20b39b22014-09-28 11:27:24 +0300760 new_unicode = (PyObject *)PyObject_REALLOC(unicode, new_size);
Victor Stinner84def372011-12-11 20:04:56 +0100761 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100762 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200763 PyErr_NoMemory();
764 return NULL;
765 }
Victor Stinner84def372011-12-11 20:04:56 +0100766 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200767 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100768
Victor Stinnerfe226c02011-10-03 03:52:20 +0200769 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200770 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200771 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100772 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200773 _PyUnicode_WSTR_LENGTH(unicode) = length;
774 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100775 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
776 PyObject_DEL(_PyUnicode_WSTR(unicode));
777 _PyUnicode_WSTR(unicode) = NULL;
778 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200779#ifdef Py_DEBUG
780 unicode_fill_invalid(unicode, old_length);
781#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200782 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
783 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200784 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200785 return unicode;
786}
787
Alexander Belopolsky40018472011-02-26 01:02:56 +0000788static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200789resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000790{
Victor Stinner95663112011-10-04 01:03:50 +0200791 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100792 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200793 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200794 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000795
Victor Stinnerfe226c02011-10-03 03:52:20 +0200796 if (PyUnicode_IS_READY(unicode)) {
797 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200798 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200799 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +0200800#ifdef Py_DEBUG
801 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
802#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200803
804 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200805 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200806 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
807 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200808
809 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
810 PyErr_NoMemory();
811 return -1;
812 }
813 new_size = (length + 1) * char_size;
814
Victor Stinner7a9105a2011-12-12 00:13:42 +0100815 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
816 {
817 PyObject_DEL(_PyUnicode_UTF8(unicode));
818 _PyUnicode_UTF8(unicode) = NULL;
819 _PyUnicode_UTF8_LENGTH(unicode) = 0;
820 }
821
Victor Stinnerfe226c02011-10-03 03:52:20 +0200822 data = (PyObject *)PyObject_REALLOC(data, new_size);
823 if (data == NULL) {
824 PyErr_NoMemory();
825 return -1;
826 }
827 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200828 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200829 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200830 _PyUnicode_WSTR_LENGTH(unicode) = length;
831 }
832 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200833 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200834 _PyUnicode_UTF8_LENGTH(unicode) = length;
835 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200836 _PyUnicode_LENGTH(unicode) = length;
837 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +0200838#ifdef Py_DEBUG
839 unicode_fill_invalid(unicode, old_length);
840#endif
Victor Stinner95663112011-10-04 01:03:50 +0200841 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200842 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200843 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200844 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200845 }
Victor Stinner95663112011-10-04 01:03:50 +0200846 assert(_PyUnicode_WSTR(unicode) != NULL);
847
848 /* check for integer overflow */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -0700849 if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
Victor Stinner95663112011-10-04 01:03:50 +0200850 PyErr_NoMemory();
851 return -1;
852 }
Victor Stinner7a9105a2011-12-12 00:13:42 +0100853 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +0200854 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +0100855 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +0200856 if (!wstr) {
857 PyErr_NoMemory();
858 return -1;
859 }
860 _PyUnicode_WSTR(unicode) = wstr;
861 _PyUnicode_WSTR(unicode)[length] = 0;
862 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200863 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000864 return 0;
865}
866
Victor Stinnerfe226c02011-10-03 03:52:20 +0200867static PyObject*
868resize_copy(PyObject *unicode, Py_ssize_t length)
869{
870 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100871 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200872 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100873
Benjamin Petersonbac79492012-01-14 13:34:47 -0500874 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +0100875 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200876
877 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
878 if (copy == NULL)
879 return NULL;
880
881 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +0200882 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200883 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200884 }
885 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200886 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100887
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200888 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200889 if (w == NULL)
890 return NULL;
891 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
892 copy_length = Py_MIN(copy_length, length);
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +0200893 Py_MEMCPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
894 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200895 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200896 }
897}
898
Guido van Rossumd57fd912000-03-10 22:53:23 +0000899/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000900 Ux0000 terminated; some code (e.g. new_identifier)
901 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000902
903 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000904 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000905
906*/
907
Alexander Belopolsky40018472011-02-26 01:02:56 +0000908static PyUnicodeObject *
909_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000910{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200911 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200912 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000913
Thomas Wouters477c8d52006-05-27 19:21:47 +0000914 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000915 if (length == 0 && unicode_empty != NULL) {
916 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200917 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000918 }
919
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000920 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -0700921 if (length > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000922 return (PyUnicodeObject *)PyErr_NoMemory();
923 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200924 if (length < 0) {
925 PyErr_SetString(PyExc_SystemError,
926 "Negative size passed to _PyUnicode_New");
927 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000928 }
929
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200930 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
931 if (unicode == NULL)
932 return NULL;
933 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +0100934
935 _PyUnicode_WSTR_LENGTH(unicode) = length;
936 _PyUnicode_HASH(unicode) = -1;
937 _PyUnicode_STATE(unicode).interned = 0;
938 _PyUnicode_STATE(unicode).kind = 0;
939 _PyUnicode_STATE(unicode).compact = 0;
940 _PyUnicode_STATE(unicode).ready = 0;
941 _PyUnicode_STATE(unicode).ascii = 0;
942 _PyUnicode_DATA_ANY(unicode) = NULL;
943 _PyUnicode_LENGTH(unicode) = 0;
944 _PyUnicode_UTF8(unicode) = NULL;
945 _PyUnicode_UTF8_LENGTH(unicode) = 0;
946
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200947 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
948 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100949 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +0000950 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100951 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000952 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200953
Jeremy Hyltond8082792003-09-16 19:41:39 +0000954 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000955 * the caller fails before initializing str -- unicode_resize()
956 * reads str[0], and the Keep-Alive optimization can keep memory
957 * allocated for str alive across a call to unicode_dealloc(unicode).
958 * We don't want unicode_resize to read uninitialized memory in
959 * that case.
960 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200961 _PyUnicode_WSTR(unicode)[0] = 0;
962 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +0100963
Victor Stinner7931d9a2011-11-04 00:22:48 +0100964 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000965 return unicode;
966}
967
Victor Stinnerf42dc442011-10-02 23:33:16 +0200968static const char*
969unicode_kind_name(PyObject *unicode)
970{
Victor Stinner42dfd712011-10-03 14:41:45 +0200971 /* don't check consistency: unicode_kind_name() is called from
972 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200973 if (!PyUnicode_IS_COMPACT(unicode))
974 {
975 if (!PyUnicode_IS_READY(unicode))
976 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -0600977 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200978 {
979 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200980 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200981 return "legacy ascii";
982 else
983 return "legacy latin1";
984 case PyUnicode_2BYTE_KIND:
985 return "legacy UCS2";
986 case PyUnicode_4BYTE_KIND:
987 return "legacy UCS4";
988 default:
989 return "<legacy invalid kind>";
990 }
991 }
992 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -0600993 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +0200994 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200995 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200996 return "ascii";
997 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200998 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200999 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001000 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001001 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001002 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001003 default:
1004 return "<invalid compact kind>";
1005 }
1006}
1007
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001008#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001009/* Functions wrapping macros for use in debugger */
1010char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001011 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001012}
1013
1014void *_PyUnicode_compact_data(void *unicode) {
1015 return _PyUnicode_COMPACT_DATA(unicode);
1016}
1017void *_PyUnicode_data(void *unicode){
1018 printf("obj %p\n", unicode);
1019 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
1020 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
1021 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
1022 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
1023 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
1024 return PyUnicode_DATA(unicode);
1025}
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001026
1027void
1028_PyUnicode_Dump(PyObject *op)
1029{
1030 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001031 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1032 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
1033 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001034
Victor Stinnera849a4b2011-10-03 12:12:11 +02001035 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001036 {
1037 if (ascii->state.ascii)
1038 data = (ascii + 1);
1039 else
1040 data = (compact + 1);
1041 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001042 else
1043 data = unicode->data.any;
Victor Stinner293f3f52014-07-01 08:57:10 +02001044 printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
1045 unicode_kind_name(op), ascii->length);
Victor Stinner0d60e872011-10-23 19:47:19 +02001046
Victor Stinnera849a4b2011-10-03 12:12:11 +02001047 if (ascii->wstr == data)
1048 printf("shared ");
1049 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001050
Victor Stinnera3b334d2011-10-03 13:53:37 +02001051 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinner293f3f52014-07-01 08:57:10 +02001052 printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
Victor Stinnera849a4b2011-10-03 12:12:11 +02001053 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1054 printf("shared ");
Victor Stinner293f3f52014-07-01 08:57:10 +02001055 printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
1056 compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001057 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001058 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001059}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001060#endif
1061
1062PyObject *
1063PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1064{
1065 PyObject *obj;
1066 PyCompactUnicodeObject *unicode;
1067 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001068 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001069 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001070 Py_ssize_t char_size;
1071 Py_ssize_t struct_size;
1072
1073 /* Optimization for empty strings */
1074 if (size == 0 && unicode_empty != NULL) {
1075 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001076 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001077 }
1078
Victor Stinner9e9d6892011-10-04 01:02:02 +02001079 is_ascii = 0;
1080 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001081 struct_size = sizeof(PyCompactUnicodeObject);
1082 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001083 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001084 char_size = 1;
1085 is_ascii = 1;
1086 struct_size = sizeof(PyASCIIObject);
1087 }
1088 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001089 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001090 char_size = 1;
1091 }
1092 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001093 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001094 char_size = 2;
1095 if (sizeof(wchar_t) == 2)
1096 is_sharing = 1;
1097 }
1098 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001099 if (maxchar > MAX_UNICODE) {
1100 PyErr_SetString(PyExc_SystemError,
1101 "invalid maximum character passed to PyUnicode_New");
1102 return NULL;
1103 }
Victor Stinner8f825062012-04-27 13:55:39 +02001104 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001105 char_size = 4;
1106 if (sizeof(wchar_t) == 4)
1107 is_sharing = 1;
1108 }
1109
1110 /* Ensure we won't overflow the size. */
1111 if (size < 0) {
1112 PyErr_SetString(PyExc_SystemError,
1113 "Negative size passed to PyUnicode_New");
1114 return NULL;
1115 }
1116 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1117 return PyErr_NoMemory();
1118
1119 /* Duplicated allocation code from _PyObject_New() instead of a call to
1120 * PyObject_New() so we are able to allocate space for the object and
1121 * it's data buffer.
1122 */
1123 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1124 if (obj == NULL)
1125 return PyErr_NoMemory();
1126 obj = PyObject_INIT(obj, &PyUnicode_Type);
1127 if (obj == NULL)
1128 return NULL;
1129
1130 unicode = (PyCompactUnicodeObject *)obj;
1131 if (is_ascii)
1132 data = ((PyASCIIObject*)obj) + 1;
1133 else
1134 data = unicode + 1;
1135 _PyUnicode_LENGTH(unicode) = size;
1136 _PyUnicode_HASH(unicode) = -1;
1137 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001138 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001139 _PyUnicode_STATE(unicode).compact = 1;
1140 _PyUnicode_STATE(unicode).ready = 1;
1141 _PyUnicode_STATE(unicode).ascii = is_ascii;
1142 if (is_ascii) {
1143 ((char*)data)[size] = 0;
1144 _PyUnicode_WSTR(unicode) = NULL;
1145 }
Victor Stinner8f825062012-04-27 13:55:39 +02001146 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001147 ((char*)data)[size] = 0;
1148 _PyUnicode_WSTR(unicode) = NULL;
1149 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001150 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001151 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001152 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001153 else {
1154 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001155 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001156 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001157 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001158 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001159 ((Py_UCS4*)data)[size] = 0;
1160 if (is_sharing) {
1161 _PyUnicode_WSTR_LENGTH(unicode) = size;
1162 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1163 }
1164 else {
1165 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1166 _PyUnicode_WSTR(unicode) = NULL;
1167 }
1168 }
Victor Stinner8f825062012-04-27 13:55:39 +02001169#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001170 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001171#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001172 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001173 return obj;
1174}
1175
1176#if SIZEOF_WCHAR_T == 2
1177/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1178 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001179 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001180
1181 This function assumes that unicode can hold one more code point than wstr
1182 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001183static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001184unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001185 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001186{
1187 const wchar_t *iter;
1188 Py_UCS4 *ucs4_out;
1189
Victor Stinner910337b2011-10-03 03:20:16 +02001190 assert(unicode != NULL);
1191 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001192 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1193 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1194
1195 for (iter = begin; iter < end; ) {
1196 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1197 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001198 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1199 && (iter+1) < end
1200 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001201 {
Victor Stinner551ac952011-11-29 22:58:13 +01001202 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001203 iter += 2;
1204 }
1205 else {
1206 *ucs4_out++ = *iter;
1207 iter++;
1208 }
1209 }
1210 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1211 _PyUnicode_GET_LENGTH(unicode)));
1212
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001213}
1214#endif
1215
Victor Stinnercd9950f2011-10-02 00:34:53 +02001216static int
Victor Stinner488fa492011-12-12 00:01:39 +01001217unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001218{
Victor Stinner488fa492011-12-12 00:01:39 +01001219 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001220 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001221 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001222 return -1;
1223 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001224 return 0;
1225}
1226
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001227static int
1228_copy_characters(PyObject *to, Py_ssize_t to_start,
1229 PyObject *from, Py_ssize_t from_start,
1230 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001231{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001232 unsigned int from_kind, to_kind;
1233 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001234
Victor Stinneree4544c2012-05-09 22:24:08 +02001235 assert(0 <= how_many);
1236 assert(0 <= from_start);
1237 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001238 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001239 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001240 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001241
Victor Stinnerd3f08822012-05-29 12:57:52 +02001242 assert(PyUnicode_Check(to));
1243 assert(PyUnicode_IS_READY(to));
1244 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1245
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001246 if (how_many == 0)
1247 return 0;
1248
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001249 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001250 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001251 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001252 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001253
Victor Stinnerf1852262012-06-16 16:38:26 +02001254#ifdef Py_DEBUG
1255 if (!check_maxchar
1256 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1257 {
1258 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1259 Py_UCS4 ch;
1260 Py_ssize_t i;
1261 for (i=0; i < how_many; i++) {
1262 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1263 assert(ch <= to_maxchar);
1264 }
1265 }
1266#endif
1267
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001268 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001269 if (check_maxchar
1270 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1271 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001272 /* Writing Latin-1 characters into an ASCII string requires to
1273 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001274 Py_UCS4 max_char;
1275 max_char = ucs1lib_find_max_char(from_data,
1276 (Py_UCS1*)from_data + how_many);
1277 if (max_char >= 128)
1278 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001279 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001280 Py_MEMCPY((char*)to_data + to_kind * to_start,
1281 (char*)from_data + from_kind * from_start,
1282 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001283 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001284 else if (from_kind == PyUnicode_1BYTE_KIND
1285 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001286 {
1287 _PyUnicode_CONVERT_BYTES(
1288 Py_UCS1, Py_UCS2,
1289 PyUnicode_1BYTE_DATA(from) + from_start,
1290 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1291 PyUnicode_2BYTE_DATA(to) + to_start
1292 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001293 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001294 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001295 && to_kind == PyUnicode_4BYTE_KIND)
1296 {
1297 _PyUnicode_CONVERT_BYTES(
1298 Py_UCS1, Py_UCS4,
1299 PyUnicode_1BYTE_DATA(from) + from_start,
1300 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1301 PyUnicode_4BYTE_DATA(to) + to_start
1302 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001303 }
1304 else if (from_kind == PyUnicode_2BYTE_KIND
1305 && to_kind == PyUnicode_4BYTE_KIND)
1306 {
1307 _PyUnicode_CONVERT_BYTES(
1308 Py_UCS2, Py_UCS4,
1309 PyUnicode_2BYTE_DATA(from) + from_start,
1310 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1311 PyUnicode_4BYTE_DATA(to) + to_start
1312 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001313 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001314 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001315 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1316
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001317 if (!check_maxchar) {
1318 if (from_kind == PyUnicode_2BYTE_KIND
1319 && to_kind == PyUnicode_1BYTE_KIND)
1320 {
1321 _PyUnicode_CONVERT_BYTES(
1322 Py_UCS2, Py_UCS1,
1323 PyUnicode_2BYTE_DATA(from) + from_start,
1324 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1325 PyUnicode_1BYTE_DATA(to) + to_start
1326 );
1327 }
1328 else if (from_kind == PyUnicode_4BYTE_KIND
1329 && to_kind == PyUnicode_1BYTE_KIND)
1330 {
1331 _PyUnicode_CONVERT_BYTES(
1332 Py_UCS4, Py_UCS1,
1333 PyUnicode_4BYTE_DATA(from) + from_start,
1334 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1335 PyUnicode_1BYTE_DATA(to) + to_start
1336 );
1337 }
1338 else if (from_kind == PyUnicode_4BYTE_KIND
1339 && to_kind == PyUnicode_2BYTE_KIND)
1340 {
1341 _PyUnicode_CONVERT_BYTES(
1342 Py_UCS4, Py_UCS2,
1343 PyUnicode_4BYTE_DATA(from) + from_start,
1344 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1345 PyUnicode_2BYTE_DATA(to) + to_start
1346 );
1347 }
1348 else {
1349 assert(0);
1350 return -1;
1351 }
1352 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001353 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001354 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001355 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001356 Py_ssize_t i;
1357
Victor Stinnera0702ab2011-09-29 14:14:38 +02001358 for (i=0; i < how_many; i++) {
1359 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001360 if (ch > to_maxchar)
1361 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001362 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1363 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001364 }
1365 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001366 return 0;
1367}
1368
Victor Stinnerd3f08822012-05-29 12:57:52 +02001369void
1370_PyUnicode_FastCopyCharacters(
1371 PyObject *to, Py_ssize_t to_start,
1372 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001373{
1374 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1375}
1376
1377Py_ssize_t
1378PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1379 PyObject *from, Py_ssize_t from_start,
1380 Py_ssize_t how_many)
1381{
1382 int err;
1383
1384 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1385 PyErr_BadInternalCall();
1386 return -1;
1387 }
1388
Benjamin Petersonbac79492012-01-14 13:34:47 -05001389 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001390 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001391 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001392 return -1;
1393
Victor Stinnerd3f08822012-05-29 12:57:52 +02001394 if (from_start < 0) {
1395 PyErr_SetString(PyExc_IndexError, "string index out of range");
1396 return -1;
1397 }
1398 if (to_start < 0) {
1399 PyErr_SetString(PyExc_IndexError, "string index out of range");
1400 return -1;
1401 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001402 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1403 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1404 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001405 "Cannot write %zi characters at %zi "
1406 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001407 how_many, to_start, PyUnicode_GET_LENGTH(to));
1408 return -1;
1409 }
1410
1411 if (how_many == 0)
1412 return 0;
1413
Victor Stinner488fa492011-12-12 00:01:39 +01001414 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001415 return -1;
1416
1417 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1418 if (err) {
1419 PyErr_Format(PyExc_SystemError,
1420 "Cannot copy %s characters "
1421 "into a string of %s characters",
1422 unicode_kind_name(from),
1423 unicode_kind_name(to));
1424 return -1;
1425 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001426 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001427}
1428
Victor Stinner17222162011-09-28 22:15:37 +02001429/* Find the maximum code point and count the number of surrogate pairs so a
1430 correct string length can be computed before converting a string to UCS4.
1431 This function counts single surrogates as a character and not as a pair.
1432
1433 Return 0 on success, or -1 on error. */
1434static int
1435find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1436 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001437{
1438 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001439 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001440
Victor Stinnerc53be962011-10-02 21:33:54 +02001441 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001442 *num_surrogates = 0;
1443 *maxchar = 0;
1444
1445 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001446#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001447 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1448 && (iter+1) < end
1449 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1450 {
1451 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1452 ++(*num_surrogates);
1453 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001454 }
1455 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001456#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001457 {
1458 ch = *iter;
1459 iter++;
1460 }
1461 if (ch > *maxchar) {
1462 *maxchar = ch;
1463 if (*maxchar > MAX_UNICODE) {
1464 PyErr_Format(PyExc_ValueError,
1465 "character U+%x is not in range [U+0000; U+10ffff]",
1466 ch);
1467 return -1;
1468 }
1469 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001470 }
1471 return 0;
1472}
1473
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001474int
1475_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001476{
1477 wchar_t *end;
1478 Py_UCS4 maxchar = 0;
1479 Py_ssize_t num_surrogates;
1480#if SIZEOF_WCHAR_T == 2
1481 Py_ssize_t length_wo_surrogates;
1482#endif
1483
Georg Brandl7597add2011-10-05 16:36:47 +02001484 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001485 strings were created using _PyObject_New() and where no canonical
1486 representation (the str field) has been set yet aka strings
1487 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001488 assert(_PyUnicode_CHECK(unicode));
1489 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001490 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001491 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001492 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001493 /* Actually, it should neither be interned nor be anything else: */
1494 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001495
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001496 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001497 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001498 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001499 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001500
1501 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001502 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1503 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001504 PyErr_NoMemory();
1505 return -1;
1506 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001507 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001508 _PyUnicode_WSTR(unicode), end,
1509 PyUnicode_1BYTE_DATA(unicode));
1510 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1511 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1512 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1513 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001514 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001515 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001516 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001517 }
1518 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001519 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001520 _PyUnicode_UTF8(unicode) = NULL;
1521 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001522 }
1523 PyObject_FREE(_PyUnicode_WSTR(unicode));
1524 _PyUnicode_WSTR(unicode) = NULL;
1525 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1526 }
1527 /* In this case we might have to convert down from 4-byte native
1528 wchar_t to 2-byte unicode. */
1529 else if (maxchar < 65536) {
1530 assert(num_surrogates == 0 &&
1531 "FindMaxCharAndNumSurrogatePairs() messed up");
1532
Victor Stinner506f5922011-09-28 22:34:18 +02001533#if SIZEOF_WCHAR_T == 2
1534 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001535 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001536 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1537 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1538 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001539 _PyUnicode_UTF8(unicode) = NULL;
1540 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001541#else
1542 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001543 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001544 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001545 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001546 PyErr_NoMemory();
1547 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001548 }
Victor Stinner506f5922011-09-28 22:34:18 +02001549 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1550 _PyUnicode_WSTR(unicode), end,
1551 PyUnicode_2BYTE_DATA(unicode));
1552 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1553 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1554 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001555 _PyUnicode_UTF8(unicode) = NULL;
1556 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001557 PyObject_FREE(_PyUnicode_WSTR(unicode));
1558 _PyUnicode_WSTR(unicode) = NULL;
1559 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1560#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001561 }
1562 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1563 else {
1564#if SIZEOF_WCHAR_T == 2
1565 /* in case the native representation is 2-bytes, we need to allocate a
1566 new normalized 4-byte version. */
1567 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Serhiy Storchakae55181f2015-02-20 21:34:06 +02001568 if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) {
1569 PyErr_NoMemory();
1570 return -1;
1571 }
Victor Stinnerc3c74152011-10-02 20:39:55 +02001572 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1573 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001574 PyErr_NoMemory();
1575 return -1;
1576 }
1577 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1578 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001579 _PyUnicode_UTF8(unicode) = NULL;
1580 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001581 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1582 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001583 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001584 PyObject_FREE(_PyUnicode_WSTR(unicode));
1585 _PyUnicode_WSTR(unicode) = NULL;
1586 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1587#else
1588 assert(num_surrogates == 0);
1589
Victor Stinnerc3c74152011-10-02 20:39:55 +02001590 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001591 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001592 _PyUnicode_UTF8(unicode) = NULL;
1593 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001594 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1595#endif
1596 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1597 }
1598 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001599 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001600 return 0;
1601}
1602
Alexander Belopolsky40018472011-02-26 01:02:56 +00001603static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001604unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001605{
Walter Dörwald16807132007-05-25 13:52:07 +00001606 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001607 case SSTATE_NOT_INTERNED:
1608 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001609
Benjamin Peterson29060642009-01-31 22:14:21 +00001610 case SSTATE_INTERNED_MORTAL:
1611 /* revive dead object temporarily for DelItem */
1612 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001613 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001614 Py_FatalError(
1615 "deletion of interned string failed");
1616 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001617
Benjamin Peterson29060642009-01-31 22:14:21 +00001618 case SSTATE_INTERNED_IMMORTAL:
1619 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001620
Benjamin Peterson29060642009-01-31 22:14:21 +00001621 default:
1622 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001623 }
1624
Victor Stinner03490912011-10-03 23:45:12 +02001625 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001626 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001627 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001628 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001629 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1630 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001631
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001632 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001633}
1634
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001635#ifdef Py_DEBUG
1636static int
1637unicode_is_singleton(PyObject *unicode)
1638{
1639 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1640 if (unicode == unicode_empty)
1641 return 1;
1642 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1643 {
1644 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1645 if (ch < 256 && unicode_latin1[ch] == unicode)
1646 return 1;
1647 }
1648 return 0;
1649}
1650#endif
1651
Alexander Belopolsky40018472011-02-26 01:02:56 +00001652static int
Victor Stinner488fa492011-12-12 00:01:39 +01001653unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001654{
Victor Stinner488fa492011-12-12 00:01:39 +01001655 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001656 if (Py_REFCNT(unicode) != 1)
1657 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001658 if (_PyUnicode_HASH(unicode) != -1)
1659 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001660 if (PyUnicode_CHECK_INTERNED(unicode))
1661 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001662 if (!PyUnicode_CheckExact(unicode))
1663 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001664#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001665 /* singleton refcount is greater than 1 */
1666 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001667#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001668 return 1;
1669}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001670
Victor Stinnerfe226c02011-10-03 03:52:20 +02001671static int
1672unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1673{
1674 PyObject *unicode;
1675 Py_ssize_t old_length;
1676
1677 assert(p_unicode != NULL);
1678 unicode = *p_unicode;
1679
1680 assert(unicode != NULL);
1681 assert(PyUnicode_Check(unicode));
1682 assert(0 <= length);
1683
Victor Stinner910337b2011-10-03 03:20:16 +02001684 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001685 old_length = PyUnicode_WSTR_LENGTH(unicode);
1686 else
1687 old_length = PyUnicode_GET_LENGTH(unicode);
1688 if (old_length == length)
1689 return 0;
1690
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001691 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001692 _Py_INCREF_UNICODE_EMPTY();
1693 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001694 return -1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001695 Py_DECREF(*p_unicode);
1696 *p_unicode = unicode_empty;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001697 return 0;
1698 }
1699
Victor Stinner488fa492011-12-12 00:01:39 +01001700 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001701 PyObject *copy = resize_copy(unicode, length);
1702 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001703 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001704 Py_DECREF(*p_unicode);
1705 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001706 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001707 }
1708
Victor Stinnerfe226c02011-10-03 03:52:20 +02001709 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001710 PyObject *new_unicode = resize_compact(unicode, length);
1711 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001712 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001713 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001714 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001715 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001716 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001717}
1718
Alexander Belopolsky40018472011-02-26 01:02:56 +00001719int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001720PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001721{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001722 PyObject *unicode;
1723 if (p_unicode == NULL) {
1724 PyErr_BadInternalCall();
1725 return -1;
1726 }
1727 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001728 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001729 {
1730 PyErr_BadInternalCall();
1731 return -1;
1732 }
1733 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001734}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001735
Victor Stinnerc5166102012-02-22 13:55:02 +01001736/* Copy a ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001737
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001738 WARNING: The function doesn't copy the terminating null character and
1739 doesn't check the maximum character (may write a latin1 character in an
1740 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001741static void
1742unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1743 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001744{
1745 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1746 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001747 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001748
1749 switch (kind) {
1750 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001751 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001752#ifdef Py_DEBUG
1753 if (PyUnicode_IS_ASCII(unicode)) {
1754 Py_UCS4 maxchar = ucs1lib_find_max_char(
1755 (const Py_UCS1*)str,
1756 (const Py_UCS1*)str + len);
1757 assert(maxchar < 128);
1758 }
1759#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001760 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001761 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001762 }
1763 case PyUnicode_2BYTE_KIND: {
1764 Py_UCS2 *start = (Py_UCS2 *)data + index;
1765 Py_UCS2 *ucs2 = start;
1766 assert(index <= PyUnicode_GET_LENGTH(unicode));
1767
Victor Stinner184252a2012-06-16 02:57:41 +02001768 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001769 *ucs2 = (Py_UCS2)*str;
1770
1771 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001772 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001773 }
1774 default: {
1775 Py_UCS4 *start = (Py_UCS4 *)data + index;
1776 Py_UCS4 *ucs4 = start;
1777 assert(kind == PyUnicode_4BYTE_KIND);
1778 assert(index <= PyUnicode_GET_LENGTH(unicode));
1779
Victor Stinner184252a2012-06-16 02:57:41 +02001780 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001781 *ucs4 = (Py_UCS4)*str;
1782
1783 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001784 }
1785 }
1786}
1787
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001788static PyObject*
1789get_latin1_char(unsigned char ch)
1790{
Victor Stinnera464fc12011-10-02 20:39:30 +02001791 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001792 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001793 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001794 if (!unicode)
1795 return NULL;
1796 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001797 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001798 unicode_latin1[ch] = unicode;
1799 }
1800 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001801 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001802}
1803
Victor Stinner985a82a2014-01-03 12:53:47 +01001804static PyObject*
1805unicode_char(Py_UCS4 ch)
1806{
1807 PyObject *unicode;
1808
1809 assert(ch <= MAX_UNICODE);
1810
Victor Stinnerf3b46b42014-01-03 13:16:00 +01001811 if (ch < 256)
1812 return get_latin1_char(ch);
1813
Victor Stinner985a82a2014-01-03 12:53:47 +01001814 unicode = PyUnicode_New(1, ch);
1815 if (unicode == NULL)
1816 return NULL;
1817 switch (PyUnicode_KIND(unicode)) {
1818 case PyUnicode_1BYTE_KIND:
1819 PyUnicode_1BYTE_DATA(unicode)[0] = (Py_UCS1)ch;
1820 break;
1821 case PyUnicode_2BYTE_KIND:
1822 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
1823 break;
1824 default:
1825 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1826 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1827 }
1828 assert(_PyUnicode_CheckConsistency(unicode, 1));
1829 return unicode;
1830}
1831
Alexander Belopolsky40018472011-02-26 01:02:56 +00001832PyObject *
1833PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001834{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001835 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001836 Py_UCS4 maxchar = 0;
1837 Py_ssize_t num_surrogates;
1838
1839 if (u == NULL)
1840 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001841
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001842 /* If the Unicode data is known at construction time, we can apply
1843 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001844
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001845 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02001846 if (size == 0)
1847 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00001848
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001849 /* Single character Unicode objects in the Latin-1 range are
1850 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001851 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001852 return get_latin1_char((unsigned char)*u);
1853
1854 /* If not empty and not single character, copy the Unicode data
1855 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001856 if (find_maxchar_surrogates(u, u + size,
1857 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001858 return NULL;
1859
Victor Stinner8faf8212011-12-08 22:14:11 +01001860 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001861 if (!unicode)
1862 return NULL;
1863
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001864 switch (PyUnicode_KIND(unicode)) {
1865 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001866 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001867 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1868 break;
1869 case PyUnicode_2BYTE_KIND:
1870#if Py_UNICODE_SIZE == 2
1871 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1872#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001873 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001874 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1875#endif
1876 break;
1877 case PyUnicode_4BYTE_KIND:
1878#if SIZEOF_WCHAR_T == 2
1879 /* This is the only case which has to process surrogates, thus
1880 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001881 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001882#else
1883 assert(num_surrogates == 0);
1884 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1885#endif
1886 break;
1887 default:
1888 assert(0 && "Impossible state");
1889 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001890
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001891 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001892}
1893
Alexander Belopolsky40018472011-02-26 01:02:56 +00001894PyObject *
1895PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001896{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001897 if (size < 0) {
1898 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001899 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001900 return NULL;
1901 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001902 if (u != NULL)
1903 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1904 else
1905 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001906}
1907
Alexander Belopolsky40018472011-02-26 01:02:56 +00001908PyObject *
1909PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001910{
1911 size_t size = strlen(u);
1912 if (size > PY_SSIZE_T_MAX) {
1913 PyErr_SetString(PyExc_OverflowError, "input too long");
1914 return NULL;
1915 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001916 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001917}
1918
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001919PyObject *
1920_PyUnicode_FromId(_Py_Identifier *id)
1921{
1922 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01001923 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1924 strlen(id->string),
1925 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001926 if (!id->object)
1927 return NULL;
1928 PyUnicode_InternInPlace(&id->object);
1929 assert(!id->next);
1930 id->next = static_strings;
1931 static_strings = id;
1932 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001933 return id->object;
1934}
1935
1936void
1937_PyUnicode_ClearStaticStrings()
1938{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001939 _Py_Identifier *tmp, *s = static_strings;
1940 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02001941 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001942 tmp = s->next;
1943 s->next = NULL;
1944 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001945 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001946 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001947}
1948
Benjamin Peterson0df54292012-03-26 14:50:32 -04001949/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001950
Victor Stinnerd3f08822012-05-29 12:57:52 +02001951PyObject*
1952_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001953{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001954 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01001955 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001956 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001957#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001958 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001959#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001960 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001961 }
Victor Stinner785938e2011-12-11 20:09:03 +01001962 unicode = PyUnicode_New(size, 127);
1963 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001964 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001965 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1966 assert(_PyUnicode_CheckConsistency(unicode, 1));
1967 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001968}
1969
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001970static Py_UCS4
1971kind_maxchar_limit(unsigned int kind)
1972{
Benjamin Petersonead6b532011-12-20 17:23:42 -06001973 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001974 case PyUnicode_1BYTE_KIND:
1975 return 0x80;
1976 case PyUnicode_2BYTE_KIND:
1977 return 0x100;
1978 case PyUnicode_4BYTE_KIND:
1979 return 0x10000;
1980 default:
1981 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001982 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001983 }
1984}
1985
Victor Stinnere6abb482012-05-02 01:15:40 +02001986Py_LOCAL_INLINE(Py_UCS4)
1987align_maxchar(Py_UCS4 maxchar)
1988{
1989 if (maxchar <= 127)
1990 return 127;
1991 else if (maxchar <= 255)
1992 return 255;
1993 else if (maxchar <= 65535)
1994 return 65535;
1995 else
1996 return MAX_UNICODE;
1997}
1998
Victor Stinner702c7342011-10-05 13:50:52 +02001999static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002000_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00002001{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002002 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002003 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002004
Serhiy Storchaka678db842013-01-26 12:16:36 +02002005 if (size == 0)
2006 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002007 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002008 if (size == 1)
2009 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002010
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002011 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002012 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002013 if (!res)
2014 return NULL;
2015 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002016 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002017 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00002018}
2019
Victor Stinnere57b1c02011-09-28 22:20:48 +02002020static PyObject*
2021_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002022{
2023 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002024 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002025
Serhiy Storchaka678db842013-01-26 12:16:36 +02002026 if (size == 0)
2027 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002028 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002029 if (size == 1)
2030 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002031
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002032 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002033 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002034 if (!res)
2035 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002036 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002037 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002038 else {
2039 _PyUnicode_CONVERT_BYTES(
2040 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2041 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002042 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002043 return res;
2044}
2045
Victor Stinnere57b1c02011-09-28 22:20:48 +02002046static PyObject*
2047_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002048{
2049 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002050 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002051
Serhiy Storchaka678db842013-01-26 12:16:36 +02002052 if (size == 0)
2053 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002054 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002055 if (size == 1)
2056 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002057
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002058 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002059 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002060 if (!res)
2061 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002062 if (max_char < 256)
2063 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2064 PyUnicode_1BYTE_DATA(res));
2065 else if (max_char < 0x10000)
2066 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2067 PyUnicode_2BYTE_DATA(res));
2068 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002069 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002070 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002071 return res;
2072}
2073
2074PyObject*
2075PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2076{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002077 if (size < 0) {
2078 PyErr_SetString(PyExc_ValueError, "size must be positive");
2079 return NULL;
2080 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002081 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002082 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002083 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002084 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002085 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002086 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002087 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002088 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002089 PyErr_SetString(PyExc_SystemError, "invalid kind");
2090 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002091 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002092}
2093
Victor Stinnerece58de2012-04-23 23:36:38 +02002094Py_UCS4
2095_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2096{
2097 enum PyUnicode_Kind kind;
2098 void *startptr, *endptr;
2099
2100 assert(PyUnicode_IS_READY(unicode));
2101 assert(0 <= start);
2102 assert(end <= PyUnicode_GET_LENGTH(unicode));
2103 assert(start <= end);
2104
2105 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2106 return PyUnicode_MAX_CHAR_VALUE(unicode);
2107
2108 if (start == end)
2109 return 127;
2110
Victor Stinner94d558b2012-04-27 22:26:58 +02002111 if (PyUnicode_IS_ASCII(unicode))
2112 return 127;
2113
Victor Stinnerece58de2012-04-23 23:36:38 +02002114 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002115 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002116 endptr = (char *)startptr + end * kind;
2117 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002118 switch(kind) {
2119 case PyUnicode_1BYTE_KIND:
2120 return ucs1lib_find_max_char(startptr, endptr);
2121 case PyUnicode_2BYTE_KIND:
2122 return ucs2lib_find_max_char(startptr, endptr);
2123 case PyUnicode_4BYTE_KIND:
2124 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002125 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002126 assert(0);
2127 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002128 }
2129}
2130
Victor Stinner25a4b292011-10-06 12:31:55 +02002131/* Ensure that a string uses the most efficient storage, if it is not the
2132 case: create a new string with of the right kind. Write NULL into *p_unicode
2133 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002134static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002135unicode_adjust_maxchar(PyObject **p_unicode)
2136{
2137 PyObject *unicode, *copy;
2138 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002139 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002140 unsigned int kind;
2141
2142 assert(p_unicode != NULL);
2143 unicode = *p_unicode;
2144 assert(PyUnicode_IS_READY(unicode));
2145 if (PyUnicode_IS_ASCII(unicode))
2146 return;
2147
2148 len = PyUnicode_GET_LENGTH(unicode);
2149 kind = PyUnicode_KIND(unicode);
2150 if (kind == PyUnicode_1BYTE_KIND) {
2151 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002152 max_char = ucs1lib_find_max_char(u, u + len);
2153 if (max_char >= 128)
2154 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002155 }
2156 else if (kind == PyUnicode_2BYTE_KIND) {
2157 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002158 max_char = ucs2lib_find_max_char(u, u + len);
2159 if (max_char >= 256)
2160 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002161 }
2162 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002163 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002164 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002165 max_char = ucs4lib_find_max_char(u, u + len);
2166 if (max_char >= 0x10000)
2167 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002168 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002169 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002170 if (copy != NULL)
2171 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002172 Py_DECREF(unicode);
2173 *p_unicode = copy;
2174}
2175
Victor Stinner034f6cf2011-09-30 02:26:44 +02002176PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002177_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002178{
Victor Stinner87af4f22011-11-21 23:03:47 +01002179 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002180 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002181
Victor Stinner034f6cf2011-09-30 02:26:44 +02002182 if (!PyUnicode_Check(unicode)) {
2183 PyErr_BadInternalCall();
2184 return NULL;
2185 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002186 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002187 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002188
Victor Stinner87af4f22011-11-21 23:03:47 +01002189 length = PyUnicode_GET_LENGTH(unicode);
2190 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002191 if (!copy)
2192 return NULL;
2193 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2194
Victor Stinner87af4f22011-11-21 23:03:47 +01002195 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2196 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002197 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002198 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002199}
2200
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002201
Victor Stinnerbc603d12011-10-02 01:00:40 +02002202/* Widen Unicode objects to larger buffers. Don't write terminating null
2203 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002204
2205void*
2206_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2207{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002208 Py_ssize_t len;
2209 void *result;
2210 unsigned int skind;
2211
Benjamin Petersonbac79492012-01-14 13:34:47 -05002212 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002213 return NULL;
2214
2215 len = PyUnicode_GET_LENGTH(s);
2216 skind = PyUnicode_KIND(s);
2217 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002218 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002219 return NULL;
2220 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002221 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002222 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002223 result = PyMem_New(Py_UCS2, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002224 if (!result)
2225 return PyErr_NoMemory();
2226 assert(skind == PyUnicode_1BYTE_KIND);
2227 _PyUnicode_CONVERT_BYTES(
2228 Py_UCS1, Py_UCS2,
2229 PyUnicode_1BYTE_DATA(s),
2230 PyUnicode_1BYTE_DATA(s) + len,
2231 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002232 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002233 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002234 result = PyMem_New(Py_UCS4, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002235 if (!result)
2236 return PyErr_NoMemory();
2237 if (skind == PyUnicode_2BYTE_KIND) {
2238 _PyUnicode_CONVERT_BYTES(
2239 Py_UCS2, Py_UCS4,
2240 PyUnicode_2BYTE_DATA(s),
2241 PyUnicode_2BYTE_DATA(s) + len,
2242 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002243 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002244 else {
2245 assert(skind == PyUnicode_1BYTE_KIND);
2246 _PyUnicode_CONVERT_BYTES(
2247 Py_UCS1, Py_UCS4,
2248 PyUnicode_1BYTE_DATA(s),
2249 PyUnicode_1BYTE_DATA(s) + len,
2250 result);
2251 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002252 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002253 default:
2254 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002255 }
Victor Stinner01698042011-10-04 00:04:26 +02002256 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002257 return NULL;
2258}
2259
2260static Py_UCS4*
2261as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2262 int copy_null)
2263{
2264 int kind;
2265 void *data;
2266 Py_ssize_t len, targetlen;
2267 if (PyUnicode_READY(string) == -1)
2268 return NULL;
2269 kind = PyUnicode_KIND(string);
2270 data = PyUnicode_DATA(string);
2271 len = PyUnicode_GET_LENGTH(string);
2272 targetlen = len;
2273 if (copy_null)
2274 targetlen++;
2275 if (!target) {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002276 target = PyMem_New(Py_UCS4, targetlen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002277 if (!target) {
2278 PyErr_NoMemory();
2279 return NULL;
2280 }
2281 }
2282 else {
2283 if (targetsize < targetlen) {
2284 PyErr_Format(PyExc_SystemError,
2285 "string is longer than the buffer");
2286 if (copy_null && 0 < targetsize)
2287 target[0] = 0;
2288 return NULL;
2289 }
2290 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002291 if (kind == PyUnicode_1BYTE_KIND) {
2292 Py_UCS1 *start = (Py_UCS1 *) data;
2293 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002294 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002295 else if (kind == PyUnicode_2BYTE_KIND) {
2296 Py_UCS2 *start = (Py_UCS2 *) data;
2297 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2298 }
2299 else {
2300 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002301 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002302 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002303 if (copy_null)
2304 target[len] = 0;
2305 return target;
2306}
2307
2308Py_UCS4*
2309PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2310 int copy_null)
2311{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002312 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002313 PyErr_BadInternalCall();
2314 return NULL;
2315 }
2316 return as_ucs4(string, target, targetsize, copy_null);
2317}
2318
2319Py_UCS4*
2320PyUnicode_AsUCS4Copy(PyObject *string)
2321{
2322 return as_ucs4(string, NULL, 0, 1);
2323}
2324
2325#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002326
Alexander Belopolsky40018472011-02-26 01:02:56 +00002327PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002328PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002329{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002330 if (w == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00002331 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02002332 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson29060642009-01-31 22:14:21 +00002333 PyErr_BadInternalCall();
2334 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002335 }
2336
Martin v. Löwis790465f2008-04-05 20:41:37 +00002337 if (size == -1) {
2338 size = wcslen(w);
2339 }
2340
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002341 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002342}
2343
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002344#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002345
Victor Stinner15a11362012-10-06 23:48:20 +02002346/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002347 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2348 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2349#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002350
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002351static int
2352unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2353 Py_ssize_t width, Py_ssize_t precision)
2354{
2355 Py_ssize_t length, fill, arglen;
2356 Py_UCS4 maxchar;
2357
2358 if (PyUnicode_READY(str) == -1)
2359 return -1;
2360
2361 length = PyUnicode_GET_LENGTH(str);
2362 if ((precision == -1 || precision >= length)
2363 && width <= length)
2364 return _PyUnicodeWriter_WriteStr(writer, str);
2365
2366 if (precision != -1)
2367 length = Py_MIN(precision, length);
2368
2369 arglen = Py_MAX(length, width);
2370 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2371 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2372 else
2373 maxchar = writer->maxchar;
2374
2375 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2376 return -1;
2377
2378 if (width > length) {
2379 fill = width - length;
2380 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2381 return -1;
2382 writer->pos += fill;
2383 }
2384
2385 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2386 str, 0, length);
2387 writer->pos += length;
2388 return 0;
2389}
2390
2391static int
2392unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
2393 Py_ssize_t width, Py_ssize_t precision)
2394{
2395 /* UTF-8 */
2396 Py_ssize_t length;
2397 PyObject *unicode;
2398 int res;
2399
2400 length = strlen(str);
2401 if (precision != -1)
2402 length = Py_MIN(length, precision);
2403 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2404 if (unicode == NULL)
2405 return -1;
2406
2407 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2408 Py_DECREF(unicode);
2409 return res;
2410}
2411
Victor Stinner96865452011-03-01 23:44:09 +00002412static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002413unicode_fromformat_arg(_PyUnicodeWriter *writer,
2414 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002415{
Victor Stinnere215d962012-10-06 23:03:36 +02002416 const char *p;
2417 Py_ssize_t len;
2418 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002419 Py_ssize_t width;
2420 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002421 int longflag;
2422 int longlongflag;
2423 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002424 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002425
2426 p = f;
2427 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002428 zeropad = 0;
2429 if (*f == '0') {
2430 zeropad = 1;
2431 f++;
2432 }
Victor Stinner96865452011-03-01 23:44:09 +00002433
2434 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002435 width = -1;
2436 if (Py_ISDIGIT((unsigned)*f)) {
2437 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002438 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002439 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002440 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002441 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002442 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002443 return NULL;
2444 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002445 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002446 f++;
2447 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002448 }
2449 precision = -1;
2450 if (*f == '.') {
2451 f++;
2452 if (Py_ISDIGIT((unsigned)*f)) {
2453 precision = (*f - '0');
2454 f++;
2455 while (Py_ISDIGIT((unsigned)*f)) {
2456 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2457 PyErr_SetString(PyExc_ValueError,
2458 "precision too big");
2459 return NULL;
2460 }
2461 precision = (precision * 10) + (*f - '0');
2462 f++;
2463 }
2464 }
Victor Stinner96865452011-03-01 23:44:09 +00002465 if (*f == '%') {
2466 /* "%.3%s" => f points to "3" */
2467 f--;
2468 }
2469 }
2470 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002471 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002472 f--;
2473 }
Victor Stinner96865452011-03-01 23:44:09 +00002474
2475 /* Handle %ld, %lu, %lld and %llu. */
2476 longflag = 0;
2477 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002478 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002479 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002480 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002481 longflag = 1;
2482 ++f;
2483 }
2484#ifdef HAVE_LONG_LONG
2485 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002486 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002487 longlongflag = 1;
2488 f += 2;
2489 }
2490#endif
2491 }
2492 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002493 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002494 size_tflag = 1;
2495 ++f;
2496 }
Victor Stinnere215d962012-10-06 23:03:36 +02002497
2498 if (f[1] == '\0')
2499 writer->overallocate = 0;
2500
2501 switch (*f) {
2502 case 'c':
2503 {
2504 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002505 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002506 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002507 "character argument not in range(0x110000)");
2508 return NULL;
2509 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002510 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002511 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002512 break;
2513 }
2514
2515 case 'i':
2516 case 'd':
2517 case 'u':
2518 case 'x':
2519 {
2520 /* used by sprintf */
Victor Stinner15a11362012-10-06 23:48:20 +02002521 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002522 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002523
2524 if (*f == 'u') {
Victor Stinnere215d962012-10-06 23:03:36 +02002525 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002526 len = sprintf(buffer, "%lu",
Victor Stinnere215d962012-10-06 23:03:36 +02002527 va_arg(*vargs, unsigned long));
2528#ifdef HAVE_LONG_LONG
2529 else if (longlongflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002530 len = sprintf(buffer, "%" PY_FORMAT_LONG_LONG "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002531 va_arg(*vargs, unsigned PY_LONG_LONG));
2532#endif
2533 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002534 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002535 va_arg(*vargs, size_t));
2536 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002537 len = sprintf(buffer, "%u",
Victor Stinnere215d962012-10-06 23:03:36 +02002538 va_arg(*vargs, unsigned int));
2539 }
2540 else if (*f == 'x') {
Victor Stinner3aa979e2014-11-18 21:40:51 +01002541 len = sprintf(buffer, "%x", va_arg(*vargs, int));
Victor Stinnere215d962012-10-06 23:03:36 +02002542 }
2543 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002544 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002545 len = sprintf(buffer, "%li",
Victor Stinnere215d962012-10-06 23:03:36 +02002546 va_arg(*vargs, long));
2547#ifdef HAVE_LONG_LONG
2548 else if (longlongflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002549 len = sprintf(buffer, "%" PY_FORMAT_LONG_LONG "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002550 va_arg(*vargs, PY_LONG_LONG));
2551#endif
2552 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002553 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002554 va_arg(*vargs, Py_ssize_t));
2555 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002556 len = sprintf(buffer, "%i",
Victor Stinnere215d962012-10-06 23:03:36 +02002557 va_arg(*vargs, int));
2558 }
2559 assert(len >= 0);
2560
Victor Stinnere215d962012-10-06 23:03:36 +02002561 if (precision < len)
2562 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002563
2564 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002565 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2566 return NULL;
2567
Victor Stinnere215d962012-10-06 23:03:36 +02002568 if (width > precision) {
2569 Py_UCS4 fillchar;
2570 fill = width - precision;
2571 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002572 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2573 return NULL;
2574 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002575 }
Victor Stinner15a11362012-10-06 23:48:20 +02002576 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002577 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002578 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2579 return NULL;
2580 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002581 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002582
Victor Stinner4a587072013-11-19 12:54:53 +01002583 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2584 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002585 break;
2586 }
2587
2588 case 'p':
2589 {
2590 char number[MAX_LONG_LONG_CHARS];
2591
2592 len = sprintf(number, "%p", va_arg(*vargs, void*));
2593 assert(len >= 0);
2594
2595 /* %p is ill-defined: ensure leading 0x. */
2596 if (number[1] == 'X')
2597 number[1] = 'x';
2598 else if (number[1] != 'x') {
2599 memmove(number + 2, number,
2600 strlen(number) + 1);
2601 number[0] = '0';
2602 number[1] = 'x';
2603 len += 2;
2604 }
2605
Victor Stinner4a587072013-11-19 12:54:53 +01002606 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002607 return NULL;
2608 break;
2609 }
2610
2611 case 's':
2612 {
2613 /* UTF-8 */
2614 const char *s = va_arg(*vargs, const char*);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002615 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002616 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002617 break;
2618 }
2619
2620 case 'U':
2621 {
2622 PyObject *obj = va_arg(*vargs, PyObject *);
2623 assert(obj && _PyUnicode_CHECK(obj));
2624
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002625 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002626 return NULL;
2627 break;
2628 }
2629
2630 case 'V':
2631 {
2632 PyObject *obj = va_arg(*vargs, PyObject *);
2633 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002634 if (obj) {
2635 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002636 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002637 return NULL;
2638 }
2639 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002640 assert(str != NULL);
2641 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002642 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002643 }
2644 break;
2645 }
2646
2647 case 'S':
2648 {
2649 PyObject *obj = va_arg(*vargs, PyObject *);
2650 PyObject *str;
2651 assert(obj);
2652 str = PyObject_Str(obj);
2653 if (!str)
2654 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002655 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002656 Py_DECREF(str);
2657 return NULL;
2658 }
2659 Py_DECREF(str);
2660 break;
2661 }
2662
2663 case 'R':
2664 {
2665 PyObject *obj = va_arg(*vargs, PyObject *);
2666 PyObject *repr;
2667 assert(obj);
2668 repr = PyObject_Repr(obj);
2669 if (!repr)
2670 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002671 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002672 Py_DECREF(repr);
2673 return NULL;
2674 }
2675 Py_DECREF(repr);
2676 break;
2677 }
2678
2679 case 'A':
2680 {
2681 PyObject *obj = va_arg(*vargs, PyObject *);
2682 PyObject *ascii;
2683 assert(obj);
2684 ascii = PyObject_ASCII(obj);
2685 if (!ascii)
2686 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002687 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002688 Py_DECREF(ascii);
2689 return NULL;
2690 }
2691 Py_DECREF(ascii);
2692 break;
2693 }
2694
2695 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002696 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002697 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002698 break;
2699
2700 default:
2701 /* if we stumble upon an unknown formatting code, copy the rest
2702 of the format string to the output string. (we cannot just
2703 skip the code, since there's no way to know what's in the
2704 argument list) */
2705 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002706 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002707 return NULL;
2708 f = p+len;
2709 return f;
2710 }
2711
2712 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002713 return f;
2714}
2715
Walter Dörwaldd2034312007-05-18 16:29:38 +00002716PyObject *
2717PyUnicode_FromFormatV(const char *format, va_list vargs)
2718{
Victor Stinnere215d962012-10-06 23:03:36 +02002719 va_list vargs2;
2720 const char *f;
2721 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002722
Victor Stinner8f674cc2013-04-17 23:02:17 +02002723 _PyUnicodeWriter_Init(&writer);
2724 writer.min_length = strlen(format) + 100;
2725 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002726
2727 /* va_list may be an array (of 1 item) on some platforms (ex: AMD64).
2728 Copy it to be able to pass a reference to a subfunction. */
2729 Py_VA_COPY(vargs2, vargs);
2730
2731 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002732 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002733 f = unicode_fromformat_arg(&writer, f, &vargs2);
2734 if (f == NULL)
2735 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002736 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002737 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002738 const char *p;
2739 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002740
Victor Stinnere215d962012-10-06 23:03:36 +02002741 p = f;
2742 do
2743 {
2744 if ((unsigned char)*p > 127) {
2745 PyErr_Format(PyExc_ValueError,
2746 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2747 "string, got a non-ASCII byte: 0x%02x",
2748 (unsigned char)*p);
2749 return NULL;
2750 }
2751 p++;
2752 }
2753 while (*p != '\0' && *p != '%');
2754 len = p - f;
2755
2756 if (*p == '\0')
2757 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01002758
2759 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002760 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002761
2762 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002763 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002764 }
Victor Stinnere215d962012-10-06 23:03:36 +02002765 return _PyUnicodeWriter_Finish(&writer);
2766
2767 fail:
2768 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002769 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002770}
2771
Walter Dörwaldd2034312007-05-18 16:29:38 +00002772PyObject *
2773PyUnicode_FromFormat(const char *format, ...)
2774{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002775 PyObject* ret;
2776 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002777
2778#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002779 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002780#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002781 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002782#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002783 ret = PyUnicode_FromFormatV(format, vargs);
2784 va_end(vargs);
2785 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002786}
2787
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002788#ifdef HAVE_WCHAR_H
2789
Victor Stinner5593d8a2010-10-02 11:11:27 +00002790/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2791 convert a Unicode object to a wide character string.
2792
Victor Stinnerd88d9832011-09-06 02:00:05 +02002793 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002794 character) required to convert the unicode object. Ignore size argument.
2795
Victor Stinnerd88d9832011-09-06 02:00:05 +02002796 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002797 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002798 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002799static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002800unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002801 wchar_t *w,
2802 Py_ssize_t size)
2803{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002804 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002805 const wchar_t *wstr;
2806
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002807 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002808 if (wstr == NULL)
2809 return -1;
2810
Victor Stinner5593d8a2010-10-02 11:11:27 +00002811 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002812 if (size > res)
2813 size = res + 1;
2814 else
2815 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002816 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002817 return res;
2818 }
2819 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002820 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002821}
2822
2823Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002824PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002825 wchar_t *w,
2826 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002827{
2828 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002829 PyErr_BadInternalCall();
2830 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002831 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002832 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002833}
2834
Victor Stinner137c34c2010-09-29 10:25:54 +00002835wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002836PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002837 Py_ssize_t *size)
2838{
2839 wchar_t* buffer;
2840 Py_ssize_t buflen;
2841
2842 if (unicode == NULL) {
2843 PyErr_BadInternalCall();
2844 return NULL;
2845 }
2846
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002847 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002848 if (buflen == -1)
2849 return NULL;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002850 buffer = PyMem_NEW(wchar_t, buflen);
Victor Stinner137c34c2010-09-29 10:25:54 +00002851 if (buffer == NULL) {
2852 PyErr_NoMemory();
2853 return NULL;
2854 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002855 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02002856 if (buflen == -1) {
2857 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002858 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02002859 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00002860 if (size != NULL)
2861 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002862 return buffer;
2863}
2864
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002865#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002866
Alexander Belopolsky40018472011-02-26 01:02:56 +00002867PyObject *
2868PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002869{
Victor Stinner8faf8212011-12-08 22:14:11 +01002870 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002871 PyErr_SetString(PyExc_ValueError,
2872 "chr() arg not in range(0x110000)");
2873 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002874 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002875
Victor Stinner985a82a2014-01-03 12:53:47 +01002876 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002877}
2878
Alexander Belopolsky40018472011-02-26 01:02:56 +00002879PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002880PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002881{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002882 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002883 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002884 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05002885 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002886 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002887 Py_INCREF(obj);
2888 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002889 }
2890 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002891 /* For a Unicode subtype that's not a Unicode object,
2892 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002893 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002894 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002895 PyErr_Format(PyExc_TypeError,
2896 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002897 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002898 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002899}
2900
Alexander Belopolsky40018472011-02-26 01:02:56 +00002901PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002902PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002903 const char *encoding,
2904 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002905{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002906 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002907 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002908
Guido van Rossumd57fd912000-03-10 22:53:23 +00002909 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002910 PyErr_BadInternalCall();
2911 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002912 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002913
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002914 /* Decoding bytes objects is the most common case and should be fast */
2915 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002916 if (PyBytes_GET_SIZE(obj) == 0)
2917 _Py_RETURN_UNICODE_EMPTY();
2918 v = PyUnicode_Decode(
2919 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2920 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002921 return v;
2922 }
2923
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002924 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002925 PyErr_SetString(PyExc_TypeError,
2926 "decoding str is not supported");
2927 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002928 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002929
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002930 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2931 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2932 PyErr_Format(PyExc_TypeError,
Serhiy Storchakab757c832014-12-05 22:25:22 +02002933 "coercing to str: need a bytes-like object, %.80s found",
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002934 Py_TYPE(obj)->tp_name);
2935 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002936 }
Tim Petersced69f82003-09-16 20:30:58 +00002937
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002938 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002939 PyBuffer_Release(&buffer);
2940 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00002941 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002942
Serhiy Storchaka05997252013-01-26 12:14:02 +02002943 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002944 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002945 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002946}
2947
Victor Stinner600d3be2010-06-10 12:00:55 +00002948/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002949 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2950 1 on success. */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01002951int
2952_Py_normalize_encoding(const char *encoding,
2953 char *lower,
2954 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002955{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002956 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002957 char *l;
2958 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002959
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002960 if (encoding == NULL) {
Victor Stinner66b32702013-11-07 23:12:23 +01002961 /* 6 == strlen("utf-8") + 1 */
Victor Stinnerdf23e302013-11-07 13:33:36 +01002962 if (lower_len < 6)
2963 return 0;
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002964 strcpy(lower, "utf-8");
2965 return 1;
2966 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002967 e = encoding;
2968 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002969 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002970 while (*e) {
2971 if (l == l_end)
2972 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002973 if (Py_ISUPPER(*e)) {
2974 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002975 }
2976 else if (*e == '_') {
2977 *l++ = '-';
2978 e++;
2979 }
2980 else {
2981 *l++ = *e++;
2982 }
2983 }
2984 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002985 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002986}
2987
Alexander Belopolsky40018472011-02-26 01:02:56 +00002988PyObject *
2989PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002990 Py_ssize_t size,
2991 const char *encoding,
2992 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002993{
2994 PyObject *buffer = NULL, *unicode;
2995 Py_buffer info;
2996 char lower[11]; /* Enough for any encoding shortcut */
2997
Fred Drakee4315f52000-05-09 19:53:39 +00002998 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01002999 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003000 if ((strcmp(lower, "utf-8") == 0) ||
3001 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003002 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00003003 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003004 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003005 (strcmp(lower, "iso-8859-1") == 0) ||
3006 (strcmp(lower, "iso8859-1") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00003007 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003008#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003009 else if (strcmp(lower, "mbcs") == 0)
3010 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003011#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003012 else if (strcmp(lower, "ascii") == 0)
3013 return PyUnicode_DecodeASCII(s, size, errors);
3014 else if (strcmp(lower, "utf-16") == 0)
3015 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3016 else if (strcmp(lower, "utf-32") == 0)
3017 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3018 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003019
3020 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003021 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003022 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003023 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003024 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003025 if (buffer == NULL)
3026 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003027 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003028 if (unicode == NULL)
3029 goto onError;
3030 if (!PyUnicode_Check(unicode)) {
3031 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003032 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3033 "use codecs.decode() to decode to arbitrary types",
3034 encoding,
3035 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003036 Py_DECREF(unicode);
3037 goto onError;
3038 }
3039 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003040 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003041
Benjamin Peterson29060642009-01-31 22:14:21 +00003042 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003043 Py_XDECREF(buffer);
3044 return NULL;
3045}
3046
Alexander Belopolsky40018472011-02-26 01:02:56 +00003047PyObject *
3048PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003049 const char *encoding,
3050 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003051{
3052 PyObject *v;
3053
3054 if (!PyUnicode_Check(unicode)) {
3055 PyErr_BadArgument();
3056 goto onError;
3057 }
3058
3059 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003060 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003061
3062 /* Decode via the codec registry */
3063 v = PyCodec_Decode(unicode, encoding, errors);
3064 if (v == NULL)
3065 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003066 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003067
Benjamin Peterson29060642009-01-31 22:14:21 +00003068 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003069 return NULL;
3070}
3071
Alexander Belopolsky40018472011-02-26 01:02:56 +00003072PyObject *
3073PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003074 const char *encoding,
3075 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003076{
3077 PyObject *v;
3078
3079 if (!PyUnicode_Check(unicode)) {
3080 PyErr_BadArgument();
3081 goto onError;
3082 }
3083
3084 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003085 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003086
3087 /* Decode via the codec registry */
3088 v = PyCodec_Decode(unicode, encoding, errors);
3089 if (v == NULL)
3090 goto onError;
3091 if (!PyUnicode_Check(v)) {
3092 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003093 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3094 "use codecs.decode() to decode to arbitrary types",
3095 encoding,
3096 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003097 Py_DECREF(v);
3098 goto onError;
3099 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003100 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003101
Benjamin Peterson29060642009-01-31 22:14:21 +00003102 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003103 return NULL;
3104}
3105
Alexander Belopolsky40018472011-02-26 01:02:56 +00003106PyObject *
3107PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003108 Py_ssize_t size,
3109 const char *encoding,
3110 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003111{
3112 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003113
Guido van Rossumd57fd912000-03-10 22:53:23 +00003114 unicode = PyUnicode_FromUnicode(s, size);
3115 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003116 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003117 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3118 Py_DECREF(unicode);
3119 return v;
3120}
3121
Alexander Belopolsky40018472011-02-26 01:02:56 +00003122PyObject *
3123PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003124 const char *encoding,
3125 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003126{
3127 PyObject *v;
3128
3129 if (!PyUnicode_Check(unicode)) {
3130 PyErr_BadArgument();
3131 goto onError;
3132 }
3133
3134 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003135 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003136
3137 /* Encode via the codec registry */
3138 v = PyCodec_Encode(unicode, encoding, errors);
3139 if (v == NULL)
3140 goto onError;
3141 return v;
3142
Benjamin Peterson29060642009-01-31 22:14:21 +00003143 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003144 return NULL;
3145}
3146
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003147static size_t
3148wcstombs_errorpos(const wchar_t *wstr)
3149{
3150 size_t len;
3151#if SIZEOF_WCHAR_T == 2
3152 wchar_t buf[3];
3153#else
3154 wchar_t buf[2];
3155#endif
3156 char outbuf[MB_LEN_MAX];
3157 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003158
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003159#if SIZEOF_WCHAR_T == 2
3160 buf[2] = 0;
3161#else
3162 buf[1] = 0;
3163#endif
3164 start = wstr;
3165 while (*wstr != L'\0')
3166 {
3167 previous = wstr;
3168#if SIZEOF_WCHAR_T == 2
3169 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3170 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3171 {
3172 buf[0] = wstr[0];
3173 buf[1] = wstr[1];
3174 wstr += 2;
3175 }
3176 else {
3177 buf[0] = *wstr;
3178 buf[1] = 0;
3179 wstr++;
3180 }
3181#else
3182 buf[0] = *wstr;
3183 wstr++;
3184#endif
3185 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003186 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003187 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003188 }
3189
3190 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003191 return 0;
3192}
3193
Victor Stinner1b579672011-12-17 05:47:23 +01003194static int
3195locale_error_handler(const char *errors, int *surrogateescape)
3196{
Victor Stinner50149202015-09-22 00:26:54 +02003197 _Py_error_handler error_handler = get_error_handler(errors);
3198 switch (error_handler)
3199 {
3200 case _Py_ERROR_STRICT:
Victor Stinner1b579672011-12-17 05:47:23 +01003201 *surrogateescape = 0;
3202 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003203 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner1b579672011-12-17 05:47:23 +01003204 *surrogateescape = 1;
3205 return 0;
Victor Stinner50149202015-09-22 00:26:54 +02003206 default:
3207 PyErr_Format(PyExc_ValueError,
3208 "only 'strict' and 'surrogateescape' error handlers "
3209 "are supported, not '%s'",
3210 errors);
3211 return -1;
Victor Stinner1b579672011-12-17 05:47:23 +01003212 }
Victor Stinner1b579672011-12-17 05:47:23 +01003213}
3214
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003215PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003216PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003217{
3218 Py_ssize_t wlen, wlen2;
3219 wchar_t *wstr;
3220 PyObject *bytes = NULL;
3221 char *errmsg;
Raymond Hettingere56666d2013-08-04 11:51:03 -07003222 PyObject *reason = NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003223 PyObject *exc;
3224 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003225 int surrogateescape;
3226
3227 if (locale_error_handler(errors, &surrogateescape) < 0)
3228 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003229
3230 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3231 if (wstr == NULL)
3232 return NULL;
3233
3234 wlen2 = wcslen(wstr);
3235 if (wlen2 != wlen) {
3236 PyMem_Free(wstr);
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003237 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003238 return NULL;
3239 }
3240
3241 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003242 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003243 char *str;
3244
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003245 str = Py_EncodeLocale(wstr, &error_pos);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003246 if (str == NULL) {
3247 if (error_pos == (size_t)-1) {
3248 PyErr_NoMemory();
3249 PyMem_Free(wstr);
3250 return NULL;
3251 }
3252 else {
3253 goto encode_error;
3254 }
3255 }
3256 PyMem_Free(wstr);
3257
3258 bytes = PyBytes_FromString(str);
3259 PyMem_Free(str);
3260 }
3261 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003262 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003263 size_t len, len2;
3264
3265 len = wcstombs(NULL, wstr, 0);
3266 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003267 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003268 goto encode_error;
3269 }
3270
3271 bytes = PyBytes_FromStringAndSize(NULL, len);
3272 if (bytes == NULL) {
3273 PyMem_Free(wstr);
3274 return NULL;
3275 }
3276
3277 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3278 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003279 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003280 goto encode_error;
3281 }
3282 PyMem_Free(wstr);
3283 }
3284 return bytes;
3285
3286encode_error:
3287 errmsg = strerror(errno);
3288 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003289
3290 if (error_pos == (size_t)-1)
3291 error_pos = wcstombs_errorpos(wstr);
3292
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003293 PyMem_Free(wstr);
3294 Py_XDECREF(bytes);
3295
Victor Stinner2f197072011-12-17 07:08:30 +01003296 if (errmsg != NULL) {
3297 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003298 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003299 if (wstr != NULL) {
3300 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003301 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003302 } else
3303 errmsg = NULL;
3304 }
3305 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003306 reason = PyUnicode_FromString(
3307 "wcstombs() encountered an unencodable "
3308 "wide character");
3309 if (reason == NULL)
3310 return NULL;
3311
3312 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3313 "locale", unicode,
3314 (Py_ssize_t)error_pos,
3315 (Py_ssize_t)(error_pos+1),
3316 reason);
3317 Py_DECREF(reason);
3318 if (exc != NULL) {
3319 PyCodec_StrictErrors(exc);
3320 Py_XDECREF(exc);
3321 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003322 return NULL;
3323}
3324
Victor Stinnerad158722010-10-27 00:25:46 +00003325PyObject *
3326PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003327{
Victor Stinner99b95382011-07-04 14:23:54 +02003328#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003329 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003330#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003331 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003332#else
Victor Stinner793b5312011-04-27 00:24:21 +02003333 PyInterpreterState *interp = PyThreadState_GET()->interp;
3334 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3335 cannot use it to encode and decode filenames before it is loaded. Load
3336 the Python codec requires to encode at least its own filename. Use the C
3337 version of the locale codec until the codec registry is initialized and
3338 the Python codec is loaded.
3339
3340 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3341 cannot only rely on it: check also interp->fscodec_initialized for
3342 subinterpreters. */
3343 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003344 return PyUnicode_AsEncodedString(unicode,
3345 Py_FileSystemDefaultEncoding,
3346 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003347 }
3348 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003349 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003350 }
Victor Stinnerad158722010-10-27 00:25:46 +00003351#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003352}
3353
Alexander Belopolsky40018472011-02-26 01:02:56 +00003354PyObject *
3355PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003356 const char *encoding,
3357 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003358{
3359 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003360 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003361
Guido van Rossumd57fd912000-03-10 22:53:23 +00003362 if (!PyUnicode_Check(unicode)) {
3363 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003364 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003365 }
Fred Drakee4315f52000-05-09 19:53:39 +00003366
Fred Drakee4315f52000-05-09 19:53:39 +00003367 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003368 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003369 if ((strcmp(lower, "utf-8") == 0) ||
3370 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003371 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003372 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003373 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003374 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003375 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003376 }
Victor Stinner37296e82010-06-10 13:36:23 +00003377 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003378 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003379 (strcmp(lower, "iso-8859-1") == 0) ||
3380 (strcmp(lower, "iso8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003381 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003382#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003383 else if (strcmp(lower, "mbcs") == 0)
3384 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003385#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003386 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003387 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003388 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003389
3390 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003391 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003392 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003393 return NULL;
3394
3395 /* The normal path */
3396 if (PyBytes_Check(v))
3397 return v;
3398
3399 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003400 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003401 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003402 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003403
3404 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003405 "encoder %s returned bytearray instead of bytes; "
3406 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003407 encoding);
3408 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003409 Py_DECREF(v);
3410 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003411 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003412
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003413 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3414 Py_DECREF(v);
3415 return b;
3416 }
3417
3418 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003419 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3420 "use codecs.encode() to encode to arbitrary types",
3421 encoding,
3422 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003423 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003424 return NULL;
3425}
3426
Alexander Belopolsky40018472011-02-26 01:02:56 +00003427PyObject *
3428PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003429 const char *encoding,
3430 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003431{
3432 PyObject *v;
3433
3434 if (!PyUnicode_Check(unicode)) {
3435 PyErr_BadArgument();
3436 goto onError;
3437 }
3438
3439 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003440 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003441
3442 /* Encode via the codec registry */
3443 v = PyCodec_Encode(unicode, encoding, errors);
3444 if (v == NULL)
3445 goto onError;
3446 if (!PyUnicode_Check(v)) {
3447 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003448 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3449 "use codecs.encode() to encode to arbitrary types",
3450 encoding,
3451 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003452 Py_DECREF(v);
3453 goto onError;
3454 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003455 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003456
Benjamin Peterson29060642009-01-31 22:14:21 +00003457 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003458 return NULL;
3459}
3460
Victor Stinner2f197072011-12-17 07:08:30 +01003461static size_t
3462mbstowcs_errorpos(const char *str, size_t len)
3463{
3464#ifdef HAVE_MBRTOWC
3465 const char *start = str;
3466 mbstate_t mbs;
3467 size_t converted;
3468 wchar_t ch;
3469
3470 memset(&mbs, 0, sizeof mbs);
3471 while (len)
3472 {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03003473 converted = mbrtowc(&ch, str, len, &mbs);
Victor Stinner2f197072011-12-17 07:08:30 +01003474 if (converted == 0)
3475 /* Reached end of string */
3476 break;
3477 if (converted == (size_t)-1 || converted == (size_t)-2) {
3478 /* Conversion error or incomplete character */
3479 return str - start;
3480 }
3481 else {
3482 str += converted;
3483 len -= converted;
3484 }
3485 }
3486 /* failed to find the undecodable byte sequence */
3487 return 0;
3488#endif
3489 return 0;
3490}
3491
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003492PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003493PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003494 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003495{
3496 wchar_t smallbuf[256];
3497 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3498 wchar_t *wstr;
3499 size_t wlen, wlen2;
3500 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003501 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003502 size_t error_pos;
3503 char *errmsg;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01003504 PyObject *reason = NULL; /* initialize to prevent gcc warning */
3505 PyObject *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003506
3507 if (locale_error_handler(errors, &surrogateescape) < 0)
3508 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003509
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003510 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3511 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003512 return NULL;
3513 }
3514
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003515 if (surrogateescape) {
3516 /* "surrogateescape" error handler */
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003517 wstr = Py_DecodeLocale(str, &wlen);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003518 if (wstr == NULL) {
3519 if (wlen == (size_t)-1)
3520 PyErr_NoMemory();
3521 else
3522 PyErr_SetFromErrno(PyExc_OSError);
3523 return NULL;
3524 }
3525
3526 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003527 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003528 }
3529 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003530 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003531#ifndef HAVE_BROKEN_MBSTOWCS
3532 wlen = mbstowcs(NULL, str, 0);
3533#else
3534 wlen = len;
3535#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003536 if (wlen == (size_t)-1)
3537 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003538 if (wlen+1 <= smallbuf_len) {
3539 wstr = smallbuf;
3540 }
3541 else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003542 wstr = PyMem_New(wchar_t, wlen+1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003543 if (!wstr)
3544 return PyErr_NoMemory();
3545 }
3546
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003547 wlen2 = mbstowcs(wstr, str, wlen+1);
3548 if (wlen2 == (size_t)-1) {
3549 if (wstr != smallbuf)
3550 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003551 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003552 }
3553#ifdef HAVE_BROKEN_MBSTOWCS
3554 assert(wlen2 == wlen);
3555#endif
3556 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3557 if (wstr != smallbuf)
3558 PyMem_Free(wstr);
3559 }
3560 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003561
3562decode_error:
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003563 reason = NULL;
Victor Stinner2f197072011-12-17 07:08:30 +01003564 errmsg = strerror(errno);
3565 assert(errmsg != NULL);
3566
3567 error_pos = mbstowcs_errorpos(str, len);
3568 if (errmsg != NULL) {
3569 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003570 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003571 if (wstr != NULL) {
3572 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003573 PyMem_RawFree(wstr);
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003574 }
Victor Stinner2f197072011-12-17 07:08:30 +01003575 }
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003576 if (reason == NULL)
Victor Stinner2f197072011-12-17 07:08:30 +01003577 reason = PyUnicode_FromString(
3578 "mbstowcs() encountered an invalid multibyte sequence");
3579 if (reason == NULL)
3580 return NULL;
3581
3582 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3583 "locale", str, len,
3584 (Py_ssize_t)error_pos,
3585 (Py_ssize_t)(error_pos+1),
3586 reason);
3587 Py_DECREF(reason);
3588 if (exc != NULL) {
3589 PyCodec_StrictErrors(exc);
3590 Py_XDECREF(exc);
3591 }
3592 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003593}
3594
3595PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003596PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003597{
3598 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003599 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003600}
3601
3602
3603PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003604PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003605 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003606 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3607}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003608
Christian Heimes5894ba72007-11-04 11:43:14 +00003609PyObject*
3610PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3611{
Victor Stinner99b95382011-07-04 14:23:54 +02003612#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003613 return PyUnicode_DecodeMBCS(s, size, NULL);
3614#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003615 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003616#else
Victor Stinner793b5312011-04-27 00:24:21 +02003617 PyInterpreterState *interp = PyThreadState_GET()->interp;
3618 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3619 cannot use it to encode and decode filenames before it is loaded. Load
3620 the Python codec requires to encode at least its own filename. Use the C
3621 version of the locale codec until the codec registry is initialized and
3622 the Python codec is loaded.
3623
3624 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3625 cannot only rely on it: check also interp->fscodec_initialized for
3626 subinterpreters. */
3627 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003628 return PyUnicode_Decode(s, size,
3629 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003630 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003631 }
3632 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003633 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003634 }
Victor Stinnerad158722010-10-27 00:25:46 +00003635#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003636}
3637
Martin v. Löwis011e8422009-05-05 04:43:17 +00003638
3639int
3640PyUnicode_FSConverter(PyObject* arg, void* addr)
3641{
3642 PyObject *output = NULL;
3643 Py_ssize_t size;
3644 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003645 if (arg == NULL) {
3646 Py_DECREF(*(PyObject**)addr);
3647 return 1;
3648 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003649 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003650 output = arg;
3651 Py_INCREF(output);
3652 }
3653 else {
3654 arg = PyUnicode_FromObject(arg);
3655 if (!arg)
3656 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003657 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003658 Py_DECREF(arg);
3659 if (!output)
3660 return 0;
3661 if (!PyBytes_Check(output)) {
3662 Py_DECREF(output);
3663 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3664 return 0;
3665 }
3666 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003667 size = PyBytes_GET_SIZE(output);
3668 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003669 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003670 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003671 Py_DECREF(output);
3672 return 0;
3673 }
3674 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003675 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003676}
3677
3678
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003679int
3680PyUnicode_FSDecoder(PyObject* arg, void* addr)
3681{
3682 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003683 if (arg == NULL) {
3684 Py_DECREF(*(PyObject**)addr);
3685 return 1;
3686 }
3687 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003688 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003689 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003690 output = arg;
3691 Py_INCREF(output);
3692 }
3693 else {
3694 arg = PyBytes_FromObject(arg);
3695 if (!arg)
3696 return 0;
3697 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3698 PyBytes_GET_SIZE(arg));
3699 Py_DECREF(arg);
3700 if (!output)
3701 return 0;
3702 if (!PyUnicode_Check(output)) {
3703 Py_DECREF(output);
3704 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3705 return 0;
3706 }
3707 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003708 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003709 Py_DECREF(output);
3710 return 0;
3711 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003712 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003713 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003714 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003715 Py_DECREF(output);
3716 return 0;
3717 }
3718 *(PyObject**)addr = output;
3719 return Py_CLEANUP_SUPPORTED;
3720}
3721
3722
Martin v. Löwis5b222132007-06-10 09:51:05 +00003723char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003724PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003725{
Christian Heimesf3863112007-11-22 07:46:41 +00003726 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003727
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003728 if (!PyUnicode_Check(unicode)) {
3729 PyErr_BadArgument();
3730 return NULL;
3731 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003732 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003733 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003734
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003735 if (PyUnicode_UTF8(unicode) == NULL) {
3736 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003737 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3738 if (bytes == NULL)
3739 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003740 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3741 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003742 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003743 Py_DECREF(bytes);
3744 return NULL;
3745 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003746 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3747 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3748 PyBytes_AS_STRING(bytes),
3749 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003750 Py_DECREF(bytes);
3751 }
3752
3753 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003754 *psize = PyUnicode_UTF8_LENGTH(unicode);
3755 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003756}
3757
3758char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003759PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003760{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003761 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3762}
3763
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003764Py_UNICODE *
3765PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3766{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003767 const unsigned char *one_byte;
3768#if SIZEOF_WCHAR_T == 4
3769 const Py_UCS2 *two_bytes;
3770#else
3771 const Py_UCS4 *four_bytes;
3772 const Py_UCS4 *ucs4_end;
3773 Py_ssize_t num_surrogates;
3774#endif
3775 wchar_t *w;
3776 wchar_t *wchar_end;
3777
3778 if (!PyUnicode_Check(unicode)) {
3779 PyErr_BadArgument();
3780 return NULL;
3781 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003782 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003783 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003784 assert(_PyUnicode_KIND(unicode) != 0);
3785 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003786
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003787 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003788#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003789 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3790 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003791 num_surrogates = 0;
3792
3793 for (; four_bytes < ucs4_end; ++four_bytes) {
3794 if (*four_bytes > 0xFFFF)
3795 ++num_surrogates;
3796 }
3797
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003798 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3799 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3800 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003801 PyErr_NoMemory();
3802 return NULL;
3803 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003804 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003805
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003806 w = _PyUnicode_WSTR(unicode);
3807 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3808 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003809 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3810 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003811 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003812 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003813 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3814 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003815 }
3816 else
3817 *w = *four_bytes;
3818
3819 if (w > wchar_end) {
3820 assert(0 && "Miscalculated string end");
3821 }
3822 }
3823 *w = 0;
3824#else
3825 /* sizeof(wchar_t) == 4 */
3826 Py_FatalError("Impossible unicode object state, wstr and str "
3827 "should share memory already.");
3828 return NULL;
3829#endif
3830 }
3831 else {
Serhiy Storchakae55181f2015-02-20 21:34:06 +02003832 if ((size_t)_PyUnicode_LENGTH(unicode) >
3833 PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
3834 PyErr_NoMemory();
3835 return NULL;
3836 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003837 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3838 (_PyUnicode_LENGTH(unicode) + 1));
3839 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003840 PyErr_NoMemory();
3841 return NULL;
3842 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003843 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3844 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3845 w = _PyUnicode_WSTR(unicode);
3846 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003847
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003848 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3849 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003850 for (; w < wchar_end; ++one_byte, ++w)
3851 *w = *one_byte;
3852 /* null-terminate the wstr */
3853 *w = 0;
3854 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003855 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003856#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003857 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003858 for (; w < wchar_end; ++two_bytes, ++w)
3859 *w = *two_bytes;
3860 /* null-terminate the wstr */
3861 *w = 0;
3862#else
3863 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003864 PyObject_FREE(_PyUnicode_WSTR(unicode));
3865 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003866 Py_FatalError("Impossible unicode object state, wstr "
3867 "and str should share memory already.");
3868 return NULL;
3869#endif
3870 }
3871 else {
3872 assert(0 && "This should never happen.");
3873 }
3874 }
3875 }
3876 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003877 *size = PyUnicode_WSTR_LENGTH(unicode);
3878 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003879}
3880
Alexander Belopolsky40018472011-02-26 01:02:56 +00003881Py_UNICODE *
3882PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003883{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003884 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003885}
3886
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003887
Alexander Belopolsky40018472011-02-26 01:02:56 +00003888Py_ssize_t
3889PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003890{
3891 if (!PyUnicode_Check(unicode)) {
3892 PyErr_BadArgument();
3893 goto onError;
3894 }
3895 return PyUnicode_GET_SIZE(unicode);
3896
Benjamin Peterson29060642009-01-31 22:14:21 +00003897 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003898 return -1;
3899}
3900
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003901Py_ssize_t
3902PyUnicode_GetLength(PyObject *unicode)
3903{
Victor Stinner07621332012-06-16 04:53:46 +02003904 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003905 PyErr_BadArgument();
3906 return -1;
3907 }
Victor Stinner07621332012-06-16 04:53:46 +02003908 if (PyUnicode_READY(unicode) == -1)
3909 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003910 return PyUnicode_GET_LENGTH(unicode);
3911}
3912
3913Py_UCS4
3914PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3915{
Victor Stinner69ed0f42013-04-09 21:48:24 +02003916 void *data;
3917 int kind;
3918
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003919 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3920 PyErr_BadArgument();
3921 return (Py_UCS4)-1;
3922 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003923 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003924 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003925 return (Py_UCS4)-1;
3926 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02003927 data = PyUnicode_DATA(unicode);
3928 kind = PyUnicode_KIND(unicode);
3929 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003930}
3931
3932int
3933PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3934{
3935 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003936 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003937 return -1;
3938 }
Victor Stinner488fa492011-12-12 00:01:39 +01003939 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01003940 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003941 PyErr_SetString(PyExc_IndexError, "string index out of range");
3942 return -1;
3943 }
Victor Stinner488fa492011-12-12 00:01:39 +01003944 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02003945 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01003946 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
3947 PyErr_SetString(PyExc_ValueError, "character out of range");
3948 return -1;
3949 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003950 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3951 index, ch);
3952 return 0;
3953}
3954
Alexander Belopolsky40018472011-02-26 01:02:56 +00003955const char *
3956PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003957{
Victor Stinner42cb4622010-09-01 19:39:01 +00003958 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003959}
3960
Victor Stinner554f3f02010-06-16 23:33:54 +00003961/* create or adjust a UnicodeDecodeError */
3962static void
3963make_decode_exception(PyObject **exceptionObject,
3964 const char *encoding,
3965 const char *input, Py_ssize_t length,
3966 Py_ssize_t startpos, Py_ssize_t endpos,
3967 const char *reason)
3968{
3969 if (*exceptionObject == NULL) {
3970 *exceptionObject = PyUnicodeDecodeError_Create(
3971 encoding, input, length, startpos, endpos, reason);
3972 }
3973 else {
3974 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3975 goto onError;
3976 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3977 goto onError;
3978 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3979 goto onError;
3980 }
3981 return;
3982
3983onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02003984 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00003985}
3986
Victor Stinnerfc009ef2012-11-07 00:36:38 +01003987#ifdef HAVE_MBCS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003988/* error handling callback helper:
3989 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003990 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003991 and adjust various state variables.
3992 return 0 on success, -1 on error
3993*/
3994
Alexander Belopolsky40018472011-02-26 01:02:56 +00003995static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01003996unicode_decode_call_errorhandler_wchar(
3997 const char *errors, PyObject **errorHandler,
3998 const char *encoding, const char *reason,
3999 const char **input, const char **inend, Py_ssize_t *startinpos,
4000 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4001 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004002{
Benjamin Peterson142957c2008-07-04 19:55:29 +00004003 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004004
4005 PyObject *restuple = NULL;
4006 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004007 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004008 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004009 Py_ssize_t requiredsize;
4010 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004011 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004012 wchar_t *repwstr;
4013 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004014
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004015 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4016 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004017
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004018 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004019 *errorHandler = PyCodec_LookupError(errors);
4020 if (*errorHandler == NULL)
4021 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004022 }
4023
Victor Stinner554f3f02010-06-16 23:33:54 +00004024 make_decode_exception(exceptionObject,
4025 encoding,
4026 *input, *inend - *input,
4027 *startinpos, *endinpos,
4028 reason);
4029 if (*exceptionObject == NULL)
4030 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004031
4032 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4033 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004034 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004035 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004036 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004037 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004038 }
4039 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004040 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004041
4042 /* Copy back the bytes variables, which might have been modified by the
4043 callback */
4044 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4045 if (!inputobj)
4046 goto onError;
4047 if (!PyBytes_Check(inputobj)) {
4048 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
4049 }
4050 *input = PyBytes_AS_STRING(inputobj);
4051 insize = PyBytes_GET_SIZE(inputobj);
4052 *inend = *input + insize;
4053 /* we can DECREF safely, as the exception has another reference,
4054 so the object won't go away. */
4055 Py_DECREF(inputobj);
4056
4057 if (newpos<0)
4058 newpos = insize+newpos;
4059 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004060 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004061 goto onError;
4062 }
4063
4064 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4065 if (repwstr == NULL)
4066 goto onError;
4067 /* need more space? (at least enough for what we
4068 have+the replacement+the rest of the string (starting
4069 at the new input position), so we won't have to check space
4070 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004071 requiredsize = *outpos;
4072 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4073 goto overflow;
4074 requiredsize += repwlen;
4075 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4076 goto overflow;
4077 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004078 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004079 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004080 requiredsize = 2*outsize;
4081 if (unicode_resize(output, requiredsize) < 0)
4082 goto onError;
4083 }
4084 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4085 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004086 *endinpos = newpos;
4087 *inptr = *input + newpos;
4088
4089 /* we made it! */
4090 Py_XDECREF(restuple);
4091 return 0;
4092
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004093 overflow:
4094 PyErr_SetString(PyExc_OverflowError,
4095 "decoded result is too long for a Python string");
4096
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004097 onError:
4098 Py_XDECREF(restuple);
4099 return -1;
4100}
4101#endif /* HAVE_MBCS */
4102
4103static int
4104unicode_decode_call_errorhandler_writer(
4105 const char *errors, PyObject **errorHandler,
4106 const char *encoding, const char *reason,
4107 const char **input, const char **inend, Py_ssize_t *startinpos,
4108 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4109 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4110{
4111 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
4112
4113 PyObject *restuple = NULL;
4114 PyObject *repunicode = NULL;
4115 Py_ssize_t insize;
4116 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004117 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004118 PyObject *inputobj = NULL;
4119
4120 if (*errorHandler == NULL) {
4121 *errorHandler = PyCodec_LookupError(errors);
4122 if (*errorHandler == NULL)
4123 goto onError;
4124 }
4125
4126 make_decode_exception(exceptionObject,
4127 encoding,
4128 *input, *inend - *input,
4129 *startinpos, *endinpos,
4130 reason);
4131 if (*exceptionObject == NULL)
4132 goto onError;
4133
4134 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4135 if (restuple == NULL)
4136 goto onError;
4137 if (!PyTuple_Check(restuple)) {
4138 PyErr_SetString(PyExc_TypeError, &argparse[4]);
4139 goto onError;
4140 }
4141 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004142 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004143
4144 /* Copy back the bytes variables, which might have been modified by the
4145 callback */
4146 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4147 if (!inputobj)
4148 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004149 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004150 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004151 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004152 *input = PyBytes_AS_STRING(inputobj);
4153 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004154 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004155 /* we can DECREF safely, as the exception has another reference,
4156 so the object won't go away. */
4157 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004158
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004159 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004160 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004161 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004162 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004163 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004164 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004165
Victor Stinner8f674cc2013-04-17 23:02:17 +02004166 if (PyUnicode_READY(repunicode) < 0)
4167 goto onError;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004168 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004169 if (replen > 1) {
4170 writer->min_length += replen - 1;
Victor Stinner8f674cc2013-04-17 23:02:17 +02004171 writer->overallocate = 1;
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004172 if (_PyUnicodeWriter_Prepare(writer, writer->min_length,
4173 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4174 goto onError;
4175 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004176 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004177 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004178
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004179 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004180 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004181
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004182 /* we made it! */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004183 Py_XDECREF(restuple);
4184 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004185
Benjamin Peterson29060642009-01-31 22:14:21 +00004186 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004187 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004188 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004189}
4190
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004191/* --- UTF-7 Codec -------------------------------------------------------- */
4192
Antoine Pitrou244651a2009-05-04 18:56:13 +00004193/* See RFC2152 for details. We encode conservatively and decode liberally. */
4194
4195/* Three simple macros defining base-64. */
4196
4197/* Is c a base-64 character? */
4198
4199#define IS_BASE64(c) \
4200 (((c) >= 'A' && (c) <= 'Z') || \
4201 ((c) >= 'a' && (c) <= 'z') || \
4202 ((c) >= '0' && (c) <= '9') || \
4203 (c) == '+' || (c) == '/')
4204
4205/* given that c is a base-64 character, what is its base-64 value? */
4206
4207#define FROM_BASE64(c) \
4208 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4209 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4210 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4211 (c) == '+' ? 62 : 63)
4212
4213/* What is the base-64 character of the bottom 6 bits of n? */
4214
4215#define TO_BASE64(n) \
4216 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4217
4218/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4219 * decoded as itself. We are permissive on decoding; the only ASCII
4220 * byte not decoding to itself is the + which begins a base64
4221 * string. */
4222
4223#define DECODE_DIRECT(c) \
4224 ((c) <= 127 && (c) != '+')
4225
4226/* The UTF-7 encoder treats ASCII characters differently according to
4227 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4228 * the above). See RFC2152. This array identifies these different
4229 * sets:
4230 * 0 : "Set D"
4231 * alphanumeric and '(),-./:?
4232 * 1 : "Set O"
4233 * !"#$%&*;<=>@[]^_`{|}
4234 * 2 : "whitespace"
4235 * ht nl cr sp
4236 * 3 : special (must be base64 encoded)
4237 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4238 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004239
Tim Petersced69f82003-09-16 20:30:58 +00004240static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004241char utf7_category[128] = {
4242/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4243 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4244/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4245 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4246/* sp ! " # $ % & ' ( ) * + , - . / */
4247 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4248/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4249 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4250/* @ A B C D E F G H I J K L M N O */
4251 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4252/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4253 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4254/* ` a b c d e f g h i j k l m n o */
4255 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4256/* p q r s t u v w x y z { | } ~ del */
4257 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004258};
4259
Antoine Pitrou244651a2009-05-04 18:56:13 +00004260/* ENCODE_DIRECT: this character should be encoded as itself. The
4261 * answer depends on whether we are encoding set O as itself, and also
4262 * on whether we are encoding whitespace as itself. RFC2152 makes it
4263 * clear that the answers to these questions vary between
4264 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004265
Antoine Pitrou244651a2009-05-04 18:56:13 +00004266#define ENCODE_DIRECT(c, directO, directWS) \
4267 ((c) < 128 && (c) > 0 && \
4268 ((utf7_category[(c)] == 0) || \
4269 (directWS && (utf7_category[(c)] == 2)) || \
4270 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004271
Alexander Belopolsky40018472011-02-26 01:02:56 +00004272PyObject *
4273PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004274 Py_ssize_t size,
4275 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004276{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004277 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4278}
4279
Antoine Pitrou244651a2009-05-04 18:56:13 +00004280/* The decoder. The only state we preserve is our read position,
4281 * i.e. how many characters we have consumed. So if we end in the
4282 * middle of a shift sequence we have to back off the read position
4283 * and the output to the beginning of the sequence, otherwise we lose
4284 * all the shift state (seen bits, number of bits seen, high
4285 * surrogate). */
4286
Alexander Belopolsky40018472011-02-26 01:02:56 +00004287PyObject *
4288PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004289 Py_ssize_t size,
4290 const char *errors,
4291 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004292{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004293 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004294 Py_ssize_t startinpos;
4295 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004296 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004297 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004298 const char *errmsg = "";
4299 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004300 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004301 unsigned int base64bits = 0;
4302 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004303 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004304 PyObject *errorHandler = NULL;
4305 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004306
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004307 if (size == 0) {
4308 if (consumed)
4309 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004310 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004311 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004312
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004313 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004314 _PyUnicodeWriter_Init(&writer);
4315 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004316
4317 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004318 e = s + size;
4319
4320 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004321 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004322 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004323 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004324
Antoine Pitrou244651a2009-05-04 18:56:13 +00004325 if (inShift) { /* in a base-64 section */
4326 if (IS_BASE64(ch)) { /* consume a base-64 character */
4327 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4328 base64bits += 6;
4329 s++;
4330 if (base64bits >= 16) {
4331 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004332 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004333 base64bits -= 16;
4334 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004335 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004336 if (surrogate) {
4337 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004338 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4339 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004340 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004341 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004342 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004343 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004344 }
4345 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004346 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004347 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004348 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004349 }
4350 }
Victor Stinner551ac952011-11-29 22:58:13 +01004351 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004352 /* first surrogate */
4353 surrogate = outCh;
4354 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004355 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004356 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004357 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004358 }
4359 }
4360 }
4361 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004362 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004363 if (base64bits > 0) { /* left-over bits */
4364 if (base64bits >= 6) {
4365 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004366 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004367 errmsg = "partial character in shift sequence";
4368 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004369 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004370 else {
4371 /* Some bits remain; they should be zero */
4372 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004373 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004374 errmsg = "non-zero padding bits in shift sequence";
4375 goto utf7Error;
4376 }
4377 }
4378 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004379 if (surrogate && DECODE_DIRECT(ch)) {
4380 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4381 goto onError;
4382 }
4383 surrogate = 0;
4384 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004385 /* '-' is absorbed; other terminating
4386 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004387 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004388 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004389 }
4390 }
4391 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004392 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004393 s++; /* consume '+' */
4394 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004395 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004396 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004397 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004398 }
4399 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004400 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004401 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004402 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004403 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004404 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004405 }
4406 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004407 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004408 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004409 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004410 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004411 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004412 else {
4413 startinpos = s-starts;
4414 s++;
4415 errmsg = "unexpected special character";
4416 goto utf7Error;
4417 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004418 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004419utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004420 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004421 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004422 errors, &errorHandler,
4423 "utf7", errmsg,
4424 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004425 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004426 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004427 }
4428
Antoine Pitrou244651a2009-05-04 18:56:13 +00004429 /* end of string */
4430
4431 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4432 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004433 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004434 if (surrogate ||
4435 (base64bits >= 6) ||
4436 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004437 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004438 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004439 errors, &errorHandler,
4440 "utf7", "unterminated shift sequence",
4441 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004442 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004443 goto onError;
4444 if (s < e)
4445 goto restart;
4446 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004447 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004448
4449 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004450 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004451 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004452 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004453 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004454 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004455 writer.kind, writer.data, shiftOutStart);
4456 Py_XDECREF(errorHandler);
4457 Py_XDECREF(exc);
4458 _PyUnicodeWriter_Dealloc(&writer);
4459 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004460 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004461 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004462 }
4463 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004464 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004465 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004466 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004467
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004468 Py_XDECREF(errorHandler);
4469 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004470 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004471
Benjamin Peterson29060642009-01-31 22:14:21 +00004472 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004473 Py_XDECREF(errorHandler);
4474 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004475 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004476 return NULL;
4477}
4478
4479
Alexander Belopolsky40018472011-02-26 01:02:56 +00004480PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004481_PyUnicode_EncodeUTF7(PyObject *str,
4482 int base64SetO,
4483 int base64WhiteSpace,
4484 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004485{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004486 int kind;
4487 void *data;
4488 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004489 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004490 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004491 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004492 unsigned int base64bits = 0;
4493 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004494 char * out;
4495 char * start;
4496
Benjamin Petersonbac79492012-01-14 13:34:47 -05004497 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004498 return NULL;
4499 kind = PyUnicode_KIND(str);
4500 data = PyUnicode_DATA(str);
4501 len = PyUnicode_GET_LENGTH(str);
4502
4503 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004504 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004505
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004506 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004507 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004508 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004509 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004510 if (v == NULL)
4511 return NULL;
4512
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004513 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004514 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004515 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004516
Antoine Pitrou244651a2009-05-04 18:56:13 +00004517 if (inShift) {
4518 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4519 /* shifting out */
4520 if (base64bits) { /* output remaining bits */
4521 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4522 base64buffer = 0;
4523 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004524 }
4525 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004526 /* Characters not in the BASE64 set implicitly unshift the sequence
4527 so no '-' is required, except if the character is itself a '-' */
4528 if (IS_BASE64(ch) || ch == '-') {
4529 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004530 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004531 *out++ = (char) ch;
4532 }
4533 else {
4534 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004535 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004536 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004537 else { /* not in a shift sequence */
4538 if (ch == '+') {
4539 *out++ = '+';
4540 *out++ = '-';
4541 }
4542 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4543 *out++ = (char) ch;
4544 }
4545 else {
4546 *out++ = '+';
4547 inShift = 1;
4548 goto encode_char;
4549 }
4550 }
4551 continue;
4552encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004553 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004554 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004555
Antoine Pitrou244651a2009-05-04 18:56:13 +00004556 /* code first surrogate */
4557 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004558 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004559 while (base64bits >= 6) {
4560 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4561 base64bits -= 6;
4562 }
4563 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004564 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004565 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004566 base64bits += 16;
4567 base64buffer = (base64buffer << 16) | ch;
4568 while (base64bits >= 6) {
4569 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4570 base64bits -= 6;
4571 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004572 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004573 if (base64bits)
4574 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4575 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004576 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004577 if (_PyBytes_Resize(&v, out - start) < 0)
4578 return NULL;
4579 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004580}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004581PyObject *
4582PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4583 Py_ssize_t size,
4584 int base64SetO,
4585 int base64WhiteSpace,
4586 const char *errors)
4587{
4588 PyObject *result;
4589 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4590 if (tmp == NULL)
4591 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004592 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004593 base64WhiteSpace, errors);
4594 Py_DECREF(tmp);
4595 return result;
4596}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004597
Antoine Pitrou244651a2009-05-04 18:56:13 +00004598#undef IS_BASE64
4599#undef FROM_BASE64
4600#undef TO_BASE64
4601#undef DECODE_DIRECT
4602#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004603
Guido van Rossumd57fd912000-03-10 22:53:23 +00004604/* --- UTF-8 Codec -------------------------------------------------------- */
4605
Alexander Belopolsky40018472011-02-26 01:02:56 +00004606PyObject *
4607PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004608 Py_ssize_t size,
4609 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004610{
Walter Dörwald69652032004-09-07 20:24:22 +00004611 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4612}
4613
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004614#include "stringlib/asciilib.h"
4615#include "stringlib/codecs.h"
4616#include "stringlib/undef.h"
4617
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004618#include "stringlib/ucs1lib.h"
4619#include "stringlib/codecs.h"
4620#include "stringlib/undef.h"
4621
4622#include "stringlib/ucs2lib.h"
4623#include "stringlib/codecs.h"
4624#include "stringlib/undef.h"
4625
4626#include "stringlib/ucs4lib.h"
4627#include "stringlib/codecs.h"
4628#include "stringlib/undef.h"
4629
Antoine Pitrouab868312009-01-10 15:40:25 +00004630/* Mask to quickly check whether a C 'long' contains a
4631 non-ASCII, UTF8-encoded char. */
4632#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004633# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004634#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004635# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004636#else
4637# error C 'long' size should be either 4 or 8!
4638#endif
4639
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004640static Py_ssize_t
4641ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004642{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004643 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004644 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004645
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004646 /*
4647 * Issue #17237: m68k is a bit different from most architectures in
4648 * that objects do not use "natural alignment" - for example, int and
4649 * long are only aligned at 2-byte boundaries. Therefore the assert()
4650 * won't work; also, tests have shown that skipping the "optimised
4651 * version" will even speed up m68k.
4652 */
4653#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004654#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004655 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4656 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004657 /* Fast path, see in STRINGLIB(utf8_decode) for
4658 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004659 /* Help allocation */
4660 const char *_p = p;
4661 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004662 while (_p < aligned_end) {
4663 unsigned long value = *(const unsigned long *) _p;
4664 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004665 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004666 *((unsigned long *)q) = value;
4667 _p += SIZEOF_LONG;
4668 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004669 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004670 p = _p;
4671 while (p < end) {
4672 if ((unsigned char)*p & 0x80)
4673 break;
4674 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004675 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004676 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004677 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004678#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004679#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004680 while (p < end) {
4681 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4682 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004683 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004684 /* Help allocation */
4685 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004686 while (_p < aligned_end) {
4687 unsigned long value = *(unsigned long *) _p;
4688 if (value & ASCII_CHAR_MASK)
4689 break;
4690 _p += SIZEOF_LONG;
4691 }
4692 p = _p;
4693 if (_p == end)
4694 break;
4695 }
4696 if ((unsigned char)*p & 0x80)
4697 break;
4698 ++p;
4699 }
4700 memcpy(dest, start, p - start);
4701 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004702}
Antoine Pitrouab868312009-01-10 15:40:25 +00004703
Victor Stinner785938e2011-12-11 20:09:03 +01004704PyObject *
4705PyUnicode_DecodeUTF8Stateful(const char *s,
4706 Py_ssize_t size,
4707 const char *errors,
4708 Py_ssize_t *consumed)
4709{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004710 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004711 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004712 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004713
4714 Py_ssize_t startinpos;
4715 Py_ssize_t endinpos;
4716 const char *errmsg = "";
Victor Stinner1d65d912015-10-05 13:43:50 +02004717 PyObject *error_handler_obj = NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004718 PyObject *exc = NULL;
Victor Stinner1d65d912015-10-05 13:43:50 +02004719 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner785938e2011-12-11 20:09:03 +01004720
4721 if (size == 0) {
4722 if (consumed)
4723 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004724 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004725 }
4726
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004727 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4728 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004729 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004730 *consumed = 1;
4731 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004732 }
4733
Victor Stinner8f674cc2013-04-17 23:02:17 +02004734 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004735 writer.min_length = size;
4736 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004737 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004738
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004739 writer.pos = ascii_decode(s, end, writer.data);
4740 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004741 while (s < end) {
4742 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004743 int kind = writer.kind;
Victor Stinner1d65d912015-10-05 13:43:50 +02004744
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004745 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004746 if (PyUnicode_IS_ASCII(writer.buffer))
4747 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004748 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004749 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004750 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004751 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004752 } else {
4753 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004754 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004755 }
4756
4757 switch (ch) {
4758 case 0:
4759 if (s == end || consumed)
4760 goto End;
4761 errmsg = "unexpected end of data";
4762 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004763 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004764 break;
4765 case 1:
4766 errmsg = "invalid start byte";
4767 startinpos = s - starts;
4768 endinpos = startinpos + 1;
4769 break;
4770 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004771 case 3:
4772 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004773 errmsg = "invalid continuation byte";
4774 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004775 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004776 break;
4777 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004778 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004779 goto onError;
4780 continue;
4781 }
4782
Victor Stinner1d65d912015-10-05 13:43:50 +02004783 if (error_handler == _Py_ERROR_UNKNOWN)
4784 error_handler = get_error_handler(errors);
4785
4786 switch (error_handler) {
4787 case _Py_ERROR_IGNORE:
4788 s += (endinpos - startinpos);
4789 break;
4790
4791 case _Py_ERROR_REPLACE:
4792 if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
4793 goto onError;
4794 s += (endinpos - startinpos);
4795 break;
4796
4797 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner74e8fac2015-10-05 13:49:26 +02004798 {
4799 Py_ssize_t i;
4800
Victor Stinner1d65d912015-10-05 13:43:50 +02004801 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
4802 goto onError;
Victor Stinner74e8fac2015-10-05 13:49:26 +02004803 for (i=startinpos; i<endinpos; i++) {
Victor Stinner1d65d912015-10-05 13:43:50 +02004804 ch = (Py_UCS4)(unsigned char)(starts[i]);
4805 PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
4806 ch + 0xdc00);
4807 writer.pos++;
4808 }
4809 s += (endinpos - startinpos);
4810 break;
Victor Stinner74e8fac2015-10-05 13:49:26 +02004811 }
Victor Stinner1d65d912015-10-05 13:43:50 +02004812
4813 default:
4814 if (unicode_decode_call_errorhandler_writer(
4815 errors, &error_handler_obj,
4816 "utf-8", errmsg,
4817 &starts, &end, &startinpos, &endinpos, &exc, &s,
4818 &writer))
4819 goto onError;
4820 }
Victor Stinner785938e2011-12-11 20:09:03 +01004821 }
4822
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004823End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004824 if (consumed)
4825 *consumed = s - starts;
4826
Victor Stinner1d65d912015-10-05 13:43:50 +02004827 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004828 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004829 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004830
4831onError:
Victor Stinner1d65d912015-10-05 13:43:50 +02004832 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004833 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004834 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004835 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004836}
4837
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004838#ifdef __APPLE__
4839
4840/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004841 used to decode the command line arguments on Mac OS X.
4842
4843 Return a pointer to a newly allocated wide character string (use
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004844 PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004845
4846wchar_t*
4847_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4848{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004849 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004850 wchar_t *unicode;
4851 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004852
4853 /* Note: size will always be longer than the resulting Unicode
4854 character count */
Victor Stinnerf50e1872015-03-20 11:32:24 +01004855 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004856 return NULL;
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004857 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004858 if (!unicode)
4859 return NULL;
4860
4861 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004862 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004863 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004864 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004865 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004866#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004867 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004868#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004869 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004870#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004871 if (ch > 0xFF) {
4872#if SIZEOF_WCHAR_T == 4
4873 assert(0);
4874#else
4875 assert(Py_UNICODE_IS_SURROGATE(ch));
4876 /* compute and append the two surrogates: */
4877 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4878 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4879#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004880 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004881 else {
4882 if (!ch && s == e)
4883 break;
4884 /* surrogateescape */
4885 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
4886 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004887 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004888 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004889 return unicode;
4890}
4891
4892#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004893
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004894/* Primary internal function which creates utf8 encoded bytes objects.
4895
4896 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004897 and allocate exactly as much space needed at the end. Else allocate the
4898 maximum possible needed (4 result bytes per Unicode character), and return
4899 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004900*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004901PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004902_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004903{
Victor Stinner6099a032011-12-18 14:22:26 +01004904 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004905 void *data;
4906 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004907
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004908 if (!PyUnicode_Check(unicode)) {
4909 PyErr_BadArgument();
4910 return NULL;
4911 }
4912
4913 if (PyUnicode_READY(unicode) == -1)
4914 return NULL;
4915
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004916 if (PyUnicode_UTF8(unicode))
4917 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4918 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004919
4920 kind = PyUnicode_KIND(unicode);
4921 data = PyUnicode_DATA(unicode);
4922 size = PyUnicode_GET_LENGTH(unicode);
4923
Benjamin Petersonead6b532011-12-20 17:23:42 -06004924 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01004925 default:
4926 assert(0);
4927 case PyUnicode_1BYTE_KIND:
4928 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
4929 assert(!PyUnicode_IS_ASCII(unicode));
4930 return ucs1lib_utf8_encoder(unicode, data, size, errors);
4931 case PyUnicode_2BYTE_KIND:
4932 return ucs2lib_utf8_encoder(unicode, data, size, errors);
4933 case PyUnicode_4BYTE_KIND:
4934 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00004935 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004936}
4937
Alexander Belopolsky40018472011-02-26 01:02:56 +00004938PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004939PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4940 Py_ssize_t size,
4941 const char *errors)
4942{
4943 PyObject *v, *unicode;
4944
4945 unicode = PyUnicode_FromUnicode(s, size);
4946 if (unicode == NULL)
4947 return NULL;
4948 v = _PyUnicode_AsUTF8String(unicode, errors);
4949 Py_DECREF(unicode);
4950 return v;
4951}
4952
4953PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004954PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004955{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004956 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004957}
4958
Walter Dörwald41980ca2007-08-16 21:55:45 +00004959/* --- UTF-32 Codec ------------------------------------------------------- */
4960
4961PyObject *
4962PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004963 Py_ssize_t size,
4964 const char *errors,
4965 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004966{
4967 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4968}
4969
4970PyObject *
4971PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004972 Py_ssize_t size,
4973 const char *errors,
4974 int *byteorder,
4975 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004976{
4977 const char *starts = s;
4978 Py_ssize_t startinpos;
4979 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004980 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004981 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01004982 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02004983 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004984 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004985 PyObject *errorHandler = NULL;
4986 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004987
Walter Dörwald41980ca2007-08-16 21:55:45 +00004988 q = (unsigned char *)s;
4989 e = q + size;
4990
4991 if (byteorder)
4992 bo = *byteorder;
4993
4994 /* Check for BOM marks (U+FEFF) in the input and adjust current
4995 byte order setting accordingly. In native mode, the leading BOM
4996 mark is skipped, in all other modes, it is copied to the output
4997 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01004998 if (bo == 0 && size >= 4) {
4999 Py_UCS4 bom = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5000 if (bom == 0x0000FEFF) {
5001 bo = -1;
5002 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005003 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005004 else if (bom == 0xFFFE0000) {
5005 bo = 1;
5006 q += 4;
5007 }
5008 if (byteorder)
5009 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005010 }
5011
Victor Stinnere64322e2012-10-30 23:12:47 +01005012 if (q == e) {
5013 if (consumed)
5014 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005015 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005016 }
5017
Victor Stinnere64322e2012-10-30 23:12:47 +01005018#ifdef WORDS_BIGENDIAN
5019 le = bo < 0;
5020#else
5021 le = bo <= 0;
5022#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005023 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005024
Victor Stinner8f674cc2013-04-17 23:02:17 +02005025 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005026 writer.min_length = (e - q + 3) / 4;
5027 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005028 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005029
Victor Stinnere64322e2012-10-30 23:12:47 +01005030 while (1) {
5031 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005032 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005033
Victor Stinnere64322e2012-10-30 23:12:47 +01005034 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005035 enum PyUnicode_Kind kind = writer.kind;
5036 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005037 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005038 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005039 if (le) {
5040 do {
5041 ch = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
5042 if (ch > maxch)
5043 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005044 if (kind != PyUnicode_1BYTE_KIND &&
5045 Py_UNICODE_IS_SURROGATE(ch))
5046 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005047 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005048 q += 4;
5049 } while (q <= last);
5050 }
5051 else {
5052 do {
5053 ch = (q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
5054 if (ch > maxch)
5055 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005056 if (kind != PyUnicode_1BYTE_KIND &&
5057 Py_UNICODE_IS_SURROGATE(ch))
5058 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005059 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005060 q += 4;
5061 } while (q <= last);
5062 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005063 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005064 }
5065
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005066 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005067 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005068 startinpos = ((const char *)q) - starts;
5069 endinpos = startinpos + 4;
5070 }
5071 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005072 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005073 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005074 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005075 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005076 startinpos = ((const char *)q) - starts;
5077 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005078 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005079 else {
5080 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005081 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005082 goto onError;
5083 q += 4;
5084 continue;
5085 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005086 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005087 startinpos = ((const char *)q) - starts;
5088 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005089 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005090
5091 /* The remaining input chars are ignored if the callback
5092 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005093 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005094 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005095 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005096 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005097 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005098 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005099 }
5100
Walter Dörwald41980ca2007-08-16 21:55:45 +00005101 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005102 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005103
Walter Dörwald41980ca2007-08-16 21:55:45 +00005104 Py_XDECREF(errorHandler);
5105 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005106 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005107
Benjamin Peterson29060642009-01-31 22:14:21 +00005108 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005109 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005110 Py_XDECREF(errorHandler);
5111 Py_XDECREF(exc);
5112 return NULL;
5113}
5114
5115PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005116_PyUnicode_EncodeUTF32(PyObject *str,
5117 const char *errors,
5118 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005119{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005120 enum PyUnicode_Kind kind;
5121 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005122 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005123 PyObject *v;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005124 PY_UINT32_T *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005125#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005126 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005127#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005128 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005129#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005130 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005131 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005132 PyObject *errorHandler = NULL;
5133 PyObject *exc = NULL;
5134 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005135
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005136 if (!PyUnicode_Check(str)) {
5137 PyErr_BadArgument();
5138 return NULL;
5139 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005140 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005141 return NULL;
5142 kind = PyUnicode_KIND(str);
5143 data = PyUnicode_DATA(str);
5144 len = PyUnicode_GET_LENGTH(str);
5145
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005146 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005147 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005148 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005149 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005150 if (v == NULL)
5151 return NULL;
5152
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005153 /* output buffer is 4-bytes aligned */
5154 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
5155 out = (PY_UINT32_T *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005156 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005157 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005158 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005159 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005160
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005161 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005162 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005163 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005164 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005165 else
5166 encoding = "utf-32";
5167
5168 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005169 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5170 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005171 }
5172
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005173 pos = 0;
5174 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005175 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005176
5177 if (kind == PyUnicode_2BYTE_KIND) {
5178 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5179 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005180 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005181 else {
5182 assert(kind == PyUnicode_4BYTE_KIND);
5183 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5184 &out, native_ordering);
5185 }
5186 if (pos == len)
5187 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005188
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005189 rep = unicode_encode_call_errorhandler(
5190 errors, &errorHandler,
5191 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005192 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005193 if (!rep)
5194 goto error;
5195
5196 if (PyBytes_Check(rep)) {
5197 repsize = PyBytes_GET_SIZE(rep);
5198 if (repsize & 3) {
5199 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005200 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005201 "surrogates not allowed");
5202 goto error;
5203 }
5204 moreunits = repsize / 4;
5205 }
5206 else {
5207 assert(PyUnicode_Check(rep));
5208 if (PyUnicode_READY(rep) < 0)
5209 goto error;
5210 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5211 if (!PyUnicode_IS_ASCII(rep)) {
5212 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005213 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005214 "surrogates not allowed");
5215 goto error;
5216 }
5217 }
5218
5219 /* four bytes are reserved for each surrogate */
5220 if (moreunits > 1) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005221 Py_ssize_t outpos = out - (PY_UINT32_T*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005222 Py_ssize_t morebytes = 4 * (moreunits - 1);
5223 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5224 /* integer overflow */
5225 PyErr_NoMemory();
5226 goto error;
5227 }
5228 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5229 goto error;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005230 out = (PY_UINT32_T*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005231 }
5232
5233 if (PyBytes_Check(rep)) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005234 Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
5235 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005236 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005237 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005238 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5239 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005240 }
5241
5242 Py_CLEAR(rep);
5243 }
5244
5245 /* Cut back to size actually needed. This is necessary for, for example,
5246 encoding of a string containing isolated surrogates and the 'ignore'
5247 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005248 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005249 if (nsize != PyBytes_GET_SIZE(v))
5250 _PyBytes_Resize(&v, nsize);
5251 Py_XDECREF(errorHandler);
5252 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005253 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005254 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005255 error:
5256 Py_XDECREF(rep);
5257 Py_XDECREF(errorHandler);
5258 Py_XDECREF(exc);
5259 Py_XDECREF(v);
5260 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005261}
5262
Alexander Belopolsky40018472011-02-26 01:02:56 +00005263PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005264PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5265 Py_ssize_t size,
5266 const char *errors,
5267 int byteorder)
5268{
5269 PyObject *result;
5270 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5271 if (tmp == NULL)
5272 return NULL;
5273 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5274 Py_DECREF(tmp);
5275 return result;
5276}
5277
5278PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005279PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005280{
Victor Stinnerb960b342011-11-20 19:12:52 +01005281 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005282}
5283
Guido van Rossumd57fd912000-03-10 22:53:23 +00005284/* --- UTF-16 Codec ------------------------------------------------------- */
5285
Tim Peters772747b2001-08-09 22:21:55 +00005286PyObject *
5287PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005288 Py_ssize_t size,
5289 const char *errors,
5290 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005291{
Walter Dörwald69652032004-09-07 20:24:22 +00005292 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5293}
5294
5295PyObject *
5296PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005297 Py_ssize_t size,
5298 const char *errors,
5299 int *byteorder,
5300 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005301{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005302 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005303 Py_ssize_t startinpos;
5304 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005305 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005306 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005307 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005308 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005309 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005310 PyObject *errorHandler = NULL;
5311 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005312 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005313
Tim Peters772747b2001-08-09 22:21:55 +00005314 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005315 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005316
5317 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005318 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005319
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005320 /* Check for BOM marks (U+FEFF) in the input and adjust current
5321 byte order setting accordingly. In native mode, the leading BOM
5322 mark is skipped, in all other modes, it is copied to the output
5323 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005324 if (bo == 0 && size >= 2) {
5325 const Py_UCS4 bom = (q[1] << 8) | q[0];
5326 if (bom == 0xFEFF) {
5327 q += 2;
5328 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005329 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005330 else if (bom == 0xFFFE) {
5331 q += 2;
5332 bo = 1;
5333 }
5334 if (byteorder)
5335 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005336 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005337
Antoine Pitrou63065d72012-05-15 23:48:04 +02005338 if (q == e) {
5339 if (consumed)
5340 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005341 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005342 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005343
Christian Heimes743e0cd2012-10-17 23:52:17 +02005344#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005345 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005346 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005347#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005348 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005349 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005350#endif
Tim Peters772747b2001-08-09 22:21:55 +00005351
Antoine Pitrou63065d72012-05-15 23:48:04 +02005352 /* Note: size will always be longer than the resulting Unicode
5353 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005354 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005355 writer.min_length = (e - q + 1) / 2;
5356 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005357 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005358
Antoine Pitrou63065d72012-05-15 23:48:04 +02005359 while (1) {
5360 Py_UCS4 ch = 0;
5361 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005362 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005363 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005364 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005365 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005366 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005367 native_ordering);
5368 else
5369 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005370 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005371 native_ordering);
5372 } else if (kind == PyUnicode_2BYTE_KIND) {
5373 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005374 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005375 native_ordering);
5376 } else {
5377 assert(kind == PyUnicode_4BYTE_KIND);
5378 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005379 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005380 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005381 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005382 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005383
Antoine Pitrou63065d72012-05-15 23:48:04 +02005384 switch (ch)
5385 {
5386 case 0:
5387 /* remaining byte at the end? (size should be even) */
5388 if (q == e || consumed)
5389 goto End;
5390 errmsg = "truncated data";
5391 startinpos = ((const char *)q) - starts;
5392 endinpos = ((const char *)e) - starts;
5393 break;
5394 /* The remaining input chars are ignored if the callback
5395 chooses to skip the input */
5396 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005397 q -= 2;
5398 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005399 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005400 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005401 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005402 endinpos = ((const char *)e) - starts;
5403 break;
5404 case 2:
5405 errmsg = "illegal encoding";
5406 startinpos = ((const char *)q) - 2 - starts;
5407 endinpos = startinpos + 2;
5408 break;
5409 case 3:
5410 errmsg = "illegal UTF-16 surrogate";
5411 startinpos = ((const char *)q) - 4 - starts;
5412 endinpos = startinpos + 2;
5413 break;
5414 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005415 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005416 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005417 continue;
5418 }
5419
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005420 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005421 errors,
5422 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005423 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005424 &starts,
5425 (const char **)&e,
5426 &startinpos,
5427 &endinpos,
5428 &exc,
5429 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005430 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005431 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005432 }
5433
Antoine Pitrou63065d72012-05-15 23:48:04 +02005434End:
Walter Dörwald69652032004-09-07 20:24:22 +00005435 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005436 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005437
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005438 Py_XDECREF(errorHandler);
5439 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005440 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005441
Benjamin Peterson29060642009-01-31 22:14:21 +00005442 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005443 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005444 Py_XDECREF(errorHandler);
5445 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005446 return NULL;
5447}
5448
Tim Peters772747b2001-08-09 22:21:55 +00005449PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005450_PyUnicode_EncodeUTF16(PyObject *str,
5451 const char *errors,
5452 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005453{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005454 enum PyUnicode_Kind kind;
5455 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005456 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005457 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005458 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005459 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005460#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005461 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005462#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005463 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005464#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005465 const char *encoding;
5466 Py_ssize_t nsize, pos;
5467 PyObject *errorHandler = NULL;
5468 PyObject *exc = NULL;
5469 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005470
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005471 if (!PyUnicode_Check(str)) {
5472 PyErr_BadArgument();
5473 return NULL;
5474 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005475 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005476 return NULL;
5477 kind = PyUnicode_KIND(str);
5478 data = PyUnicode_DATA(str);
5479 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005480
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005481 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005482 if (kind == PyUnicode_4BYTE_KIND) {
5483 const Py_UCS4 *in = (const Py_UCS4 *)data;
5484 const Py_UCS4 *end = in + len;
5485 while (in < end)
5486 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005487 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005488 }
5489 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005490 return PyErr_NoMemory();
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005491 nsize = len + pairs + (byteorder == 0);
5492 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005493 if (v == NULL)
5494 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005495
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005496 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005497 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005498 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005499 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005500 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005501 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005502 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005503
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005504 if (kind == PyUnicode_1BYTE_KIND) {
5505 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5506 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005507 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005508
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005509 if (byteorder < 0)
5510 encoding = "utf-16-le";
5511 else if (byteorder > 0)
5512 encoding = "utf-16-be";
5513 else
5514 encoding = "utf-16";
5515
5516 pos = 0;
5517 while (pos < len) {
5518 Py_ssize_t repsize, moreunits;
5519
5520 if (kind == PyUnicode_2BYTE_KIND) {
5521 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5522 &out, native_ordering);
5523 }
5524 else {
5525 assert(kind == PyUnicode_4BYTE_KIND);
5526 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5527 &out, native_ordering);
5528 }
5529 if (pos == len)
5530 break;
5531
5532 rep = unicode_encode_call_errorhandler(
5533 errors, &errorHandler,
5534 encoding, "surrogates not allowed",
5535 str, &exc, pos, pos + 1, &pos);
5536 if (!rep)
5537 goto error;
5538
5539 if (PyBytes_Check(rep)) {
5540 repsize = PyBytes_GET_SIZE(rep);
5541 if (repsize & 1) {
5542 raise_encode_exception(&exc, encoding,
5543 str, pos - 1, pos,
5544 "surrogates not allowed");
5545 goto error;
5546 }
5547 moreunits = repsize / 2;
5548 }
5549 else {
5550 assert(PyUnicode_Check(rep));
5551 if (PyUnicode_READY(rep) < 0)
5552 goto error;
5553 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5554 if (!PyUnicode_IS_ASCII(rep)) {
5555 raise_encode_exception(&exc, encoding,
5556 str, pos - 1, pos,
5557 "surrogates not allowed");
5558 goto error;
5559 }
5560 }
5561
5562 /* two bytes are reserved for each surrogate */
5563 if (moreunits > 1) {
5564 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
5565 Py_ssize_t morebytes = 2 * (moreunits - 1);
5566 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5567 /* integer overflow */
5568 PyErr_NoMemory();
5569 goto error;
5570 }
5571 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5572 goto error;
5573 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5574 }
5575
5576 if (PyBytes_Check(rep)) {
5577 Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
5578 out += moreunits;
5579 } else /* rep is unicode */ {
5580 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5581 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5582 &out, native_ordering);
5583 }
5584
5585 Py_CLEAR(rep);
5586 }
5587
5588 /* Cut back to size actually needed. This is necessary for, for example,
5589 encoding of a string containing isolated surrogates and the 'ignore' handler
5590 is used. */
5591 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5592 if (nsize != PyBytes_GET_SIZE(v))
5593 _PyBytes_Resize(&v, nsize);
5594 Py_XDECREF(errorHandler);
5595 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005596 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005597 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005598 error:
5599 Py_XDECREF(rep);
5600 Py_XDECREF(errorHandler);
5601 Py_XDECREF(exc);
5602 Py_XDECREF(v);
5603 return NULL;
5604#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005605}
5606
Alexander Belopolsky40018472011-02-26 01:02:56 +00005607PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005608PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5609 Py_ssize_t size,
5610 const char *errors,
5611 int byteorder)
5612{
5613 PyObject *result;
5614 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5615 if (tmp == NULL)
5616 return NULL;
5617 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5618 Py_DECREF(tmp);
5619 return result;
5620}
5621
5622PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005623PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005624{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005625 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005626}
5627
5628/* --- Unicode Escape Codec ----------------------------------------------- */
5629
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005630/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5631 if all the escapes in the string make it still a valid ASCII string.
5632 Returns -1 if any escapes were found which cause the string to
5633 pop out of ASCII range. Otherwise returns the length of the
5634 required buffer to hold the string.
5635 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005636static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005637length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5638{
5639 const unsigned char *p = (const unsigned char *)s;
5640 const unsigned char *end = p + size;
5641 Py_ssize_t length = 0;
5642
5643 if (size < 0)
5644 return -1;
5645
5646 for (; p < end; ++p) {
5647 if (*p > 127) {
5648 /* Non-ASCII */
5649 return -1;
5650 }
5651 else if (*p != '\\') {
5652 /* Normal character */
5653 ++length;
5654 }
5655 else {
5656 /* Backslash-escape, check next char */
5657 ++p;
5658 /* Escape sequence reaches till end of string or
5659 non-ASCII follow-up. */
5660 if (p >= end || *p > 127)
5661 return -1;
5662 switch (*p) {
5663 case '\n':
5664 /* backslash + \n result in zero characters */
5665 break;
5666 case '\\': case '\'': case '\"':
5667 case 'b': case 'f': case 't':
5668 case 'n': case 'r': case 'v': case 'a':
5669 ++length;
5670 break;
5671 case '0': case '1': case '2': case '3':
5672 case '4': case '5': case '6': case '7':
5673 case 'x': case 'u': case 'U': case 'N':
5674 /* these do not guarantee ASCII characters */
5675 return -1;
5676 default:
5677 /* count the backslash + the other character */
5678 length += 2;
5679 }
5680 }
5681 }
5682 return length;
5683}
5684
Fredrik Lundh06d12682001-01-24 07:59:11 +00005685static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005686
Alexander Belopolsky40018472011-02-26 01:02:56 +00005687PyObject *
5688PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005689 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005690 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005691{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005692 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005693 Py_ssize_t startinpos;
5694 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005695 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005696 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005697 char* message;
5698 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005699 PyObject *errorHandler = NULL;
5700 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005701 Py_ssize_t len;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005702
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005703 len = length_of_escaped_ascii_string(s, size);
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005704 if (len == 0)
5705 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005706
5707 /* After length_of_escaped_ascii_string() there are two alternatives,
5708 either the string is pure ASCII with named escapes like \n, etc.
5709 and we determined it's exact size (common case)
5710 or it contains \x, \u, ... escape sequences. then we create a
5711 legacy wchar string and resize it at the end of this function. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005712 _PyUnicodeWriter_Init(&writer);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005713 if (len > 0) {
Victor Stinner8f674cc2013-04-17 23:02:17 +02005714 writer.min_length = len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005715 }
5716 else {
5717 /* Escaped strings will always be longer than the resulting
5718 Unicode string, so we start with size here and then reduce the
5719 length after conversion to the true value.
5720 (but if the error callback returns a long replacement string
5721 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005722 writer.min_length = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005723 }
5724
Guido van Rossumd57fd912000-03-10 22:53:23 +00005725 if (size == 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005726 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005727 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005728
Guido van Rossumd57fd912000-03-10 22:53:23 +00005729 while (s < end) {
5730 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005731 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005732 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005733
5734 /* Non-escape characters are interpreted as Unicode ordinals */
5735 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005736 x = (unsigned char)*s;
5737 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005738 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005739 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005740 continue;
5741 }
5742
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005743 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005744 /* \ - Escapes */
5745 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005746 c = *s++;
5747 if (s > end)
5748 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005749
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005750 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005751
Benjamin Peterson29060642009-01-31 22:14:21 +00005752 /* \x escapes */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005753#define WRITECHAR(ch) \
5754 do { \
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005755 if (_PyUnicodeWriter_WriteCharInline(&writer, (ch)) < 0) \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005756 goto onError; \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005757 } while(0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005758
Guido van Rossumd57fd912000-03-10 22:53:23 +00005759 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005760 case '\\': WRITECHAR('\\'); break;
5761 case '\'': WRITECHAR('\''); break;
5762 case '\"': WRITECHAR('\"'); break;
5763 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005764 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005765 case 'f': WRITECHAR('\014'); break;
5766 case 't': WRITECHAR('\t'); break;
5767 case 'n': WRITECHAR('\n'); break;
5768 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005769 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005770 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005771 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005772 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005773
Benjamin Peterson29060642009-01-31 22:14:21 +00005774 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005775 case '0': case '1': case '2': case '3':
5776 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005777 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005778 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005779 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005780 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005781 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005782 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005783 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005784 break;
5785
Benjamin Peterson29060642009-01-31 22:14:21 +00005786 /* hex escapes */
5787 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005788 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005789 digits = 2;
5790 message = "truncated \\xXX escape";
5791 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005792
Benjamin Peterson29060642009-01-31 22:14:21 +00005793 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005794 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005795 digits = 4;
5796 message = "truncated \\uXXXX escape";
5797 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005798
Benjamin Peterson29060642009-01-31 22:14:21 +00005799 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005800 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005801 digits = 8;
5802 message = "truncated \\UXXXXXXXX escape";
5803 hexescape:
5804 chr = 0;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005805 if (end - s < digits) {
5806 /* count only hex digits */
5807 for (; s < end; ++s) {
5808 c = (unsigned char)*s;
5809 if (!Py_ISXDIGIT(c))
5810 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005811 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005812 goto error;
5813 }
5814 for (; digits--; ++s) {
5815 c = (unsigned char)*s;
5816 if (!Py_ISXDIGIT(c))
5817 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005818 chr = (chr<<4) & ~0xF;
5819 if (c >= '0' && c <= '9')
5820 chr += c - '0';
5821 else if (c >= 'a' && c <= 'f')
5822 chr += 10 + c - 'a';
5823 else
5824 chr += 10 + c - 'A';
5825 }
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005826 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005827 /* _decoding_error will have already written into the
5828 target buffer. */
5829 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005830 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005831 /* when we get here, chr is a 32-bit unicode character */
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005832 message = "illegal Unicode character";
5833 if (chr > MAX_UNICODE)
Serhiy Storchakad6793772013-01-29 10:20:44 +02005834 goto error;
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005835 WRITECHAR(chr);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005836 break;
5837
Benjamin Peterson29060642009-01-31 22:14:21 +00005838 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005839 case 'N':
5840 message = "malformed \\N character escape";
5841 if (ucnhash_CAPI == NULL) {
5842 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005843 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5844 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005845 if (ucnhash_CAPI == NULL)
5846 goto ucnhashError;
5847 }
5848 if (*s == '{') {
5849 const char *start = s+1;
5850 /* look for the closing brace */
5851 while (*s != '}' && s < end)
5852 s++;
5853 if (s > start && s < end && *s == '}') {
5854 /* found a name. look it up in the unicode database */
5855 message = "unknown Unicode character name";
5856 s++;
Serhiy Storchaka4f5f0e52013-01-21 11:38:00 +02005857 if (s - start - 1 <= INT_MAX &&
Serhiy Storchakac35f3a92013-01-21 11:42:57 +02005858 ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005859 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005860 goto store;
5861 }
5862 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005863 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005864
5865 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005866 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005867 message = "\\ at end of string";
5868 s--;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005869 goto error;
Walter Dörwald8c077222002-03-25 11:16:18 +00005870 }
5871 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005872 WRITECHAR('\\');
Serhiy Storchaka73e38802013-01-25 23:52:21 +02005873 WRITECHAR((unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005874 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005875 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005876 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005877 continue;
5878
5879 error:
5880 endinpos = s-starts;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005881 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02005882 errors, &errorHandler,
5883 "unicodeescape", message,
5884 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005885 &writer))
Serhiy Storchakad6793772013-01-29 10:20:44 +02005886 goto onError;
5887 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005888 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005889#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005890
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005891 Py_XDECREF(errorHandler);
5892 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005893 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00005894
Benjamin Peterson29060642009-01-31 22:14:21 +00005895 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005896 PyErr_SetString(
5897 PyExc_UnicodeError,
5898 "\\N escapes not supported (can't load unicodedata module)"
5899 );
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005900 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005901 Py_XDECREF(errorHandler);
5902 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005903 return NULL;
5904
Benjamin Peterson29060642009-01-31 22:14:21 +00005905 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005906 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005907 Py_XDECREF(errorHandler);
5908 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005909 return NULL;
5910}
5911
5912/* Return a Unicode-Escape string version of the Unicode object.
5913
5914 If quotes is true, the string is enclosed in u"" or u'' quotes as
5915 appropriate.
5916
5917*/
5918
Alexander Belopolsky40018472011-02-26 01:02:56 +00005919PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005920PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005921{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005922 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005923 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005924 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005925 int kind;
5926 void *data;
5927 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005928
Ezio Melottie7f90372012-10-05 03:33:31 +03005929 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00005930 escape.
5931
Ezio Melottie7f90372012-10-05 03:33:31 +03005932 For UCS1 strings it's '\xxx', 4 bytes per source character.
5933 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
5934 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00005935 */
5936
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005937 if (!PyUnicode_Check(unicode)) {
5938 PyErr_BadArgument();
5939 return NULL;
5940 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005941 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005942 return NULL;
5943 len = PyUnicode_GET_LENGTH(unicode);
5944 kind = PyUnicode_KIND(unicode);
5945 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06005946 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005947 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5948 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5949 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5950 }
5951
5952 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005953 return PyBytes_FromStringAndSize(NULL, 0);
5954
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005955 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005956 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005957
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005958 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005959 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005960 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005961 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005962 if (repr == NULL)
5963 return NULL;
5964
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005965 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005966
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005967 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005968 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005969
Walter Dörwald79e913e2007-05-12 11:08:06 +00005970 /* Escape backslashes */
5971 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005972 *p++ = '\\';
5973 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005974 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005975 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005976
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005977 /* Map 21-bit characters to '\U00xxxxxx' */
5978 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005979 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005980 *p++ = '\\';
5981 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005982 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5983 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5984 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5985 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5986 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5987 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5988 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5989 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005990 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005991 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005992
Guido van Rossumd57fd912000-03-10 22:53:23 +00005993 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005994 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005995 *p++ = '\\';
5996 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005997 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5998 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5999 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6000 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006001 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006002
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006003 /* Map special whitespace to '\t', \n', '\r' */
6004 else if (ch == '\t') {
6005 *p++ = '\\';
6006 *p++ = 't';
6007 }
6008 else if (ch == '\n') {
6009 *p++ = '\\';
6010 *p++ = 'n';
6011 }
6012 else if (ch == '\r') {
6013 *p++ = '\\';
6014 *p++ = 'r';
6015 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006016
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006017 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006018 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006019 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006020 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006021 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6022 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006023 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006024
Guido van Rossumd57fd912000-03-10 22:53:23 +00006025 /* Copy everything else as-is */
6026 else
6027 *p++ = (char) ch;
6028 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006029
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006030 assert(p - PyBytes_AS_STRING(repr) > 0);
6031 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6032 return NULL;
6033 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006034}
6035
Alexander Belopolsky40018472011-02-26 01:02:56 +00006036PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006037PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6038 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006039{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006040 PyObject *result;
6041 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6042 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006043 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006044 result = PyUnicode_AsUnicodeEscapeString(tmp);
6045 Py_DECREF(tmp);
6046 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006047}
6048
6049/* --- Raw Unicode Escape Codec ------------------------------------------- */
6050
Alexander Belopolsky40018472011-02-26 01:02:56 +00006051PyObject *
6052PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006053 Py_ssize_t size,
6054 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006055{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006056 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006057 Py_ssize_t startinpos;
6058 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006059 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006060 const char *end;
6061 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006062 PyObject *errorHandler = NULL;
6063 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006064
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006065 if (size == 0)
6066 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006067
Guido van Rossumd57fd912000-03-10 22:53:23 +00006068 /* Escaped strings will always be longer than the resulting
6069 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006070 length after conversion to the true value. (But decoding error
6071 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006072 _PyUnicodeWriter_Init(&writer);
6073 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006074
Guido van Rossumd57fd912000-03-10 22:53:23 +00006075 end = s + size;
6076 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006077 unsigned char c;
6078 Py_UCS4 x;
6079 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006080 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006081
Benjamin Peterson29060642009-01-31 22:14:21 +00006082 /* Non-escape characters are interpreted as Unicode ordinals */
6083 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006084 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006085 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006086 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006087 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006088 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006089 startinpos = s-starts;
6090
6091 /* \u-escapes are only interpreted iff the number of leading
6092 backslashes if odd */
6093 bs = s;
6094 for (;s < end;) {
6095 if (*s != '\\')
6096 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006097 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006098 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006099 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006100 }
6101 if (((s - bs) & 1) == 0 ||
6102 s >= end ||
6103 (*s != 'u' && *s != 'U')) {
6104 continue;
6105 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006106 writer.pos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006107 count = *s=='u' ? 4 : 8;
6108 s++;
6109
6110 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006111 for (x = 0, i = 0; i < count; ++i, ++s) {
6112 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006113 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006114 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006115 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006116 errors, &errorHandler,
6117 "rawunicodeescape", "truncated \\uXXXX",
6118 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006119 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006120 goto onError;
6121 goto nextByte;
6122 }
6123 x = (x<<4) & ~0xF;
6124 if (c >= '0' && c <= '9')
6125 x += c - '0';
6126 else if (c >= 'a' && c <= 'f')
6127 x += 10 + c - 'a';
6128 else
6129 x += 10 + c - 'A';
6130 }
Victor Stinner8faf8212011-12-08 22:14:11 +01006131 if (x <= MAX_UNICODE) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006132 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006133 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006134 }
6135 else {
Christian Heimesfe337bf2008-03-23 21:54:12 +00006136 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006137 if (unicode_decode_call_errorhandler_writer(
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006138 errors, &errorHandler,
6139 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006140 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006141 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006142 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006143 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006144 nextByte:
6145 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006146 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006147 Py_XDECREF(errorHandler);
6148 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006149 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006150
Benjamin Peterson29060642009-01-31 22:14:21 +00006151 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006152 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006153 Py_XDECREF(errorHandler);
6154 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006155 return NULL;
6156}
6157
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006158
Alexander Belopolsky40018472011-02-26 01:02:56 +00006159PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006160PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006161{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006162 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006163 char *p;
6164 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006165 Py_ssize_t expandsize, pos;
6166 int kind;
6167 void *data;
6168 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006169
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006170 if (!PyUnicode_Check(unicode)) {
6171 PyErr_BadArgument();
6172 return NULL;
6173 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006174 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006175 return NULL;
6176 kind = PyUnicode_KIND(unicode);
6177 data = PyUnicode_DATA(unicode);
6178 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006179 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6180 bytes, and 1 byte characters 4. */
6181 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006182
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006183 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006184 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006185
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006186 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006187 if (repr == NULL)
6188 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006189 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006190 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006191
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006192 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006193 for (pos = 0; pos < len; pos++) {
6194 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006195 /* Map 32-bit characters to '\Uxxxxxxxx' */
6196 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006197 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006198 *p++ = '\\';
6199 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006200 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6201 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6202 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6203 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6204 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6205 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6206 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6207 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006208 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006209 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006210 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006211 *p++ = '\\';
6212 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006213 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6214 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6215 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6216 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006217 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006218 /* Copy everything else as-is */
6219 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006220 *p++ = (char) ch;
6221 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006222
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006223 assert(p > q);
6224 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006225 return NULL;
6226 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006227}
6228
Alexander Belopolsky40018472011-02-26 01:02:56 +00006229PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006230PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6231 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006232{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006233 PyObject *result;
6234 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6235 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006236 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006237 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6238 Py_DECREF(tmp);
6239 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006240}
6241
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006242/* --- Unicode Internal Codec ------------------------------------------- */
6243
Alexander Belopolsky40018472011-02-26 01:02:56 +00006244PyObject *
6245_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006246 Py_ssize_t size,
6247 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006248{
6249 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006250 Py_ssize_t startinpos;
6251 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006252 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006253 const char *end;
6254 const char *reason;
6255 PyObject *errorHandler = NULL;
6256 PyObject *exc = NULL;
6257
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006258 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006259 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006260 1))
6261 return NULL;
6262
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006263 if (size == 0)
6264 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006265
Victor Stinner8f674cc2013-04-17 23:02:17 +02006266 _PyUnicodeWriter_Init(&writer);
6267 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6268 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006269 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006270 }
6271 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006272
Victor Stinner8f674cc2013-04-17 23:02:17 +02006273 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006274 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006275 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006276 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006277 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006278 endinpos = end-starts;
6279 reason = "truncated input";
6280 goto error;
6281 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006282 /* We copy the raw representation one byte at a time because the
6283 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006284 ((char *) &uch)[0] = s[0];
6285 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006286#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006287 ((char *) &uch)[2] = s[2];
6288 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006289#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006290 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006291#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006292 /* We have to sanity check the raw data, otherwise doom looms for
6293 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006294 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006295 endinpos = s - starts + Py_UNICODE_SIZE;
6296 reason = "illegal code point (> 0x10FFFF)";
6297 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006298 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006299#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006300 s += Py_UNICODE_SIZE;
6301#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006302 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006303 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006304 Py_UNICODE uch2;
6305 ((char *) &uch2)[0] = s[0];
6306 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006307 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006308 {
Victor Stinner551ac952011-11-29 22:58:13 +01006309 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006310 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006311 }
6312 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006313#endif
6314
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006315 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006316 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006317 continue;
6318
6319 error:
6320 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006321 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006322 errors, &errorHandler,
6323 "unicode_internal", reason,
6324 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006325 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006326 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006327 }
6328
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006329 Py_XDECREF(errorHandler);
6330 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006331 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006332
Benjamin Peterson29060642009-01-31 22:14:21 +00006333 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006334 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006335 Py_XDECREF(errorHandler);
6336 Py_XDECREF(exc);
6337 return NULL;
6338}
6339
Guido van Rossumd57fd912000-03-10 22:53:23 +00006340/* --- Latin-1 Codec ------------------------------------------------------ */
6341
Alexander Belopolsky40018472011-02-26 01:02:56 +00006342PyObject *
6343PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006344 Py_ssize_t size,
6345 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006346{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006347 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006348 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006349}
6350
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006351/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006352static void
6353make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006354 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006355 PyObject *unicode,
6356 Py_ssize_t startpos, Py_ssize_t endpos,
6357 const char *reason)
6358{
6359 if (*exceptionObject == NULL) {
6360 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006361 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006362 encoding, unicode, startpos, endpos, reason);
6363 }
6364 else {
6365 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6366 goto onError;
6367 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6368 goto onError;
6369 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6370 goto onError;
6371 return;
6372 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006373 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006374 }
6375}
6376
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006377/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006378static void
6379raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006380 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006381 PyObject *unicode,
6382 Py_ssize_t startpos, Py_ssize_t endpos,
6383 const char *reason)
6384{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006385 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006386 encoding, unicode, startpos, endpos, reason);
6387 if (*exceptionObject != NULL)
6388 PyCodec_StrictErrors(*exceptionObject);
6389}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006390
6391/* error handling callback helper:
6392 build arguments, call the callback and check the arguments,
6393 put the result into newpos and return the replacement string, which
6394 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006395static PyObject *
6396unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006397 PyObject **errorHandler,
6398 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006399 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006400 Py_ssize_t startpos, Py_ssize_t endpos,
6401 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006402{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006403 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006404 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006405 PyObject *restuple;
6406 PyObject *resunicode;
6407
6408 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006409 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006410 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006411 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006412 }
6413
Benjamin Petersonbac79492012-01-14 13:34:47 -05006414 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006415 return NULL;
6416 len = PyUnicode_GET_LENGTH(unicode);
6417
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006418 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006419 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006420 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006421 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006422
6423 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006424 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006425 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006426 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006427 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006428 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006429 Py_DECREF(restuple);
6430 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006431 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006432 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006433 &resunicode, newpos)) {
6434 Py_DECREF(restuple);
6435 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006436 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006437 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6438 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6439 Py_DECREF(restuple);
6440 return NULL;
6441 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006442 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006443 *newpos = len + *newpos;
6444 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006445 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006446 Py_DECREF(restuple);
6447 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006448 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006449 Py_INCREF(resunicode);
6450 Py_DECREF(restuple);
6451 return resunicode;
6452}
6453
Alexander Belopolsky40018472011-02-26 01:02:56 +00006454static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006455unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006456 const char *errors,
Victor Stinner0030cd52015-09-24 14:45:00 +02006457 const Py_UCS4 limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006458{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006459 /* input state */
6460 Py_ssize_t pos=0, size;
6461 int kind;
6462 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006463 /* output object */
6464 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006465 /* pointer into the output */
6466 char *str;
6467 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006468 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006469 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6470 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006471 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006472 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006473 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006474
Benjamin Petersonbac79492012-01-14 13:34:47 -05006475 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006476 return NULL;
6477 size = PyUnicode_GET_LENGTH(unicode);
6478 kind = PyUnicode_KIND(unicode);
6479 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006480 /* allocate enough for a simple encoding without
6481 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006482 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006483 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006484 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006485 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006486 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006487 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006488 ressize = size;
6489
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006490 while (pos < size) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006491 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006492
Benjamin Peterson29060642009-01-31 22:14:21 +00006493 /* can we encode this? */
Victor Stinner0030cd52015-09-24 14:45:00 +02006494 if (ch < limit) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006495 /* no overflow check, because we know that the space is enough */
Victor Stinner0030cd52015-09-24 14:45:00 +02006496 *str++ = (char)ch;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006497 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006498 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006499 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006500 Py_ssize_t requiredsize;
6501 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006502 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006503 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006504 Py_ssize_t collstart = pos;
6505 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006506 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006507
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006508 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006509 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006510
Benjamin Peterson29060642009-01-31 22:14:21 +00006511 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006512 if (error_handler == _Py_ERROR_UNKNOWN)
6513 error_handler = get_error_handler(errors);
6514
6515 switch (error_handler) {
6516 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006517 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006518 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006519
6520 case _Py_ERROR_REPLACE:
Victor Stinner01ada392015-10-01 21:54:51 +02006521 memset(str, '?', collend - collstart);
6522 str += (collend - collstart);
Victor Stinner0030cd52015-09-24 14:45:00 +02006523 /* fall through ignore error handler */
Victor Stinner50149202015-09-22 00:26:54 +02006524 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006525 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006526 break;
Victor Stinner50149202015-09-22 00:26:54 +02006527
6528 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson29060642009-01-31 22:14:21 +00006529 respos = str - PyBytes_AS_STRING(res);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006530 requiredsize = respos;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006531 /* determine replacement size */
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006532 for (i = collstart; i < collend; ++i) {
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006533 Py_ssize_t incr;
Victor Stinner0030cd52015-09-24 14:45:00 +02006534
6535 ch = PyUnicode_READ(kind, data, i);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006536 if (ch < 10)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006537 incr = 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006538 else if (ch < 100)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006539 incr = 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006540 else if (ch < 1000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006541 incr = 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006542 else if (ch < 10000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006543 incr = 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006544 else if (ch < 100000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006545 incr = 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006546 else if (ch < 1000000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006547 incr = 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006548 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006549 assert(ch <= MAX_UNICODE);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006550 incr = 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006551 }
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006552 if (requiredsize > PY_SSIZE_T_MAX - incr)
6553 goto overflow;
6554 requiredsize += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +00006555 }
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006556 if (requiredsize > PY_SSIZE_T_MAX - (size - collend))
6557 goto overflow;
6558 requiredsize += size - collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006559 if (requiredsize > ressize) {
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006560 if (ressize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*ressize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006561 requiredsize = 2*ressize;
6562 if (_PyBytes_Resize(&res, requiredsize))
6563 goto onError;
6564 str = PyBytes_AS_STRING(res) + respos;
6565 ressize = requiredsize;
6566 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006567 /* generate replacement */
6568 for (i = collstart; i < collend; ++i) {
6569 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006570 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006571 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006572 break;
Victor Stinner50149202015-09-22 00:26:54 +02006573
Victor Stinnerc3713e92015-09-29 12:32:13 +02006574 case _Py_ERROR_SURROGATEESCAPE:
6575 for (i = collstart; i < collend; ++i) {
6576 ch = PyUnicode_READ(kind, data, i);
6577 if (ch < 0xdc80 || 0xdcff < ch) {
6578 /* Not a UTF-8b surrogate */
6579 break;
6580 }
6581 *str++ = (char)(ch - 0xdc00);
6582 ++pos;
6583 }
6584 if (i >= collend)
6585 break;
6586 collstart = pos;
6587 assert(collstart != collend);
6588 /* fallback to general error handling */
6589
Benjamin Peterson29060642009-01-31 22:14:21 +00006590 default:
Victor Stinner50149202015-09-22 00:26:54 +02006591 repunicode = unicode_encode_call_errorhandler(errors, &error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006592 encoding, reason, unicode, &exc,
6593 collstart, collend, &newpos);
6594 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006595 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006596 goto onError;
Victor Stinner0030cd52015-09-24 14:45:00 +02006597
Martin v. Löwis011e8422009-05-05 04:43:17 +00006598 if (PyBytes_Check(repunicode)) {
6599 /* Directly copy bytes result to output. */
6600 repsize = PyBytes_Size(repunicode);
6601 if (repsize > 1) {
6602 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006603 respos = str - PyBytes_AS_STRING(res);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006604 if (ressize > PY_SSIZE_T_MAX - repsize - 1) {
6605 Py_DECREF(repunicode);
6606 goto overflow;
6607 }
Martin v. Löwis011e8422009-05-05 04:43:17 +00006608 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6609 Py_DECREF(repunicode);
6610 goto onError;
6611 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006612 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006613 ressize += repsize-1;
6614 }
6615 memcpy(str, PyBytes_AsString(repunicode), repsize);
6616 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006617 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006618 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006619 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006620 }
Victor Stinner0030cd52015-09-24 14:45:00 +02006621
Benjamin Peterson29060642009-01-31 22:14:21 +00006622 /* need more space? (at least enough for what we
6623 have+the replacement+the rest of the string, so
6624 we won't have to check space for encodable characters) */
6625 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006626 repsize = PyUnicode_GET_LENGTH(repunicode);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006627 requiredsize = respos;
6628 if (requiredsize > PY_SSIZE_T_MAX - repsize)
6629 goto overflow;
6630 requiredsize += repsize;
6631 if (requiredsize > PY_SSIZE_T_MAX - (size - collend))
6632 goto overflow;
6633 requiredsize += size - collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006634 if (requiredsize > ressize) {
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006635 if (ressize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*ressize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006636 requiredsize = 2*ressize;
6637 if (_PyBytes_Resize(&res, requiredsize)) {
6638 Py_DECREF(repunicode);
6639 goto onError;
6640 }
6641 str = PyBytes_AS_STRING(res) + respos;
6642 ressize = requiredsize;
6643 }
Victor Stinner0030cd52015-09-24 14:45:00 +02006644
Benjamin Peterson29060642009-01-31 22:14:21 +00006645 /* check if there is anything unencodable in the replacement
6646 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006647 for (i = 0; repsize-->0; ++i, ++str) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006648 ch = PyUnicode_READ_CHAR(repunicode, i);
6649 if (ch >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006650 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006651 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006652 Py_DECREF(repunicode);
6653 goto onError;
6654 }
Victor Stinner0030cd52015-09-24 14:45:00 +02006655 *str = (char)ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00006656 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006657 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006658 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006659 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006660 }
6661 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006662 /* Resize if we allocated to much */
6663 size = str - PyBytes_AS_STRING(res);
6664 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006665 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006666 if (_PyBytes_Resize(&res, size) < 0)
6667 goto onError;
6668 }
6669
Victor Stinner50149202015-09-22 00:26:54 +02006670 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006671 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006672 return res;
6673
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006674 overflow:
6675 PyErr_SetString(PyExc_OverflowError,
6676 "encoded result is too long for a Python string");
6677
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006678 onError:
6679 Py_XDECREF(res);
Victor Stinner50149202015-09-22 00:26:54 +02006680 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006681 Py_XDECREF(exc);
6682 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006683}
6684
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006685/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006686PyObject *
6687PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006688 Py_ssize_t size,
6689 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006690{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006691 PyObject *result;
6692 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6693 if (unicode == NULL)
6694 return NULL;
6695 result = unicode_encode_ucs1(unicode, errors, 256);
6696 Py_DECREF(unicode);
6697 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006698}
6699
Alexander Belopolsky40018472011-02-26 01:02:56 +00006700PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006701_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006702{
6703 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006704 PyErr_BadArgument();
6705 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006706 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006707 if (PyUnicode_READY(unicode) == -1)
6708 return NULL;
6709 /* Fast path: if it is a one-byte string, construct
6710 bytes object directly. */
6711 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6712 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6713 PyUnicode_GET_LENGTH(unicode));
6714 /* Non-Latin-1 characters present. Defer to above function to
6715 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006716 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006717}
6718
6719PyObject*
6720PyUnicode_AsLatin1String(PyObject *unicode)
6721{
6722 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006723}
6724
6725/* --- 7-bit ASCII Codec -------------------------------------------------- */
6726
Alexander Belopolsky40018472011-02-26 01:02:56 +00006727PyObject *
6728PyUnicode_DecodeASCII(const char *s,
6729 Py_ssize_t size,
6730 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006731{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006732 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006733 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006734 int kind;
6735 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006736 Py_ssize_t startinpos;
6737 Py_ssize_t endinpos;
6738 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006739 const char *e;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006740 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006741 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006742 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00006743
Guido van Rossumd57fd912000-03-10 22:53:23 +00006744 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006745 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006746
Guido van Rossumd57fd912000-03-10 22:53:23 +00006747 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006748 if (size == 1 && (unsigned char)s[0] < 128)
6749 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006750
Victor Stinner8f674cc2013-04-17 23:02:17 +02006751 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006752 writer.min_length = size;
6753 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006754 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006755
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006756 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006757 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006758 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006759 writer.pos = outpos;
6760 if (writer.pos == size)
6761 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006762
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006763 s += writer.pos;
6764 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006765 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006766 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006767 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006768 PyUnicode_WRITE(kind, data, writer.pos, c);
6769 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006770 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006771 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00006772 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006773
6774 /* byte outsize range 0x00..0x7f: call the error handler */
6775
6776 if (error_handler == _Py_ERROR_UNKNOWN)
6777 error_handler = get_error_handler(errors);
6778
6779 switch (error_handler)
6780 {
6781 case _Py_ERROR_REPLACE:
6782 case _Py_ERROR_SURROGATEESCAPE:
6783 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02006784 but we may switch to UCS2 at the first write */
6785 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
6786 goto onError;
6787 kind = writer.kind;
6788 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006789
6790 if (error_handler == _Py_ERROR_REPLACE)
6791 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
6792 else
6793 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
6794 writer.pos++;
6795 ++s;
6796 break;
6797
6798 case _Py_ERROR_IGNORE:
6799 ++s;
6800 break;
6801
6802 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00006803 startinpos = s-starts;
6804 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006805 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02006806 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00006807 "ascii", "ordinal not in range(128)",
6808 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006809 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006810 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006811 kind = writer.kind;
6812 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006813 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006814 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006815 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006816 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006817 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006818
Benjamin Peterson29060642009-01-31 22:14:21 +00006819 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006820 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02006821 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006822 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006823 return NULL;
6824}
6825
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006826/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006827PyObject *
6828PyUnicode_EncodeASCII(const Py_UNICODE *p,
6829 Py_ssize_t size,
6830 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006831{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006832 PyObject *result;
6833 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6834 if (unicode == NULL)
6835 return NULL;
6836 result = unicode_encode_ucs1(unicode, errors, 128);
6837 Py_DECREF(unicode);
6838 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006839}
6840
Alexander Belopolsky40018472011-02-26 01:02:56 +00006841PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006842_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006843{
6844 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006845 PyErr_BadArgument();
6846 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006847 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006848 if (PyUnicode_READY(unicode) == -1)
6849 return NULL;
6850 /* Fast path: if it is an ASCII-only string, construct bytes object
6851 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02006852 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006853 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6854 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006855 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006856}
6857
6858PyObject *
6859PyUnicode_AsASCIIString(PyObject *unicode)
6860{
6861 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006862}
6863
Victor Stinner99b95382011-07-04 14:23:54 +02006864#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006865
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006866/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006867
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006868#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006869#define NEED_RETRY
6870#endif
6871
Victor Stinner3a50e702011-10-18 21:21:00 +02006872#ifndef WC_ERR_INVALID_CHARS
6873# define WC_ERR_INVALID_CHARS 0x0080
6874#endif
6875
6876static char*
6877code_page_name(UINT code_page, PyObject **obj)
6878{
6879 *obj = NULL;
6880 if (code_page == CP_ACP)
6881 return "mbcs";
6882 if (code_page == CP_UTF7)
6883 return "CP_UTF7";
6884 if (code_page == CP_UTF8)
6885 return "CP_UTF8";
6886
6887 *obj = PyBytes_FromFormat("cp%u", code_page);
6888 if (*obj == NULL)
6889 return NULL;
6890 return PyBytes_AS_STRING(*obj);
6891}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006892
Victor Stinner3a50e702011-10-18 21:21:00 +02006893static DWORD
6894decode_code_page_flags(UINT code_page)
6895{
6896 if (code_page == CP_UTF7) {
6897 /* The CP_UTF7 decoder only supports flags=0 */
6898 return 0;
6899 }
6900 else
6901 return MB_ERR_INVALID_CHARS;
6902}
6903
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006904/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006905 * Decode a byte string from a Windows code page into unicode object in strict
6906 * mode.
6907 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006908 * Returns consumed size if succeed, returns -2 on decode error, or raise an
6909 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006910 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006911static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006912decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006913 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006914 const char *in,
6915 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006916{
Victor Stinner3a50e702011-10-18 21:21:00 +02006917 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006918 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006919 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006920
6921 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006922 assert(insize > 0);
6923 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6924 if (outsize <= 0)
6925 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006926
6927 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006928 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01006929 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006930 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006931 if (*v == NULL)
6932 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006933 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006934 }
6935 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006936 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006937 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01006938 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006939 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006940 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006941 }
6942
6943 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006944 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6945 if (outsize <= 0)
6946 goto error;
6947 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006948
Victor Stinner3a50e702011-10-18 21:21:00 +02006949error:
6950 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6951 return -2;
6952 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006953 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006954}
6955
Victor Stinner3a50e702011-10-18 21:21:00 +02006956/*
6957 * Decode a byte string from a code page into unicode object with an error
6958 * handler.
6959 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006960 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02006961 * UnicodeDecodeError exception and returns -1 on error.
6962 */
6963static int
6964decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006965 PyObject **v,
6966 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01006967 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02006968{
6969 const char *startin = in;
6970 const char *endin = in + size;
6971 const DWORD flags = decode_code_page_flags(code_page);
6972 /* Ideally, we should get reason from FormatMessage. This is the Windows
6973 2000 English version of the message. */
6974 const char *reason = "No mapping for the Unicode character exists "
6975 "in the target code page.";
6976 /* each step cannot decode more than 1 character, but a character can be
6977 represented as a surrogate pair */
6978 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02006979 int insize;
6980 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02006981 PyObject *errorHandler = NULL;
6982 PyObject *exc = NULL;
6983 PyObject *encoding_obj = NULL;
6984 char *encoding;
6985 DWORD err;
6986 int ret = -1;
6987
6988 assert(size > 0);
6989
6990 encoding = code_page_name(code_page, &encoding_obj);
6991 if (encoding == NULL)
6992 return -1;
6993
Victor Stinner7d00cc12014-03-17 23:08:06 +01006994 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02006995 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6996 UnicodeDecodeError. */
6997 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6998 if (exc != NULL) {
6999 PyCodec_StrictErrors(exc);
7000 Py_CLEAR(exc);
7001 }
7002 goto error;
7003 }
7004
7005 if (*v == NULL) {
7006 /* Create unicode object */
7007 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7008 PyErr_NoMemory();
7009 goto error;
7010 }
Victor Stinnerab595942011-12-17 04:59:06 +01007011 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007012 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007013 if (*v == NULL)
7014 goto error;
7015 startout = PyUnicode_AS_UNICODE(*v);
7016 }
7017 else {
7018 /* Extend unicode object */
7019 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7020 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7021 PyErr_NoMemory();
7022 goto error;
7023 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007024 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007025 goto error;
7026 startout = PyUnicode_AS_UNICODE(*v) + n;
7027 }
7028
7029 /* Decode the byte string character per character */
7030 out = startout;
7031 while (in < endin)
7032 {
7033 /* Decode a character */
7034 insize = 1;
7035 do
7036 {
7037 outsize = MultiByteToWideChar(code_page, flags,
7038 in, insize,
7039 buffer, Py_ARRAY_LENGTH(buffer));
7040 if (outsize > 0)
7041 break;
7042 err = GetLastError();
7043 if (err != ERROR_NO_UNICODE_TRANSLATION
7044 && err != ERROR_INSUFFICIENT_BUFFER)
7045 {
7046 PyErr_SetFromWindowsErr(0);
7047 goto error;
7048 }
7049 insize++;
7050 }
7051 /* 4=maximum length of a UTF-8 sequence */
7052 while (insize <= 4 && (in + insize) <= endin);
7053
7054 if (outsize <= 0) {
7055 Py_ssize_t startinpos, endinpos, outpos;
7056
Victor Stinner7d00cc12014-03-17 23:08:06 +01007057 /* last character in partial decode? */
7058 if (in + insize >= endin && !final)
7059 break;
7060
Victor Stinner3a50e702011-10-18 21:21:00 +02007061 startinpos = in - startin;
7062 endinpos = startinpos + 1;
7063 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007064 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007065 errors, &errorHandler,
7066 encoding, reason,
7067 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007068 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007069 {
7070 goto error;
7071 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007072 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007073 }
7074 else {
7075 in += insize;
7076 memcpy(out, buffer, outsize * sizeof(wchar_t));
7077 out += outsize;
7078 }
7079 }
7080
7081 /* write a NUL character at the end */
7082 *out = 0;
7083
7084 /* Extend unicode object */
7085 outsize = out - startout;
7086 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007087 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007088 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007089 /* (in - startin) <= size and size is an int */
7090 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007091
7092error:
7093 Py_XDECREF(encoding_obj);
7094 Py_XDECREF(errorHandler);
7095 Py_XDECREF(exc);
7096 return ret;
7097}
7098
Victor Stinner3a50e702011-10-18 21:21:00 +02007099static PyObject *
7100decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007101 const char *s, Py_ssize_t size,
7102 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007103{
Victor Stinner76a31a62011-11-04 00:05:13 +01007104 PyObject *v = NULL;
7105 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007106
Victor Stinner3a50e702011-10-18 21:21:00 +02007107 if (code_page < 0) {
7108 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7109 return NULL;
7110 }
7111
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007112 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007113 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007114
Victor Stinner76a31a62011-11-04 00:05:13 +01007115 do
7116 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007117#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007118 if (size > INT_MAX) {
7119 chunk_size = INT_MAX;
7120 final = 0;
7121 done = 0;
7122 }
7123 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007124#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007125 {
7126 chunk_size = (int)size;
7127 final = (consumed == NULL);
7128 done = 1;
7129 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007130
Victor Stinner76a31a62011-11-04 00:05:13 +01007131 if (chunk_size == 0 && done) {
7132 if (v != NULL)
7133 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007134 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007135 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007136
Victor Stinner76a31a62011-11-04 00:05:13 +01007137 converted = decode_code_page_strict(code_page, &v,
7138 s, chunk_size);
7139 if (converted == -2)
7140 converted = decode_code_page_errors(code_page, &v,
7141 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007142 errors, final);
7143 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007144
7145 if (converted < 0) {
7146 Py_XDECREF(v);
7147 return NULL;
7148 }
7149
7150 if (consumed)
7151 *consumed += converted;
7152
7153 s += converted;
7154 size -= converted;
7155 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007156
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007157 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007158}
7159
Alexander Belopolsky40018472011-02-26 01:02:56 +00007160PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007161PyUnicode_DecodeCodePageStateful(int code_page,
7162 const char *s,
7163 Py_ssize_t size,
7164 const char *errors,
7165 Py_ssize_t *consumed)
7166{
7167 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7168}
7169
7170PyObject *
7171PyUnicode_DecodeMBCSStateful(const char *s,
7172 Py_ssize_t size,
7173 const char *errors,
7174 Py_ssize_t *consumed)
7175{
7176 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7177}
7178
7179PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007180PyUnicode_DecodeMBCS(const char *s,
7181 Py_ssize_t size,
7182 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007183{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007184 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7185}
7186
Victor Stinner3a50e702011-10-18 21:21:00 +02007187static DWORD
7188encode_code_page_flags(UINT code_page, const char *errors)
7189{
7190 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007191 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007192 }
7193 else if (code_page == CP_UTF7) {
7194 /* CP_UTF7 only supports flags=0 */
7195 return 0;
7196 }
7197 else {
7198 if (errors != NULL && strcmp(errors, "replace") == 0)
7199 return 0;
7200 else
7201 return WC_NO_BEST_FIT_CHARS;
7202 }
7203}
7204
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007205/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007206 * Encode a Unicode string to a Windows code page into a byte string in strict
7207 * mode.
7208 *
7209 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007210 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007211 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007212static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007213encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007214 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007215 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007216{
Victor Stinner554f3f02010-06-16 23:33:54 +00007217 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007218 BOOL *pusedDefaultChar = &usedDefaultChar;
7219 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007220 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007221 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007222 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007223 const DWORD flags = encode_code_page_flags(code_page, NULL);
7224 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007225 /* Create a substring so that we can get the UTF-16 representation
7226 of just the slice under consideration. */
7227 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007228
Martin v. Löwis3d325192011-11-04 18:23:06 +01007229 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007230
Victor Stinner3a50e702011-10-18 21:21:00 +02007231 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007232 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007233 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007234 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007235
Victor Stinner2fc507f2011-11-04 20:06:39 +01007236 substring = PyUnicode_Substring(unicode, offset, offset+len);
7237 if (substring == NULL)
7238 return -1;
7239 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7240 if (p == NULL) {
7241 Py_DECREF(substring);
7242 return -1;
7243 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007244 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007245
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007246 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007247 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007248 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007249 NULL, 0,
7250 NULL, pusedDefaultChar);
7251 if (outsize <= 0)
7252 goto error;
7253 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007254 if (pusedDefaultChar && *pusedDefaultChar) {
7255 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007256 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007257 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007258
Victor Stinner3a50e702011-10-18 21:21:00 +02007259 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007260 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007261 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007262 if (*outbytes == NULL) {
7263 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007264 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007265 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007266 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007267 }
7268 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007269 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007270 const Py_ssize_t n = PyBytes_Size(*outbytes);
7271 if (outsize > PY_SSIZE_T_MAX - n) {
7272 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007273 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007274 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007275 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007276 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7277 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007278 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007279 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007280 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007281 }
7282
7283 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007284 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007285 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007286 out, outsize,
7287 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007288 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007289 if (outsize <= 0)
7290 goto error;
7291 if (pusedDefaultChar && *pusedDefaultChar)
7292 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007293 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007294
Victor Stinner3a50e702011-10-18 21:21:00 +02007295error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007296 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007297 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7298 return -2;
7299 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007300 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007301}
7302
Victor Stinner3a50e702011-10-18 21:21:00 +02007303/*
7304 * Encode a Unicode string to a Windows code page into a byte string using a
7305 * error handler.
7306 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007307 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007308 * -1 on other error.
7309 */
7310static int
7311encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007312 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007313 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007314{
Victor Stinner3a50e702011-10-18 21:21:00 +02007315 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007316 Py_ssize_t pos = unicode_offset;
7317 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007318 /* Ideally, we should get reason from FormatMessage. This is the Windows
7319 2000 English version of the message. */
7320 const char *reason = "invalid character";
7321 /* 4=maximum length of a UTF-8 sequence */
7322 char buffer[4];
7323 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7324 Py_ssize_t outsize;
7325 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007326 PyObject *errorHandler = NULL;
7327 PyObject *exc = NULL;
7328 PyObject *encoding_obj = NULL;
7329 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007330 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007331 PyObject *rep;
7332 int ret = -1;
7333
7334 assert(insize > 0);
7335
7336 encoding = code_page_name(code_page, &encoding_obj);
7337 if (encoding == NULL)
7338 return -1;
7339
7340 if (errors == NULL || strcmp(errors, "strict") == 0) {
7341 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7342 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007343 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007344 if (exc != NULL) {
7345 PyCodec_StrictErrors(exc);
7346 Py_DECREF(exc);
7347 }
7348 Py_XDECREF(encoding_obj);
7349 return -1;
7350 }
7351
7352 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7353 pusedDefaultChar = &usedDefaultChar;
7354 else
7355 pusedDefaultChar = NULL;
7356
7357 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7358 PyErr_NoMemory();
7359 goto error;
7360 }
7361 outsize = insize * Py_ARRAY_LENGTH(buffer);
7362
7363 if (*outbytes == NULL) {
7364 /* Create string object */
7365 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7366 if (*outbytes == NULL)
7367 goto error;
7368 out = PyBytes_AS_STRING(*outbytes);
7369 }
7370 else {
7371 /* Extend string object */
7372 Py_ssize_t n = PyBytes_Size(*outbytes);
7373 if (n > PY_SSIZE_T_MAX - outsize) {
7374 PyErr_NoMemory();
7375 goto error;
7376 }
7377 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7378 goto error;
7379 out = PyBytes_AS_STRING(*outbytes) + n;
7380 }
7381
7382 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007383 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007384 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007385 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7386 wchar_t chars[2];
7387 int charsize;
7388 if (ch < 0x10000) {
7389 chars[0] = (wchar_t)ch;
7390 charsize = 1;
7391 }
7392 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007393 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7394 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007395 charsize = 2;
7396 }
7397
Victor Stinner3a50e702011-10-18 21:21:00 +02007398 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007399 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007400 buffer, Py_ARRAY_LENGTH(buffer),
7401 NULL, pusedDefaultChar);
7402 if (outsize > 0) {
7403 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7404 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007405 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007406 memcpy(out, buffer, outsize);
7407 out += outsize;
7408 continue;
7409 }
7410 }
7411 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7412 PyErr_SetFromWindowsErr(0);
7413 goto error;
7414 }
7415
Victor Stinner3a50e702011-10-18 21:21:00 +02007416 rep = unicode_encode_call_errorhandler(
7417 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007418 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007419 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007420 if (rep == NULL)
7421 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007422 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007423
7424 if (PyBytes_Check(rep)) {
7425 outsize = PyBytes_GET_SIZE(rep);
7426 if (outsize != 1) {
7427 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7428 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7429 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7430 Py_DECREF(rep);
7431 goto error;
7432 }
7433 out = PyBytes_AS_STRING(*outbytes) + offset;
7434 }
7435 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7436 out += outsize;
7437 }
7438 else {
7439 Py_ssize_t i;
7440 enum PyUnicode_Kind kind;
7441 void *data;
7442
Benjamin Petersonbac79492012-01-14 13:34:47 -05007443 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007444 Py_DECREF(rep);
7445 goto error;
7446 }
7447
7448 outsize = PyUnicode_GET_LENGTH(rep);
7449 if (outsize != 1) {
7450 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7451 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7452 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7453 Py_DECREF(rep);
7454 goto error;
7455 }
7456 out = PyBytes_AS_STRING(*outbytes) + offset;
7457 }
7458 kind = PyUnicode_KIND(rep);
7459 data = PyUnicode_DATA(rep);
7460 for (i=0; i < outsize; i++) {
7461 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7462 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007463 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007464 encoding, unicode,
7465 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007466 "unable to encode error handler result to ASCII");
7467 Py_DECREF(rep);
7468 goto error;
7469 }
7470 *out = (unsigned char)ch;
7471 out++;
7472 }
7473 }
7474 Py_DECREF(rep);
7475 }
7476 /* write a NUL byte */
7477 *out = 0;
7478 outsize = out - PyBytes_AS_STRING(*outbytes);
7479 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7480 if (_PyBytes_Resize(outbytes, outsize) < 0)
7481 goto error;
7482 ret = 0;
7483
7484error:
7485 Py_XDECREF(encoding_obj);
7486 Py_XDECREF(errorHandler);
7487 Py_XDECREF(exc);
7488 return ret;
7489}
7490
Victor Stinner3a50e702011-10-18 21:21:00 +02007491static PyObject *
7492encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007493 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007494 const char *errors)
7495{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007496 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007497 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007498 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007499 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007500
Victor Stinner29dacf22015-01-26 16:41:32 +01007501 if (!PyUnicode_Check(unicode)) {
7502 PyErr_BadArgument();
7503 return NULL;
7504 }
7505
Benjamin Petersonbac79492012-01-14 13:34:47 -05007506 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007507 return NULL;
7508 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007509
Victor Stinner3a50e702011-10-18 21:21:00 +02007510 if (code_page < 0) {
7511 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7512 return NULL;
7513 }
7514
Martin v. Löwis3d325192011-11-04 18:23:06 +01007515 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007516 return PyBytes_FromStringAndSize(NULL, 0);
7517
Victor Stinner7581cef2011-11-03 22:32:33 +01007518 offset = 0;
7519 do
7520 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007521#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007522 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007523 chunks. */
7524 if (len > INT_MAX/2) {
7525 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007526 done = 0;
7527 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007528 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007529#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007530 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007531 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007532 done = 1;
7533 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007534
Victor Stinner76a31a62011-11-04 00:05:13 +01007535 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007536 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007537 errors);
7538 if (ret == -2)
7539 ret = encode_code_page_errors(code_page, &outbytes,
7540 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007541 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007542 if (ret < 0) {
7543 Py_XDECREF(outbytes);
7544 return NULL;
7545 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007546
Victor Stinner7581cef2011-11-03 22:32:33 +01007547 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007548 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007549 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007550
Victor Stinner3a50e702011-10-18 21:21:00 +02007551 return outbytes;
7552}
7553
7554PyObject *
7555PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7556 Py_ssize_t size,
7557 const char *errors)
7558{
Victor Stinner7581cef2011-11-03 22:32:33 +01007559 PyObject *unicode, *res;
7560 unicode = PyUnicode_FromUnicode(p, size);
7561 if (unicode == NULL)
7562 return NULL;
7563 res = encode_code_page(CP_ACP, unicode, errors);
7564 Py_DECREF(unicode);
7565 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007566}
7567
7568PyObject *
7569PyUnicode_EncodeCodePage(int code_page,
7570 PyObject *unicode,
7571 const char *errors)
7572{
Victor Stinner7581cef2011-11-03 22:32:33 +01007573 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007574}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007575
Alexander Belopolsky40018472011-02-26 01:02:56 +00007576PyObject *
7577PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007578{
Victor Stinner7581cef2011-11-03 22:32:33 +01007579 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007580}
7581
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007582#undef NEED_RETRY
7583
Victor Stinner99b95382011-07-04 14:23:54 +02007584#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007585
Guido van Rossumd57fd912000-03-10 22:53:23 +00007586/* --- Character Mapping Codec -------------------------------------------- */
7587
Victor Stinnerfb161b12013-04-18 01:44:27 +02007588static int
7589charmap_decode_string(const char *s,
7590 Py_ssize_t size,
7591 PyObject *mapping,
7592 const char *errors,
7593 _PyUnicodeWriter *writer)
7594{
7595 const char *starts = s;
7596 const char *e;
7597 Py_ssize_t startinpos, endinpos;
7598 PyObject *errorHandler = NULL, *exc = NULL;
7599 Py_ssize_t maplen;
7600 enum PyUnicode_Kind mapkind;
7601 void *mapdata;
7602 Py_UCS4 x;
7603 unsigned char ch;
7604
7605 if (PyUnicode_READY(mapping) == -1)
7606 return -1;
7607
7608 maplen = PyUnicode_GET_LENGTH(mapping);
7609 mapdata = PyUnicode_DATA(mapping);
7610 mapkind = PyUnicode_KIND(mapping);
7611
7612 e = s + size;
7613
7614 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7615 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7616 * is disabled in encoding aliases, latin1 is preferred because
7617 * its implementation is faster. */
7618 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7619 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7620 Py_UCS4 maxchar = writer->maxchar;
7621
7622 assert (writer->kind == PyUnicode_1BYTE_KIND);
7623 while (s < e) {
7624 ch = *s;
7625 x = mapdata_ucs1[ch];
7626 if (x > maxchar) {
7627 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7628 goto onError;
7629 maxchar = writer->maxchar;
7630 outdata = (Py_UCS1 *)writer->data;
7631 }
7632 outdata[writer->pos] = x;
7633 writer->pos++;
7634 ++s;
7635 }
7636 return 0;
7637 }
7638
7639 while (s < e) {
7640 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7641 enum PyUnicode_Kind outkind = writer->kind;
7642 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7643 if (outkind == PyUnicode_1BYTE_KIND) {
7644 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7645 Py_UCS4 maxchar = writer->maxchar;
7646 while (s < e) {
7647 ch = *s;
7648 x = mapdata_ucs2[ch];
7649 if (x > maxchar)
7650 goto Error;
7651 outdata[writer->pos] = x;
7652 writer->pos++;
7653 ++s;
7654 }
7655 break;
7656 }
7657 else if (outkind == PyUnicode_2BYTE_KIND) {
7658 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7659 while (s < e) {
7660 ch = *s;
7661 x = mapdata_ucs2[ch];
7662 if (x == 0xFFFE)
7663 goto Error;
7664 outdata[writer->pos] = x;
7665 writer->pos++;
7666 ++s;
7667 }
7668 break;
7669 }
7670 }
7671 ch = *s;
7672
7673 if (ch < maplen)
7674 x = PyUnicode_READ(mapkind, mapdata, ch);
7675 else
7676 x = 0xfffe; /* invalid value */
7677Error:
7678 if (x == 0xfffe)
7679 {
7680 /* undefined mapping */
7681 startinpos = s-starts;
7682 endinpos = startinpos+1;
7683 if (unicode_decode_call_errorhandler_writer(
7684 errors, &errorHandler,
7685 "charmap", "character maps to <undefined>",
7686 &starts, &e, &startinpos, &endinpos, &exc, &s,
7687 writer)) {
7688 goto onError;
7689 }
7690 continue;
7691 }
7692
7693 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7694 goto onError;
7695 ++s;
7696 }
7697 Py_XDECREF(errorHandler);
7698 Py_XDECREF(exc);
7699 return 0;
7700
7701onError:
7702 Py_XDECREF(errorHandler);
7703 Py_XDECREF(exc);
7704 return -1;
7705}
7706
7707static int
7708charmap_decode_mapping(const char *s,
7709 Py_ssize_t size,
7710 PyObject *mapping,
7711 const char *errors,
7712 _PyUnicodeWriter *writer)
7713{
7714 const char *starts = s;
7715 const char *e;
7716 Py_ssize_t startinpos, endinpos;
7717 PyObject *errorHandler = NULL, *exc = NULL;
7718 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007719 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007720
7721 e = s + size;
7722
7723 while (s < e) {
7724 ch = *s;
7725
7726 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7727 key = PyLong_FromLong((long)ch);
7728 if (key == NULL)
7729 goto onError;
7730
7731 item = PyObject_GetItem(mapping, key);
7732 Py_DECREF(key);
7733 if (item == NULL) {
7734 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7735 /* No mapping found means: mapping is undefined. */
7736 PyErr_Clear();
7737 goto Undefined;
7738 } else
7739 goto onError;
7740 }
7741
7742 /* Apply mapping */
7743 if (item == Py_None)
7744 goto Undefined;
7745 if (PyLong_Check(item)) {
7746 long value = PyLong_AS_LONG(item);
7747 if (value == 0xFFFE)
7748 goto Undefined;
7749 if (value < 0 || value > MAX_UNICODE) {
7750 PyErr_Format(PyExc_TypeError,
7751 "character mapping must be in range(0x%lx)",
7752 (unsigned long)MAX_UNICODE + 1);
7753 goto onError;
7754 }
7755
7756 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7757 goto onError;
7758 }
7759 else if (PyUnicode_Check(item)) {
7760 if (PyUnicode_READY(item) == -1)
7761 goto onError;
7762 if (PyUnicode_GET_LENGTH(item) == 1) {
7763 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7764 if (value == 0xFFFE)
7765 goto Undefined;
7766 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7767 goto onError;
7768 }
7769 else {
7770 writer->overallocate = 1;
7771 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7772 goto onError;
7773 }
7774 }
7775 else {
7776 /* wrong return value */
7777 PyErr_SetString(PyExc_TypeError,
7778 "character mapping must return integer, None or str");
7779 goto onError;
7780 }
7781 Py_CLEAR(item);
7782 ++s;
7783 continue;
7784
7785Undefined:
7786 /* undefined mapping */
7787 Py_CLEAR(item);
7788 startinpos = s-starts;
7789 endinpos = startinpos+1;
7790 if (unicode_decode_call_errorhandler_writer(
7791 errors, &errorHandler,
7792 "charmap", "character maps to <undefined>",
7793 &starts, &e, &startinpos, &endinpos, &exc, &s,
7794 writer)) {
7795 goto onError;
7796 }
7797 }
7798 Py_XDECREF(errorHandler);
7799 Py_XDECREF(exc);
7800 return 0;
7801
7802onError:
7803 Py_XDECREF(item);
7804 Py_XDECREF(errorHandler);
7805 Py_XDECREF(exc);
7806 return -1;
7807}
7808
Alexander Belopolsky40018472011-02-26 01:02:56 +00007809PyObject *
7810PyUnicode_DecodeCharmap(const char *s,
7811 Py_ssize_t size,
7812 PyObject *mapping,
7813 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007814{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007815 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007816
Guido van Rossumd57fd912000-03-10 22:53:23 +00007817 /* Default to Latin-1 */
7818 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007819 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007820
Guido van Rossumd57fd912000-03-10 22:53:23 +00007821 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007822 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007823 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007824 writer.min_length = size;
7825 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007826 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007827
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007828 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007829 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
7830 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007831 }
7832 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007833 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
7834 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007835 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007836 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007837
Benjamin Peterson29060642009-01-31 22:14:21 +00007838 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007839 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007840 return NULL;
7841}
7842
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007843/* Charmap encoding: the lookup table */
7844
Alexander Belopolsky40018472011-02-26 01:02:56 +00007845struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007846 PyObject_HEAD
7847 unsigned char level1[32];
7848 int count2, count3;
7849 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007850};
7851
7852static PyObject*
7853encoding_map_size(PyObject *obj, PyObject* args)
7854{
7855 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007856 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007857 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007858}
7859
7860static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007861 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007862 PyDoc_STR("Return the size (in bytes) of this object") },
7863 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007864};
7865
7866static void
7867encoding_map_dealloc(PyObject* o)
7868{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007869 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007870}
7871
7872static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007873 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007874 "EncodingMap", /*tp_name*/
7875 sizeof(struct encoding_map), /*tp_basicsize*/
7876 0, /*tp_itemsize*/
7877 /* methods */
7878 encoding_map_dealloc, /*tp_dealloc*/
7879 0, /*tp_print*/
7880 0, /*tp_getattr*/
7881 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007882 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007883 0, /*tp_repr*/
7884 0, /*tp_as_number*/
7885 0, /*tp_as_sequence*/
7886 0, /*tp_as_mapping*/
7887 0, /*tp_hash*/
7888 0, /*tp_call*/
7889 0, /*tp_str*/
7890 0, /*tp_getattro*/
7891 0, /*tp_setattro*/
7892 0, /*tp_as_buffer*/
7893 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7894 0, /*tp_doc*/
7895 0, /*tp_traverse*/
7896 0, /*tp_clear*/
7897 0, /*tp_richcompare*/
7898 0, /*tp_weaklistoffset*/
7899 0, /*tp_iter*/
7900 0, /*tp_iternext*/
7901 encoding_map_methods, /*tp_methods*/
7902 0, /*tp_members*/
7903 0, /*tp_getset*/
7904 0, /*tp_base*/
7905 0, /*tp_dict*/
7906 0, /*tp_descr_get*/
7907 0, /*tp_descr_set*/
7908 0, /*tp_dictoffset*/
7909 0, /*tp_init*/
7910 0, /*tp_alloc*/
7911 0, /*tp_new*/
7912 0, /*tp_free*/
7913 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007914};
7915
7916PyObject*
7917PyUnicode_BuildEncodingMap(PyObject* string)
7918{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007919 PyObject *result;
7920 struct encoding_map *mresult;
7921 int i;
7922 int need_dict = 0;
7923 unsigned char level1[32];
7924 unsigned char level2[512];
7925 unsigned char *mlevel1, *mlevel2, *mlevel3;
7926 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007927 int kind;
7928 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007929 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007930 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007931
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007932 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007933 PyErr_BadArgument();
7934 return NULL;
7935 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007936 kind = PyUnicode_KIND(string);
7937 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007938 length = PyUnicode_GET_LENGTH(string);
7939 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007940 memset(level1, 0xFF, sizeof level1);
7941 memset(level2, 0xFF, sizeof level2);
7942
7943 /* If there isn't a one-to-one mapping of NULL to \0,
7944 or if there are non-BMP characters, we need to use
7945 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007946 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007947 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007948 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007949 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007950 ch = PyUnicode_READ(kind, data, i);
7951 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007952 need_dict = 1;
7953 break;
7954 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007955 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007956 /* unmapped character */
7957 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007958 l1 = ch >> 11;
7959 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007960 if (level1[l1] == 0xFF)
7961 level1[l1] = count2++;
7962 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007963 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007964 }
7965
7966 if (count2 >= 0xFF || count3 >= 0xFF)
7967 need_dict = 1;
7968
7969 if (need_dict) {
7970 PyObject *result = PyDict_New();
7971 PyObject *key, *value;
7972 if (!result)
7973 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007974 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007975 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007976 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007977 if (!key || !value)
7978 goto failed1;
7979 if (PyDict_SetItem(result, key, value) == -1)
7980 goto failed1;
7981 Py_DECREF(key);
7982 Py_DECREF(value);
7983 }
7984 return result;
7985 failed1:
7986 Py_XDECREF(key);
7987 Py_XDECREF(value);
7988 Py_DECREF(result);
7989 return NULL;
7990 }
7991
7992 /* Create a three-level trie */
7993 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7994 16*count2 + 128*count3 - 1);
7995 if (!result)
7996 return PyErr_NoMemory();
7997 PyObject_Init(result, &EncodingMapType);
7998 mresult = (struct encoding_map*)result;
7999 mresult->count2 = count2;
8000 mresult->count3 = count3;
8001 mlevel1 = mresult->level1;
8002 mlevel2 = mresult->level23;
8003 mlevel3 = mresult->level23 + 16*count2;
8004 memcpy(mlevel1, level1, 32);
8005 memset(mlevel2, 0xFF, 16*count2);
8006 memset(mlevel3, 0, 128*count3);
8007 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008008 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008009 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008010 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8011 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008012 /* unmapped character */
8013 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008014 o1 = ch>>11;
8015 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008016 i2 = 16*mlevel1[o1] + o2;
8017 if (mlevel2[i2] == 0xFF)
8018 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008019 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008020 i3 = 128*mlevel2[i2] + o3;
8021 mlevel3[i3] = i;
8022 }
8023 return result;
8024}
8025
8026static int
Victor Stinner22168992011-11-20 17:09:18 +01008027encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008028{
8029 struct encoding_map *map = (struct encoding_map*)mapping;
8030 int l1 = c>>11;
8031 int l2 = (c>>7) & 0xF;
8032 int l3 = c & 0x7F;
8033 int i;
8034
Victor Stinner22168992011-11-20 17:09:18 +01008035 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008036 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008037 if (c == 0)
8038 return 0;
8039 /* level 1*/
8040 i = map->level1[l1];
8041 if (i == 0xFF) {
8042 return -1;
8043 }
8044 /* level 2*/
8045 i = map->level23[16*i+l2];
8046 if (i == 0xFF) {
8047 return -1;
8048 }
8049 /* level 3 */
8050 i = map->level23[16*map->count2 + 128*i + l3];
8051 if (i == 0) {
8052 return -1;
8053 }
8054 return i;
8055}
8056
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008057/* Lookup the character ch in the mapping. If the character
8058 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008059 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008060static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008061charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008062{
Christian Heimes217cfd12007-12-02 14:31:20 +00008063 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008064 PyObject *x;
8065
8066 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008067 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008068 x = PyObject_GetItem(mapping, w);
8069 Py_DECREF(w);
8070 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008071 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8072 /* No mapping found means: mapping is undefined. */
8073 PyErr_Clear();
8074 x = Py_None;
8075 Py_INCREF(x);
8076 return x;
8077 } else
8078 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008079 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008080 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008081 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008082 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008083 long value = PyLong_AS_LONG(x);
8084 if (value < 0 || value > 255) {
8085 PyErr_SetString(PyExc_TypeError,
8086 "character mapping must be in range(256)");
8087 Py_DECREF(x);
8088 return NULL;
8089 }
8090 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008091 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008092 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008093 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008094 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008095 /* wrong return value */
8096 PyErr_Format(PyExc_TypeError,
8097 "character mapping must return integer, bytes or None, not %.400s",
8098 x->ob_type->tp_name);
8099 Py_DECREF(x);
8100 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008101 }
8102}
8103
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008104static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008105charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008106{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008107 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8108 /* exponentially overallocate to minimize reallocations */
8109 if (requiredsize < 2*outsize)
8110 requiredsize = 2*outsize;
8111 if (_PyBytes_Resize(outobj, requiredsize))
8112 return -1;
8113 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008114}
8115
Benjamin Peterson14339b62009-01-31 16:36:08 +00008116typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008117 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008118} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008119/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008120 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008121 space is available. Return a new reference to the object that
8122 was put in the output buffer, or Py_None, if the mapping was undefined
8123 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008124 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008125static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008126charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008127 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008128{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008129 PyObject *rep;
8130 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008131 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008132
Christian Heimes90aa7642007-12-19 02:45:37 +00008133 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008134 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008135 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008136 if (res == -1)
8137 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008138 if (outsize<requiredsize)
8139 if (charmapencode_resize(outobj, outpos, requiredsize))
8140 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008141 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008142 outstart[(*outpos)++] = (char)res;
8143 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008144 }
8145
8146 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008147 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008148 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008149 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008150 Py_DECREF(rep);
8151 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008152 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008153 if (PyLong_Check(rep)) {
8154 Py_ssize_t requiredsize = *outpos+1;
8155 if (outsize<requiredsize)
8156 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8157 Py_DECREF(rep);
8158 return enc_EXCEPTION;
8159 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008160 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008161 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008162 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008163 else {
8164 const char *repchars = PyBytes_AS_STRING(rep);
8165 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8166 Py_ssize_t requiredsize = *outpos+repsize;
8167 if (outsize<requiredsize)
8168 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8169 Py_DECREF(rep);
8170 return enc_EXCEPTION;
8171 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008172 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008173 memcpy(outstart + *outpos, repchars, repsize);
8174 *outpos += repsize;
8175 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008176 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008177 Py_DECREF(rep);
8178 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008179}
8180
8181/* handle an error in PyUnicode_EncodeCharmap
8182 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008183static int
8184charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008185 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008186 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008187 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008188 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008189{
8190 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008191 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008192 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008193 enum PyUnicode_Kind kind;
8194 void *data;
8195 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008196 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008197 Py_ssize_t collstartpos = *inpos;
8198 Py_ssize_t collendpos = *inpos+1;
8199 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008200 char *encoding = "charmap";
8201 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008202 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008203 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008204 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008205
Benjamin Petersonbac79492012-01-14 13:34:47 -05008206 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008207 return -1;
8208 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008209 /* find all unencodable characters */
8210 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008211 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008212 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008213 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008214 val = encoding_map_lookup(ch, mapping);
8215 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008216 break;
8217 ++collendpos;
8218 continue;
8219 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008220
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008221 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8222 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008223 if (rep==NULL)
8224 return -1;
8225 else if (rep!=Py_None) {
8226 Py_DECREF(rep);
8227 break;
8228 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008229 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008230 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008231 }
8232 /* cache callback name lookup
8233 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008234 if (*error_handler == _Py_ERROR_UNKNOWN)
8235 *error_handler = get_error_handler(errors);
8236
8237 switch (*error_handler) {
8238 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008239 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008240 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008241
8242 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008243 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008244 x = charmapencode_output('?', mapping, res, respos);
8245 if (x==enc_EXCEPTION) {
8246 return -1;
8247 }
8248 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008249 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008250 return -1;
8251 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008252 }
8253 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008254 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008255 *inpos = collendpos;
8256 break;
Victor Stinner50149202015-09-22 00:26:54 +02008257
8258 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008259 /* generate replacement (temporarily (mis)uses p) */
8260 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008261 char buffer[2+29+1+1];
8262 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008263 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008264 for (cp = buffer; *cp; ++cp) {
8265 x = charmapencode_output(*cp, mapping, res, respos);
8266 if (x==enc_EXCEPTION)
8267 return -1;
8268 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008269 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008270 return -1;
8271 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008272 }
8273 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008274 *inpos = collendpos;
8275 break;
Victor Stinner50149202015-09-22 00:26:54 +02008276
Benjamin Peterson14339b62009-01-31 16:36:08 +00008277 default:
Victor Stinner50149202015-09-22 00:26:54 +02008278 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008279 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008280 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008281 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008282 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008283 if (PyBytes_Check(repunicode)) {
8284 /* Directly copy bytes result to output. */
8285 Py_ssize_t outsize = PyBytes_Size(*res);
8286 Py_ssize_t requiredsize;
8287 repsize = PyBytes_Size(repunicode);
8288 requiredsize = *respos + repsize;
8289 if (requiredsize > outsize)
8290 /* Make room for all additional bytes. */
8291 if (charmapencode_resize(res, respos, requiredsize)) {
8292 Py_DECREF(repunicode);
8293 return -1;
8294 }
8295 memcpy(PyBytes_AsString(*res) + *respos,
8296 PyBytes_AsString(repunicode), repsize);
8297 *respos += repsize;
8298 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008299 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008300 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008301 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008302 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008303 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008304 Py_DECREF(repunicode);
8305 return -1;
8306 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008307 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008308 data = PyUnicode_DATA(repunicode);
8309 kind = PyUnicode_KIND(repunicode);
8310 for (index = 0; index < repsize; index++) {
8311 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8312 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008313 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008314 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008315 return -1;
8316 }
8317 else if (x==enc_FAILED) {
8318 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008319 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008320 return -1;
8321 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008322 }
8323 *inpos = newpos;
8324 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008325 }
8326 return 0;
8327}
8328
Alexander Belopolsky40018472011-02-26 01:02:56 +00008329PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008330_PyUnicode_EncodeCharmap(PyObject *unicode,
8331 PyObject *mapping,
8332 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008333{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008334 /* output object */
8335 PyObject *res = NULL;
8336 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008337 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008338 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008339 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008340 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008341 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008342 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008343 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008344 void *data;
8345 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008346
Benjamin Petersonbac79492012-01-14 13:34:47 -05008347 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008348 return NULL;
8349 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008350 data = PyUnicode_DATA(unicode);
8351 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008352
Guido van Rossumd57fd912000-03-10 22:53:23 +00008353 /* Default to Latin-1 */
8354 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008355 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008356
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008357 /* allocate enough for a simple encoding without
8358 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008359 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008360 if (res == NULL)
8361 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008362 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008363 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008364
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008365 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008366 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008367 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008368 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008369 if (x==enc_EXCEPTION) /* error */
8370 goto onError;
8371 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008372 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008373 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008374 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008375 &res, &respos)) {
8376 goto onError;
8377 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008378 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008379 else
8380 /* done with this character => adjust input position */
8381 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008382 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008383
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008384 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008385 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008386 if (_PyBytes_Resize(&res, respos) < 0)
8387 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008388
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008389 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008390 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008391 return res;
8392
Benjamin Peterson29060642009-01-31 22:14:21 +00008393 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008394 Py_XDECREF(res);
8395 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008396 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008397 return NULL;
8398}
8399
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008400/* Deprecated */
8401PyObject *
8402PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8403 Py_ssize_t size,
8404 PyObject *mapping,
8405 const char *errors)
8406{
8407 PyObject *result;
8408 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8409 if (unicode == NULL)
8410 return NULL;
8411 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8412 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008413 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008414}
8415
Alexander Belopolsky40018472011-02-26 01:02:56 +00008416PyObject *
8417PyUnicode_AsCharmapString(PyObject *unicode,
8418 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008419{
8420 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008421 PyErr_BadArgument();
8422 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008423 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008424 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008425}
8426
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008427/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008428static void
8429make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008430 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008431 Py_ssize_t startpos, Py_ssize_t endpos,
8432 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008433{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008434 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008435 *exceptionObject = _PyUnicodeTranslateError_Create(
8436 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008437 }
8438 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008439 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8440 goto onError;
8441 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8442 goto onError;
8443 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8444 goto onError;
8445 return;
8446 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008447 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008448 }
8449}
8450
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008451/* error handling callback helper:
8452 build arguments, call the callback and check the arguments,
8453 put the result into newpos and return the replacement string, which
8454 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008455static PyObject *
8456unicode_translate_call_errorhandler(const char *errors,
8457 PyObject **errorHandler,
8458 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008459 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008460 Py_ssize_t startpos, Py_ssize_t endpos,
8461 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008462{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008463 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008464
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008465 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008466 PyObject *restuple;
8467 PyObject *resunicode;
8468
8469 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008470 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008471 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008472 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008473 }
8474
8475 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008476 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008477 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008478 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008479
8480 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008481 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008482 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008483 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008484 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008485 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008486 Py_DECREF(restuple);
8487 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008488 }
8489 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008490 &resunicode, &i_newpos)) {
8491 Py_DECREF(restuple);
8492 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008493 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008494 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008495 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008496 else
8497 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008498 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008499 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008500 Py_DECREF(restuple);
8501 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008502 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008503 Py_INCREF(resunicode);
8504 Py_DECREF(restuple);
8505 return resunicode;
8506}
8507
8508/* Lookup the character ch in the mapping and put the result in result,
8509 which must be decrefed by the caller.
8510 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008511static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008512charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008513{
Christian Heimes217cfd12007-12-02 14:31:20 +00008514 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008515 PyObject *x;
8516
8517 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008518 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008519 x = PyObject_GetItem(mapping, w);
8520 Py_DECREF(w);
8521 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008522 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8523 /* No mapping found means: use 1:1 mapping. */
8524 PyErr_Clear();
8525 *result = NULL;
8526 return 0;
8527 } else
8528 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008529 }
8530 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008531 *result = x;
8532 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008533 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008534 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008535 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008536 if (value < 0 || value > MAX_UNICODE) {
8537 PyErr_Format(PyExc_ValueError,
8538 "character mapping must be in range(0x%x)",
8539 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008540 Py_DECREF(x);
8541 return -1;
8542 }
8543 *result = x;
8544 return 0;
8545 }
8546 else if (PyUnicode_Check(x)) {
8547 *result = x;
8548 return 0;
8549 }
8550 else {
8551 /* wrong return value */
8552 PyErr_SetString(PyExc_TypeError,
8553 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008554 Py_DECREF(x);
8555 return -1;
8556 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008557}
Victor Stinner1194ea02014-04-04 19:37:40 +02008558
8559/* lookup the character, write the result into the writer.
8560 Return 1 if the result was written into the writer, return 0 if the mapping
8561 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008562static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008563charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8564 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008565{
Victor Stinner1194ea02014-04-04 19:37:40 +02008566 PyObject *item;
8567
8568 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008569 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008570
8571 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008572 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008573 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008574 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008575 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008576 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008577 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008578
8579 if (item == Py_None) {
8580 Py_DECREF(item);
8581 return 0;
8582 }
8583
8584 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008585 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8586 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8587 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008588 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8589 Py_DECREF(item);
8590 return -1;
8591 }
8592 Py_DECREF(item);
8593 return 1;
8594 }
8595
8596 if (!PyUnicode_Check(item)) {
8597 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008598 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008599 }
8600
8601 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8602 Py_DECREF(item);
8603 return -1;
8604 }
8605
8606 Py_DECREF(item);
8607 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008608}
8609
Victor Stinner89a76ab2014-04-05 11:44:04 +02008610static int
8611unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8612 Py_UCS1 *translate)
8613{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008614 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008615 int ret = 0;
8616
Victor Stinner89a76ab2014-04-05 11:44:04 +02008617 if (charmaptranslate_lookup(ch, mapping, &item)) {
8618 return -1;
8619 }
8620
8621 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008622 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008623 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008624 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008625 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008626 /* not found => default to 1:1 mapping */
8627 translate[ch] = ch;
8628 return 1;
8629 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008630 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008631 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008632 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8633 used it */
8634 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008635 /* invalid character or character outside ASCII:
8636 skip the fast translate */
8637 goto exit;
8638 }
8639 translate[ch] = (Py_UCS1)replace;
8640 }
8641 else if (PyUnicode_Check(item)) {
8642 Py_UCS4 replace;
8643
8644 if (PyUnicode_READY(item) == -1) {
8645 Py_DECREF(item);
8646 return -1;
8647 }
8648 if (PyUnicode_GET_LENGTH(item) != 1)
8649 goto exit;
8650
8651 replace = PyUnicode_READ_CHAR(item, 0);
8652 if (replace > 127)
8653 goto exit;
8654 translate[ch] = (Py_UCS1)replace;
8655 }
8656 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008657 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008658 goto exit;
8659 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008660 ret = 1;
8661
Benjamin Peterson1365de72014-04-07 20:15:41 -04008662 exit:
8663 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008664 return ret;
8665}
8666
8667/* Fast path for ascii => ascii translation. Return 1 if the whole string
8668 was translated into writer, return 0 if the input string was partially
8669 translated into writer, raise an exception and return -1 on error. */
8670static int
8671unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner872b2912014-04-05 14:27:07 +02008672 _PyUnicodeWriter *writer, int ignore)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008673{
Victor Stinner872b2912014-04-05 14:27:07 +02008674 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008675 Py_ssize_t len;
8676 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008677 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008678
8679 if (PyUnicode_READY(input) == -1)
8680 return -1;
8681 if (!PyUnicode_IS_ASCII(input))
8682 return 0;
8683 len = PyUnicode_GET_LENGTH(input);
8684
Victor Stinner872b2912014-04-05 14:27:07 +02008685 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008686
8687 in = PyUnicode_1BYTE_DATA(input);
8688 end = in + len;
8689
8690 assert(PyUnicode_IS_ASCII(writer->buffer));
8691 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8692 out = PyUnicode_1BYTE_DATA(writer->buffer);
8693
Victor Stinner872b2912014-04-05 14:27:07 +02008694 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008695 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008696 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008697 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008698 int translate = unicode_fast_translate_lookup(mapping, ch,
8699 ascii_table);
8700 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008701 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008702 if (translate == 0)
8703 goto exit;
8704 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008705 }
Victor Stinner872b2912014-04-05 14:27:07 +02008706 if (ch2 == 0xfe) {
8707 if (ignore)
8708 continue;
8709 goto exit;
8710 }
8711 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008712 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008713 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008714 }
Victor Stinner872b2912014-04-05 14:27:07 +02008715 res = 1;
8716
8717exit:
8718 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
8719 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008720}
8721
Victor Stinner3222da22015-10-01 22:07:32 +02008722static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008723_PyUnicode_TranslateCharmap(PyObject *input,
8724 PyObject *mapping,
8725 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008726{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008727 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008728 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008729 Py_ssize_t size, i;
8730 int kind;
8731 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008732 _PyUnicodeWriter writer;
8733 /* error handler */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008734 char *reason = "character maps to <undefined>";
8735 PyObject *errorHandler = NULL;
8736 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008737 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008738 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008739
Guido van Rossumd57fd912000-03-10 22:53:23 +00008740 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008741 PyErr_BadArgument();
8742 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008743 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008744
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008745 if (PyUnicode_READY(input) == -1)
8746 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008747 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008748 kind = PyUnicode_KIND(input);
8749 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008750
8751 if (size == 0) {
8752 Py_INCREF(input);
8753 return input;
8754 }
8755
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008756 /* allocate enough for a simple 1:1 translation without
8757 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008758 _PyUnicodeWriter_Init(&writer);
8759 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008760 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008761
Victor Stinner872b2912014-04-05 14:27:07 +02008762 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
8763
8764 res = unicode_fast_translate(input, mapping, &writer, ignore);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008765 if (res < 0) {
8766 _PyUnicodeWriter_Dealloc(&writer);
8767 return NULL;
8768 }
8769 if (res == 1)
8770 return _PyUnicodeWriter_Finish(&writer);
8771
Victor Stinner89a76ab2014-04-05 11:44:04 +02008772 i = writer.pos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008773 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008774 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008775 int translate;
8776 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8777 Py_ssize_t newpos;
8778 /* startpos for collecting untranslatable chars */
8779 Py_ssize_t collstart;
8780 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02008781 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008782
Victor Stinner1194ea02014-04-04 19:37:40 +02008783 ch = PyUnicode_READ(kind, data, i);
8784 translate = charmaptranslate_output(ch, mapping, &writer);
8785 if (translate < 0)
8786 goto onError;
8787
8788 if (translate != 0) {
8789 /* it worked => adjust input pointer */
8790 ++i;
8791 continue;
8792 }
8793
8794 /* untranslatable character */
8795 collstart = i;
8796 collend = i+1;
8797
8798 /* find all untranslatable characters */
8799 while (collend < size) {
8800 PyObject *x;
8801 ch = PyUnicode_READ(kind, data, collend);
8802 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008803 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02008804 Py_XDECREF(x);
8805 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008806 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02008807 ++collend;
8808 }
8809
8810 if (ignore) {
8811 i = collend;
8812 }
8813 else {
8814 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
8815 reason, input, &exc,
8816 collstart, collend, &newpos);
8817 if (repunicode == NULL)
8818 goto onError;
8819 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008820 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02008821 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008822 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008823 Py_DECREF(repunicode);
8824 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008825 }
8826 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008827 Py_XDECREF(exc);
8828 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02008829 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008830
Benjamin Peterson29060642009-01-31 22:14:21 +00008831 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02008832 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008833 Py_XDECREF(exc);
8834 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008835 return NULL;
8836}
8837
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008838/* Deprecated. Use PyUnicode_Translate instead. */
8839PyObject *
8840PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8841 Py_ssize_t size,
8842 PyObject *mapping,
8843 const char *errors)
8844{
Christian Heimes5f520f42012-09-11 14:03:25 +02008845 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008846 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8847 if (!unicode)
8848 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02008849 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8850 Py_DECREF(unicode);
8851 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008852}
8853
Alexander Belopolsky40018472011-02-26 01:02:56 +00008854PyObject *
8855PyUnicode_Translate(PyObject *str,
8856 PyObject *mapping,
8857 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008858{
8859 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008860
Guido van Rossumd57fd912000-03-10 22:53:23 +00008861 str = PyUnicode_FromObject(str);
8862 if (str == NULL)
Christian Heimes5f520f42012-09-11 14:03:25 +02008863 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008864 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008865 Py_DECREF(str);
8866 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008867}
Tim Petersced69f82003-09-16 20:30:58 +00008868
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008869static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008870fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008871{
8872 /* No need to call PyUnicode_READY(self) because this function is only
8873 called as a callback from fixup() which does it already. */
8874 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8875 const int kind = PyUnicode_KIND(self);
8876 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008877 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008878 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008879 Py_ssize_t i;
8880
8881 for (i = 0; i < len; ++i) {
8882 ch = PyUnicode_READ(kind, data, i);
8883 fixed = 0;
8884 if (ch > 127) {
8885 if (Py_UNICODE_ISSPACE(ch))
8886 fixed = ' ';
8887 else {
8888 const int decimal = Py_UNICODE_TODECIMAL(ch);
8889 if (decimal >= 0)
8890 fixed = '0' + decimal;
8891 }
8892 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008893 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008894 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008895 PyUnicode_WRITE(kind, data, i, fixed);
8896 }
Victor Stinnere6abb482012-05-02 01:15:40 +02008897 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07008898 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008899 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008900 }
8901
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008902 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008903}
8904
8905PyObject *
8906_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8907{
8908 if (!PyUnicode_Check(unicode)) {
8909 PyErr_BadInternalCall();
8910 return NULL;
8911 }
8912 if (PyUnicode_READY(unicode) == -1)
8913 return NULL;
8914 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8915 /* If the string is already ASCII, just return the same string */
8916 Py_INCREF(unicode);
8917 return unicode;
8918 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008919 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008920}
8921
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008922PyObject *
8923PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8924 Py_ssize_t length)
8925{
Victor Stinnerf0124502011-11-21 23:12:56 +01008926 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008927 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008928 Py_UCS4 maxchar;
8929 enum PyUnicode_Kind kind;
8930 void *data;
8931
Victor Stinner99d7ad02012-02-22 13:37:39 +01008932 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008933 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02008934 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008935 if (ch > 127) {
8936 int decimal = Py_UNICODE_TODECIMAL(ch);
8937 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008938 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008939 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008940 }
8941 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008942
8943 /* Copy to a new string */
8944 decimal = PyUnicode_New(length, maxchar);
8945 if (decimal == NULL)
8946 return decimal;
8947 kind = PyUnicode_KIND(decimal);
8948 data = PyUnicode_DATA(decimal);
8949 /* Iterate over code points */
8950 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02008951 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01008952 if (ch > 127) {
8953 int decimal = Py_UNICODE_TODECIMAL(ch);
8954 if (decimal >= 0)
8955 ch = '0' + decimal;
8956 }
8957 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008958 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008959 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008960}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008961/* --- Decimal Encoder ---------------------------------------------------- */
8962
Alexander Belopolsky40018472011-02-26 01:02:56 +00008963int
8964PyUnicode_EncodeDecimal(Py_UNICODE *s,
8965 Py_ssize_t length,
8966 char *output,
8967 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008968{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008969 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008970 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008971 enum PyUnicode_Kind kind;
8972 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008973
8974 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008975 PyErr_BadArgument();
8976 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008977 }
8978
Victor Stinner42bf7752011-11-21 22:52:58 +01008979 unicode = PyUnicode_FromUnicode(s, length);
8980 if (unicode == NULL)
8981 return -1;
8982
Benjamin Petersonbac79492012-01-14 13:34:47 -05008983 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01008984 Py_DECREF(unicode);
8985 return -1;
8986 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008987 kind = PyUnicode_KIND(unicode);
8988 data = PyUnicode_DATA(unicode);
8989
Victor Stinnerb84d7232011-11-22 01:50:07 +01008990 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008991 PyObject *exc;
8992 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008993 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008994 Py_ssize_t startpos;
8995
8996 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008997
Benjamin Peterson29060642009-01-31 22:14:21 +00008998 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008999 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009000 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009001 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009002 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009003 decimal = Py_UNICODE_TODECIMAL(ch);
9004 if (decimal >= 0) {
9005 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009006 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009007 continue;
9008 }
9009 if (0 < ch && ch < 256) {
9010 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009011 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009012 continue;
9013 }
Victor Stinner6345be92011-11-25 20:09:01 +01009014
Victor Stinner42bf7752011-11-21 22:52:58 +01009015 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009016 exc = NULL;
9017 raise_encode_exception(&exc, "decimal", unicode,
9018 startpos, startpos+1,
9019 "invalid decimal Unicode string");
9020 Py_XDECREF(exc);
9021 Py_DECREF(unicode);
9022 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009023 }
9024 /* 0-terminate the output string */
9025 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009026 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009027 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009028}
9029
Guido van Rossumd57fd912000-03-10 22:53:23 +00009030/* --- Helpers ------------------------------------------------------------ */
9031
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009032/* helper macro to fixup start/end slice values */
9033#define ADJUST_INDICES(start, end, len) \
9034 if (end > len) \
9035 end = len; \
9036 else if (end < 0) { \
9037 end += len; \
9038 if (end < 0) \
9039 end = 0; \
9040 } \
9041 if (start < 0) { \
9042 start += len; \
9043 if (start < 0) \
9044 start = 0; \
9045 }
9046
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009047static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02009048any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009049 Py_ssize_t start,
9050 Py_ssize_t end)
9051{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009052 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009053 void *buf1, *buf2;
9054 Py_ssize_t len1, len2, result;
9055
9056 kind1 = PyUnicode_KIND(s1);
9057 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009058 if (kind1 < kind2)
9059 return -1;
9060
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009061 len1 = PyUnicode_GET_LENGTH(s1);
9062 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009063 ADJUST_INDICES(start, end, len1);
9064 if (end - start < len2)
9065 return -1;
9066
9067 buf1 = PyUnicode_DATA(s1);
9068 buf2 = PyUnicode_DATA(s2);
9069 if (len2 == 1) {
9070 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9071 result = findchar((const char *)buf1 + kind1*start,
9072 kind1, end - start, ch, direction);
9073 if (result == -1)
9074 return -1;
9075 else
9076 return start + result;
9077 }
9078
9079 if (kind2 != kind1) {
9080 buf2 = _PyUnicode_AsKind(s2, kind1);
9081 if (!buf2)
9082 return -2;
9083 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009084
Victor Stinner794d5672011-10-10 03:21:36 +02009085 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009086 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009087 case PyUnicode_1BYTE_KIND:
9088 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9089 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9090 else
9091 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9092 break;
9093 case PyUnicode_2BYTE_KIND:
9094 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9095 break;
9096 case PyUnicode_4BYTE_KIND:
9097 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9098 break;
9099 default:
9100 assert(0); result = -2;
9101 }
9102 }
9103 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009104 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009105 case PyUnicode_1BYTE_KIND:
9106 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9107 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9108 else
9109 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9110 break;
9111 case PyUnicode_2BYTE_KIND:
9112 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9113 break;
9114 case PyUnicode_4BYTE_KIND:
9115 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9116 break;
9117 default:
9118 assert(0); result = -2;
9119 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009120 }
9121
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009122 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009123 PyMem_Free(buf2);
9124
9125 return result;
9126}
9127
9128Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009129_PyUnicode_InsertThousandsGrouping(
9130 PyObject *unicode, Py_ssize_t index,
9131 Py_ssize_t n_buffer,
9132 void *digits, Py_ssize_t n_digits,
9133 Py_ssize_t min_width,
9134 const char *grouping, PyObject *thousands_sep,
9135 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009136{
Victor Stinner41a863c2012-02-24 00:37:51 +01009137 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009138 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009139 Py_ssize_t thousands_sep_len;
9140 Py_ssize_t len;
9141
9142 if (unicode != NULL) {
9143 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009144 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009145 }
9146 else {
9147 kind = PyUnicode_1BYTE_KIND;
9148 data = NULL;
9149 }
9150 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9151 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9152 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9153 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009154 if (thousands_sep_kind < kind) {
9155 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9156 if (!thousands_sep_data)
9157 return -1;
9158 }
9159 else {
9160 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9161 if (!data)
9162 return -1;
9163 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009164 }
9165
Benjamin Petersonead6b532011-12-20 17:23:42 -06009166 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009167 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009168 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009169 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009170 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009171 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009172 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009173 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009174 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009175 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009176 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009177 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009178 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009179 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009180 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009181 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009182 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009183 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009184 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009185 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009186 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009187 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009188 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009189 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009190 break;
9191 default:
9192 assert(0);
9193 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009194 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009195 if (unicode != NULL && thousands_sep_kind != kind) {
9196 if (thousands_sep_kind < kind)
9197 PyMem_Free(thousands_sep_data);
9198 else
9199 PyMem_Free(data);
9200 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009201 if (unicode == NULL) {
9202 *maxchar = 127;
9203 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009204 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009205 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009206 }
9207 }
9208 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009209}
9210
9211
Alexander Belopolsky40018472011-02-26 01:02:56 +00009212Py_ssize_t
9213PyUnicode_Count(PyObject *str,
9214 PyObject *substr,
9215 Py_ssize_t start,
9216 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009217{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009218 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009219 PyObject* str_obj;
9220 PyObject* sub_obj;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009221 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009222 void *buf1 = NULL, *buf2 = NULL;
9223 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009224
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009225 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009226 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00009227 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009228 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009229 if (!sub_obj) {
9230 Py_DECREF(str_obj);
9231 return -1;
9232 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06009233 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06009234 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00009235 Py_DECREF(str_obj);
9236 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009237 }
Tim Petersced69f82003-09-16 20:30:58 +00009238
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009239 kind1 = PyUnicode_KIND(str_obj);
9240 kind2 = PyUnicode_KIND(sub_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009241 if (kind1 < kind2) {
9242 Py_DECREF(sub_obj);
9243 Py_DECREF(str_obj);
9244 return 0;
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05009245 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009246
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009247 len1 = PyUnicode_GET_LENGTH(str_obj);
9248 len2 = PyUnicode_GET_LENGTH(sub_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009249 ADJUST_INDICES(start, end, len1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009250 if (end - start < len2) {
9251 Py_DECREF(sub_obj);
9252 Py_DECREF(str_obj);
9253 return 0;
9254 }
9255
9256 buf1 = PyUnicode_DATA(str_obj);
9257 buf2 = PyUnicode_DATA(sub_obj);
9258 if (kind2 != kind1) {
9259 buf2 = _PyUnicode_AsKind(sub_obj, kind1);
9260 if (!buf2)
9261 goto onError;
9262 }
9263
9264 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009265 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009266 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9267 result = asciilib_count(
9268 ((Py_UCS1*)buf1) + start, end - start,
9269 buf2, len2, PY_SSIZE_T_MAX
9270 );
9271 else
9272 result = ucs1lib_count(
9273 ((Py_UCS1*)buf1) + start, end - start,
9274 buf2, len2, PY_SSIZE_T_MAX
9275 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009276 break;
9277 case PyUnicode_2BYTE_KIND:
9278 result = ucs2lib_count(
9279 ((Py_UCS2*)buf1) + start, end - start,
9280 buf2, len2, PY_SSIZE_T_MAX
9281 );
9282 break;
9283 case PyUnicode_4BYTE_KIND:
9284 result = ucs4lib_count(
9285 ((Py_UCS4*)buf1) + start, end - start,
9286 buf2, len2, PY_SSIZE_T_MAX
9287 );
9288 break;
9289 default:
9290 assert(0); result = 0;
9291 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009292
9293 Py_DECREF(sub_obj);
9294 Py_DECREF(str_obj);
9295
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009296 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009297 PyMem_Free(buf2);
9298
Guido van Rossumd57fd912000-03-10 22:53:23 +00009299 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009300 onError:
9301 Py_DECREF(sub_obj);
9302 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009303 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009304 PyMem_Free(buf2);
9305 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009306}
9307
Alexander Belopolsky40018472011-02-26 01:02:56 +00009308Py_ssize_t
9309PyUnicode_Find(PyObject *str,
9310 PyObject *sub,
9311 Py_ssize_t start,
9312 Py_ssize_t end,
9313 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009314{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009315 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009316
Guido van Rossumd57fd912000-03-10 22:53:23 +00009317 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009318 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009319 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009320 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009321 if (!sub) {
9322 Py_DECREF(str);
9323 return -2;
9324 }
9325 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9326 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009327 Py_DECREF(str);
9328 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009329 }
Tim Petersced69f82003-09-16 20:30:58 +00009330
Victor Stinner794d5672011-10-10 03:21:36 +02009331 result = any_find_slice(direction,
9332 str, sub, start, end
9333 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009334
Guido van Rossumd57fd912000-03-10 22:53:23 +00009335 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009336 Py_DECREF(sub);
9337
Guido van Rossumd57fd912000-03-10 22:53:23 +00009338 return result;
9339}
9340
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009341Py_ssize_t
9342PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9343 Py_ssize_t start, Py_ssize_t end,
9344 int direction)
9345{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009346 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009347 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009348 if (PyUnicode_READY(str) == -1)
9349 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009350 if (start < 0 || end < 0) {
9351 PyErr_SetString(PyExc_IndexError, "string index out of range");
9352 return -2;
9353 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009354 if (end > PyUnicode_GET_LENGTH(str))
9355 end = PyUnicode_GET_LENGTH(str);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009356 if (start >= end)
9357 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009358 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009359 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9360 kind, end-start, ch, direction);
9361 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009362 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009363 else
9364 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009365}
9366
Alexander Belopolsky40018472011-02-26 01:02:56 +00009367static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009368tailmatch(PyObject *self,
9369 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009370 Py_ssize_t start,
9371 Py_ssize_t end,
9372 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009373{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009374 int kind_self;
9375 int kind_sub;
9376 void *data_self;
9377 void *data_sub;
9378 Py_ssize_t offset;
9379 Py_ssize_t i;
9380 Py_ssize_t end_sub;
9381
9382 if (PyUnicode_READY(self) == -1 ||
9383 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009384 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009385
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009386 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9387 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009388 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009389 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009390
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009391 if (PyUnicode_GET_LENGTH(substring) == 0)
9392 return 1;
9393
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009394 kind_self = PyUnicode_KIND(self);
9395 data_self = PyUnicode_DATA(self);
9396 kind_sub = PyUnicode_KIND(substring);
9397 data_sub = PyUnicode_DATA(substring);
9398 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9399
9400 if (direction > 0)
9401 offset = end;
9402 else
9403 offset = start;
9404
9405 if (PyUnicode_READ(kind_self, data_self, offset) ==
9406 PyUnicode_READ(kind_sub, data_sub, 0) &&
9407 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9408 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9409 /* If both are of the same kind, memcmp is sufficient */
9410 if (kind_self == kind_sub) {
9411 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009412 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009413 data_sub,
9414 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009415 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009416 }
9417 /* otherwise we have to compare each character by first accesing it */
9418 else {
9419 /* We do not need to compare 0 and len(substring)-1 because
9420 the if statement above ensured already that they are equal
9421 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009422 for (i = 1; i < end_sub; ++i) {
9423 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9424 PyUnicode_READ(kind_sub, data_sub, i))
9425 return 0;
9426 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009427 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009428 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009429 }
9430
9431 return 0;
9432}
9433
Alexander Belopolsky40018472011-02-26 01:02:56 +00009434Py_ssize_t
9435PyUnicode_Tailmatch(PyObject *str,
9436 PyObject *substr,
9437 Py_ssize_t start,
9438 Py_ssize_t end,
9439 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009440{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009441 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009442
Guido van Rossumd57fd912000-03-10 22:53:23 +00009443 str = PyUnicode_FromObject(str);
9444 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009445 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009446 substr = PyUnicode_FromObject(substr);
9447 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009448 Py_DECREF(str);
9449 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009450 }
Tim Petersced69f82003-09-16 20:30:58 +00009451
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009452 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009453 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009454 Py_DECREF(str);
9455 Py_DECREF(substr);
9456 return result;
9457}
9458
Guido van Rossumd57fd912000-03-10 22:53:23 +00009459/* Apply fixfct filter to the Unicode object self and return a
9460 reference to the modified object */
9461
Alexander Belopolsky40018472011-02-26 01:02:56 +00009462static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009463fixup(PyObject *self,
9464 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009465{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009466 PyObject *u;
9467 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009468 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009469
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009470 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009471 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009472 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009473 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009474
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009475 /* fix functions return the new maximum character in a string,
9476 if the kind of the resulting unicode object does not change,
9477 everything is fine. Otherwise we need to change the string kind
9478 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009479 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009480
9481 if (maxchar_new == 0) {
9482 /* no changes */;
9483 if (PyUnicode_CheckExact(self)) {
9484 Py_DECREF(u);
9485 Py_INCREF(self);
9486 return self;
9487 }
9488 else
9489 return u;
9490 }
9491
Victor Stinnere6abb482012-05-02 01:15:40 +02009492 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009493
Victor Stinnereaab6042011-12-11 22:22:39 +01009494 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009495 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009496
9497 /* In case the maximum character changed, we need to
9498 convert the string to the new category. */
9499 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9500 if (v == NULL) {
9501 Py_DECREF(u);
9502 return NULL;
9503 }
9504 if (maxchar_new > maxchar_old) {
9505 /* If the maxchar increased so that the kind changed, not all
9506 characters are representable anymore and we need to fix the
9507 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009508 _PyUnicode_FastCopyCharacters(v, 0,
9509 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009510 maxchar_old = fixfct(v);
9511 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009512 }
9513 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009514 _PyUnicode_FastCopyCharacters(v, 0,
9515 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009516 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009517 Py_DECREF(u);
9518 assert(_PyUnicode_CheckConsistency(v, 1));
9519 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009520}
9521
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009522static PyObject *
9523ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009524{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009525 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9526 char *resdata, *data = PyUnicode_DATA(self);
9527 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009528
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009529 res = PyUnicode_New(len, 127);
9530 if (res == NULL)
9531 return NULL;
9532 resdata = PyUnicode_DATA(res);
9533 if (lower)
9534 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009535 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009536 _Py_bytes_upper(resdata, data, len);
9537 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009538}
9539
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009540static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009541handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009542{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009543 Py_ssize_t j;
9544 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009545 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009546 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009547
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009548 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9549
9550 where ! is a negation and \p{xxx} is a character with property xxx.
9551 */
9552 for (j = i - 1; j >= 0; j--) {
9553 c = PyUnicode_READ(kind, data, j);
9554 if (!_PyUnicode_IsCaseIgnorable(c))
9555 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009556 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009557 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9558 if (final_sigma) {
9559 for (j = i + 1; j < length; j++) {
9560 c = PyUnicode_READ(kind, data, j);
9561 if (!_PyUnicode_IsCaseIgnorable(c))
9562 break;
9563 }
9564 final_sigma = j == length || !_PyUnicode_IsCased(c);
9565 }
9566 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009567}
9568
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009569static int
9570lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9571 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009572{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009573 /* Obscure special case. */
9574 if (c == 0x3A3) {
9575 mapped[0] = handle_capital_sigma(kind, data, length, i);
9576 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009577 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009578 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009579}
9580
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009581static Py_ssize_t
9582do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009583{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009584 Py_ssize_t i, k = 0;
9585 int n_res, j;
9586 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009587
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009588 c = PyUnicode_READ(kind, data, 0);
9589 n_res = _PyUnicode_ToUpperFull(c, mapped);
9590 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009591 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009592 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009593 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009594 for (i = 1; i < length; i++) {
9595 c = PyUnicode_READ(kind, data, i);
9596 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9597 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009598 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009599 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009600 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009601 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009602 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009603}
9604
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009605static Py_ssize_t
9606do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9607 Py_ssize_t i, k = 0;
9608
9609 for (i = 0; i < length; i++) {
9610 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9611 int n_res, j;
9612 if (Py_UNICODE_ISUPPER(c)) {
9613 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9614 }
9615 else if (Py_UNICODE_ISLOWER(c)) {
9616 n_res = _PyUnicode_ToUpperFull(c, mapped);
9617 }
9618 else {
9619 n_res = 1;
9620 mapped[0] = c;
9621 }
9622 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009623 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009624 res[k++] = mapped[j];
9625 }
9626 }
9627 return k;
9628}
9629
9630static Py_ssize_t
9631do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9632 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009633{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009634 Py_ssize_t i, k = 0;
9635
9636 for (i = 0; i < length; i++) {
9637 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9638 int n_res, j;
9639 if (lower)
9640 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9641 else
9642 n_res = _PyUnicode_ToUpperFull(c, mapped);
9643 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009644 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009645 res[k++] = mapped[j];
9646 }
9647 }
9648 return k;
9649}
9650
9651static Py_ssize_t
9652do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9653{
9654 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9655}
9656
9657static Py_ssize_t
9658do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9659{
9660 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9661}
9662
Benjamin Petersone51757f2012-01-12 21:10:29 -05009663static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009664do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9665{
9666 Py_ssize_t i, k = 0;
9667
9668 for (i = 0; i < length; i++) {
9669 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9670 Py_UCS4 mapped[3];
9671 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9672 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009673 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009674 res[k++] = mapped[j];
9675 }
9676 }
9677 return k;
9678}
9679
9680static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009681do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9682{
9683 Py_ssize_t i, k = 0;
9684 int previous_is_cased;
9685
9686 previous_is_cased = 0;
9687 for (i = 0; i < length; i++) {
9688 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9689 Py_UCS4 mapped[3];
9690 int n_res, j;
9691
9692 if (previous_is_cased)
9693 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9694 else
9695 n_res = _PyUnicode_ToTitleFull(c, mapped);
9696
9697 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009698 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009699 res[k++] = mapped[j];
9700 }
9701
9702 previous_is_cased = _PyUnicode_IsCased(c);
9703 }
9704 return k;
9705}
9706
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009707static PyObject *
9708case_operation(PyObject *self,
9709 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9710{
9711 PyObject *res = NULL;
9712 Py_ssize_t length, newlength = 0;
9713 int kind, outkind;
9714 void *data, *outdata;
9715 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9716
Benjamin Petersoneea48462012-01-16 14:28:50 -05009717 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009718
9719 kind = PyUnicode_KIND(self);
9720 data = PyUnicode_DATA(self);
9721 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009722 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009723 PyErr_SetString(PyExc_OverflowError, "string is too long");
9724 return NULL;
9725 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009726 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009727 if (tmp == NULL)
9728 return PyErr_NoMemory();
9729 newlength = perform(kind, data, length, tmp, &maxchar);
9730 res = PyUnicode_New(newlength, maxchar);
9731 if (res == NULL)
9732 goto leave;
9733 tmpend = tmp + newlength;
9734 outdata = PyUnicode_DATA(res);
9735 outkind = PyUnicode_KIND(res);
9736 switch (outkind) {
9737 case PyUnicode_1BYTE_KIND:
9738 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9739 break;
9740 case PyUnicode_2BYTE_KIND:
9741 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9742 break;
9743 case PyUnicode_4BYTE_KIND:
9744 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9745 break;
9746 default:
9747 assert(0);
9748 break;
9749 }
9750 leave:
9751 PyMem_FREE(tmp);
9752 return res;
9753}
9754
Tim Peters8ce9f162004-08-27 01:49:32 +00009755PyObject *
9756PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009757{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009758 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009759 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009760 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009761 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009762 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9763 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009764 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009765 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009766 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009767 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009768 int use_memcpy;
9769 unsigned char *res_data = NULL, *sep_data = NULL;
9770 PyObject *last_obj;
9771 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009772
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009773 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009774 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009775 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009776 }
9777
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009778 /* NOTE: the following code can't call back into Python code,
9779 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009780 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009781
Tim Peters05eba1f2004-08-27 21:32:02 +00009782 seqlen = PySequence_Fast_GET_SIZE(fseq);
9783 /* If empty sequence, return u"". */
9784 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009785 Py_DECREF(fseq);
Serhiy Storchaka678db842013-01-26 12:16:36 +02009786 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009787 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009788
Tim Peters05eba1f2004-08-27 21:32:02 +00009789 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009790 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009791 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009792 if (seqlen == 1) {
9793 if (PyUnicode_CheckExact(items[0])) {
9794 res = items[0];
9795 Py_INCREF(res);
9796 Py_DECREF(fseq);
9797 return res;
9798 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009799 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009800 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009801 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009802 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009803 /* Set up sep and seplen */
9804 if (separator == NULL) {
9805 /* fall back to a blank space separator */
9806 sep = PyUnicode_FromOrdinal(' ');
9807 if (!sep)
9808 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009809 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009810 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009811 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009812 else {
9813 if (!PyUnicode_Check(separator)) {
9814 PyErr_Format(PyExc_TypeError,
9815 "separator: expected str instance,"
9816 " %.80s found",
9817 Py_TYPE(separator)->tp_name);
9818 goto onError;
9819 }
9820 if (PyUnicode_READY(separator))
9821 goto onError;
9822 sep = separator;
9823 seplen = PyUnicode_GET_LENGTH(separator);
9824 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9825 /* inc refcount to keep this code path symmetric with the
9826 above case of a blank separator */
9827 Py_INCREF(sep);
9828 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009829 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009830 }
9831
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009832 /* There are at least two things to join, or else we have a subclass
9833 * of str in the sequence.
9834 * Do a pre-pass to figure out the total amount of space we'll
9835 * need (sz), and see whether all argument are strings.
9836 */
9837 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009838#ifdef Py_DEBUG
9839 use_memcpy = 0;
9840#else
9841 use_memcpy = 1;
9842#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009843 for (i = 0; i < seqlen; i++) {
9844 const Py_ssize_t old_sz = sz;
9845 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009846 if (!PyUnicode_Check(item)) {
9847 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +02009848 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +00009849 " %.80s found",
9850 i, Py_TYPE(item)->tp_name);
9851 goto onError;
9852 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009853 if (PyUnicode_READY(item) == -1)
9854 goto onError;
9855 sz += PyUnicode_GET_LENGTH(item);
9856 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009857 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009858 if (i != 0)
9859 sz += seplen;
9860 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9861 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009862 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009863 goto onError;
9864 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009865 if (use_memcpy && last_obj != NULL) {
9866 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9867 use_memcpy = 0;
9868 }
9869 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009870 }
Tim Petersced69f82003-09-16 20:30:58 +00009871
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009872 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009873 if (res == NULL)
9874 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009875
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009876 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009877#ifdef Py_DEBUG
9878 use_memcpy = 0;
9879#else
9880 if (use_memcpy) {
9881 res_data = PyUnicode_1BYTE_DATA(res);
9882 kind = PyUnicode_KIND(res);
9883 if (seplen != 0)
9884 sep_data = PyUnicode_1BYTE_DATA(sep);
9885 }
9886#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009887 if (use_memcpy) {
9888 for (i = 0; i < seqlen; ++i) {
9889 Py_ssize_t itemlen;
9890 item = items[i];
9891
9892 /* Copy item, and maybe the separator. */
9893 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009894 Py_MEMCPY(res_data,
9895 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009896 kind * seplen);
9897 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009898 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009899
9900 itemlen = PyUnicode_GET_LENGTH(item);
9901 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009902 Py_MEMCPY(res_data,
9903 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009904 kind * itemlen);
9905 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009906 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009907 }
9908 assert(res_data == PyUnicode_1BYTE_DATA(res)
9909 + kind * PyUnicode_GET_LENGTH(res));
9910 }
9911 else {
9912 for (i = 0, res_offset = 0; i < seqlen; ++i) {
9913 Py_ssize_t itemlen;
9914 item = items[i];
9915
9916 /* Copy item, and maybe the separator. */
9917 if (i && seplen != 0) {
9918 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
9919 res_offset += seplen;
9920 }
9921
9922 itemlen = PyUnicode_GET_LENGTH(item);
9923 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009924 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009925 res_offset += itemlen;
9926 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009927 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009928 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +02009929 }
Tim Peters8ce9f162004-08-27 01:49:32 +00009930
Tim Peters05eba1f2004-08-27 21:32:02 +00009931 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009932 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009933 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009934 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009935
Benjamin Peterson29060642009-01-31 22:14:21 +00009936 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009937 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009938 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009939 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009940 return NULL;
9941}
9942
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009943#define FILL(kind, data, value, start, length) \
9944 do { \
9945 Py_ssize_t i_ = 0; \
9946 assert(kind != PyUnicode_WCHAR_KIND); \
9947 switch ((kind)) { \
9948 case PyUnicode_1BYTE_KIND: { \
9949 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009950 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009951 break; \
9952 } \
9953 case PyUnicode_2BYTE_KIND: { \
9954 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9955 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9956 break; \
9957 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009958 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009959 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9960 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9961 break; \
9962 } \
Serhiy Storchaka133b11b2014-12-01 18:56:28 +02009963 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009964 } \
9965 } while (0)
9966
Victor Stinnerd3f08822012-05-29 12:57:52 +02009967void
9968_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9969 Py_UCS4 fill_char)
9970{
9971 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
9972 const void *data = PyUnicode_DATA(unicode);
9973 assert(PyUnicode_IS_READY(unicode));
9974 assert(unicode_modifiable(unicode));
9975 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
9976 assert(start >= 0);
9977 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
9978 FILL(kind, data, fill_char, start, length);
9979}
9980
Victor Stinner3fe55312012-01-04 00:33:50 +01009981Py_ssize_t
9982PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9983 Py_UCS4 fill_char)
9984{
9985 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +01009986
9987 if (!PyUnicode_Check(unicode)) {
9988 PyErr_BadInternalCall();
9989 return -1;
9990 }
9991 if (PyUnicode_READY(unicode) == -1)
9992 return -1;
9993 if (unicode_check_modifiable(unicode))
9994 return -1;
9995
Victor Stinnerd3f08822012-05-29 12:57:52 +02009996 if (start < 0) {
9997 PyErr_SetString(PyExc_IndexError, "string index out of range");
9998 return -1;
9999 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010000 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10001 PyErr_SetString(PyExc_ValueError,
10002 "fill character is bigger than "
10003 "the string maximum character");
10004 return -1;
10005 }
10006
10007 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10008 length = Py_MIN(maxlen, length);
10009 if (length <= 0)
10010 return 0;
10011
Victor Stinnerd3f08822012-05-29 12:57:52 +020010012 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010013 return length;
10014}
10015
Victor Stinner9310abb2011-10-05 00:59:23 +020010016static PyObject *
10017pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010018 Py_ssize_t left,
10019 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010020 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010021{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010022 PyObject *u;
10023 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010024 int kind;
10025 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010026
10027 if (left < 0)
10028 left = 0;
10029 if (right < 0)
10030 right = 0;
10031
Victor Stinnerc4b49542011-12-11 22:44:26 +010010032 if (left == 0 && right == 0)
10033 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010034
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010035 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10036 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010037 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10038 return NULL;
10039 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010040 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010041 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010042 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010043 if (!u)
10044 return NULL;
10045
10046 kind = PyUnicode_KIND(u);
10047 data = PyUnicode_DATA(u);
10048 if (left)
10049 FILL(kind, data, fill, 0, left);
10050 if (right)
10051 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010052 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010053 assert(_PyUnicode_CheckConsistency(u, 1));
10054 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010055}
10056
Alexander Belopolsky40018472011-02-26 01:02:56 +000010057PyObject *
10058PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010059{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010060 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010061
10062 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010063 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010064 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060010065 if (PyUnicode_READY(string) == -1) {
10066 Py_DECREF(string);
10067 return NULL;
10068 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010069
Benjamin Petersonead6b532011-12-20 17:23:42 -060010070 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010071 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010072 if (PyUnicode_IS_ASCII(string))
10073 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010074 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010075 PyUnicode_GET_LENGTH(string), keepends);
10076 else
10077 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010078 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010079 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010080 break;
10081 case PyUnicode_2BYTE_KIND:
10082 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010083 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010084 PyUnicode_GET_LENGTH(string), keepends);
10085 break;
10086 case PyUnicode_4BYTE_KIND:
10087 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010088 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010089 PyUnicode_GET_LENGTH(string), keepends);
10090 break;
10091 default:
10092 assert(0);
10093 list = 0;
10094 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010095 Py_DECREF(string);
10096 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010097}
10098
Alexander Belopolsky40018472011-02-26 01:02:56 +000010099static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010100split(PyObject *self,
10101 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010102 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010103{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010104 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010105 void *buf1, *buf2;
10106 Py_ssize_t len1, len2;
10107 PyObject* out;
10108
Guido van Rossumd57fd912000-03-10 22:53:23 +000010109 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010110 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010111
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010112 if (PyUnicode_READY(self) == -1)
10113 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010114
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010115 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010116 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010117 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010118 if (PyUnicode_IS_ASCII(self))
10119 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010120 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010121 PyUnicode_GET_LENGTH(self), maxcount
10122 );
10123 else
10124 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010125 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010126 PyUnicode_GET_LENGTH(self), maxcount
10127 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010128 case PyUnicode_2BYTE_KIND:
10129 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010130 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010131 PyUnicode_GET_LENGTH(self), maxcount
10132 );
10133 case PyUnicode_4BYTE_KIND:
10134 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010135 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010136 PyUnicode_GET_LENGTH(self), maxcount
10137 );
10138 default:
10139 assert(0);
10140 return NULL;
10141 }
10142
10143 if (PyUnicode_READY(substring) == -1)
10144 return NULL;
10145
10146 kind1 = PyUnicode_KIND(self);
10147 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010148 len1 = PyUnicode_GET_LENGTH(self);
10149 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010150 if (kind1 < kind2 || len1 < len2) {
10151 out = PyList_New(1);
10152 if (out == NULL)
10153 return NULL;
10154 Py_INCREF(self);
10155 PyList_SET_ITEM(out, 0, self);
10156 return out;
10157 }
10158 buf1 = PyUnicode_DATA(self);
10159 buf2 = PyUnicode_DATA(substring);
10160 if (kind2 != kind1) {
10161 buf2 = _PyUnicode_AsKind(substring, kind1);
10162 if (!buf2)
10163 return NULL;
10164 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010165
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010166 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010167 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010168 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10169 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010170 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010171 else
10172 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010173 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010174 break;
10175 case PyUnicode_2BYTE_KIND:
10176 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010177 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010178 break;
10179 case PyUnicode_4BYTE_KIND:
10180 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010181 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010182 break;
10183 default:
10184 out = NULL;
10185 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010186 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010187 PyMem_Free(buf2);
10188 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010189}
10190
Alexander Belopolsky40018472011-02-26 01:02:56 +000010191static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010192rsplit(PyObject *self,
10193 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010194 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010195{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010196 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010197 void *buf1, *buf2;
10198 Py_ssize_t len1, len2;
10199 PyObject* out;
10200
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010201 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010202 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010203
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010204 if (PyUnicode_READY(self) == -1)
10205 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010206
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010207 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010208 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010209 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010210 if (PyUnicode_IS_ASCII(self))
10211 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010212 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010213 PyUnicode_GET_LENGTH(self), maxcount
10214 );
10215 else
10216 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010217 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010218 PyUnicode_GET_LENGTH(self), maxcount
10219 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010220 case PyUnicode_2BYTE_KIND:
10221 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010222 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010223 PyUnicode_GET_LENGTH(self), maxcount
10224 );
10225 case PyUnicode_4BYTE_KIND:
10226 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010227 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010228 PyUnicode_GET_LENGTH(self), maxcount
10229 );
10230 default:
10231 assert(0);
10232 return NULL;
10233 }
10234
10235 if (PyUnicode_READY(substring) == -1)
10236 return NULL;
10237
10238 kind1 = PyUnicode_KIND(self);
10239 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010240 len1 = PyUnicode_GET_LENGTH(self);
10241 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010242 if (kind1 < kind2 || len1 < len2) {
10243 out = PyList_New(1);
10244 if (out == NULL)
10245 return NULL;
10246 Py_INCREF(self);
10247 PyList_SET_ITEM(out, 0, self);
10248 return out;
10249 }
10250 buf1 = PyUnicode_DATA(self);
10251 buf2 = PyUnicode_DATA(substring);
10252 if (kind2 != kind1) {
10253 buf2 = _PyUnicode_AsKind(substring, kind1);
10254 if (!buf2)
10255 return NULL;
10256 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010257
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010258 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010259 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010260 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10261 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010262 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010263 else
10264 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010265 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010266 break;
10267 case PyUnicode_2BYTE_KIND:
10268 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010269 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010270 break;
10271 case PyUnicode_4BYTE_KIND:
10272 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010273 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010274 break;
10275 default:
10276 out = NULL;
10277 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010278 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010279 PyMem_Free(buf2);
10280 return out;
10281}
10282
10283static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010284anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10285 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010286{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010287 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010288 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010289 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10290 return asciilib_find(buf1, len1, buf2, len2, offset);
10291 else
10292 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010293 case PyUnicode_2BYTE_KIND:
10294 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10295 case PyUnicode_4BYTE_KIND:
10296 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10297 }
10298 assert(0);
10299 return -1;
10300}
10301
10302static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010303anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10304 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010305{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010306 switch (kind) {
10307 case PyUnicode_1BYTE_KIND:
10308 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10309 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10310 else
10311 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10312 case PyUnicode_2BYTE_KIND:
10313 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10314 case PyUnicode_4BYTE_KIND:
10315 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10316 }
10317 assert(0);
10318 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010319}
10320
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010321static void
10322replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10323 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10324{
10325 int kind = PyUnicode_KIND(u);
10326 void *data = PyUnicode_DATA(u);
10327 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10328 if (kind == PyUnicode_1BYTE_KIND) {
10329 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10330 (Py_UCS1 *)data + len,
10331 u1, u2, maxcount);
10332 }
10333 else if (kind == PyUnicode_2BYTE_KIND) {
10334 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10335 (Py_UCS2 *)data + len,
10336 u1, u2, maxcount);
10337 }
10338 else {
10339 assert(kind == PyUnicode_4BYTE_KIND);
10340 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10341 (Py_UCS4 *)data + len,
10342 u1, u2, maxcount);
10343 }
10344}
10345
Alexander Belopolsky40018472011-02-26 01:02:56 +000010346static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010347replace(PyObject *self, PyObject *str1,
10348 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010349{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010350 PyObject *u;
10351 char *sbuf = PyUnicode_DATA(self);
10352 char *buf1 = PyUnicode_DATA(str1);
10353 char *buf2 = PyUnicode_DATA(str2);
10354 int srelease = 0, release1 = 0, release2 = 0;
10355 int skind = PyUnicode_KIND(self);
10356 int kind1 = PyUnicode_KIND(str1);
10357 int kind2 = PyUnicode_KIND(str2);
10358 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10359 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10360 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010361 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010362 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010363
10364 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010365 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010366 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010367 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010368
Victor Stinner59de0ee2011-10-07 10:01:28 +020010369 if (str1 == str2)
10370 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010371
Victor Stinner49a0a212011-10-12 23:46:10 +020010372 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010373 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10374 if (maxchar < maxchar_str1)
10375 /* substring too wide to be present */
10376 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010377 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10378 /* Replacing str1 with str2 may cause a maxchar reduction in the
10379 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010380 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010381 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010382
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010383 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010384 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010385 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010386 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010387 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010388 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010389 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010390 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010391
Victor Stinner69ed0f42013-04-09 21:48:24 +020010392 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010393 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010394 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010395 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010396 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010397 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010398 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010399 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010400
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010401 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10402 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010403 }
10404 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010405 int rkind = skind;
10406 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010407 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010408
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010409 if (kind1 < rkind) {
10410 /* widen substring */
10411 buf1 = _PyUnicode_AsKind(str1, rkind);
10412 if (!buf1) goto error;
10413 release1 = 1;
10414 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010415 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010416 if (i < 0)
10417 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010418 if (rkind > kind2) {
10419 /* widen replacement */
10420 buf2 = _PyUnicode_AsKind(str2, rkind);
10421 if (!buf2) goto error;
10422 release2 = 1;
10423 }
10424 else if (rkind < kind2) {
10425 /* widen self and buf1 */
10426 rkind = kind2;
10427 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010428 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010429 sbuf = _PyUnicode_AsKind(self, rkind);
10430 if (!sbuf) goto error;
10431 srelease = 1;
10432 buf1 = _PyUnicode_AsKind(str1, rkind);
10433 if (!buf1) goto error;
10434 release1 = 1;
10435 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010436 u = PyUnicode_New(slen, maxchar);
10437 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010438 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010439 assert(PyUnicode_KIND(u) == rkind);
10440 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010441
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010442 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010443 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010444 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010445 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010446 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010447 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010448
10449 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010450 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010451 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010452 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010453 if (i == -1)
10454 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010455 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010456 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010457 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010458 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010459 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010460 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010461 }
10462 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010463 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010464 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010465 int rkind = skind;
10466 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010467
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010468 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010469 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010470 buf1 = _PyUnicode_AsKind(str1, rkind);
10471 if (!buf1) goto error;
10472 release1 = 1;
10473 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010474 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010475 if (n == 0)
10476 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010477 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010478 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010479 buf2 = _PyUnicode_AsKind(str2, rkind);
10480 if (!buf2) goto error;
10481 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010482 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010483 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010484 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010485 rkind = kind2;
10486 sbuf = _PyUnicode_AsKind(self, rkind);
10487 if (!sbuf) goto error;
10488 srelease = 1;
10489 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010490 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010491 buf1 = _PyUnicode_AsKind(str1, rkind);
10492 if (!buf1) goto error;
10493 release1 = 1;
10494 }
10495 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10496 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010497 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010498 PyErr_SetString(PyExc_OverflowError,
10499 "replace string is too long");
10500 goto error;
10501 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010502 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010503 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010504 _Py_INCREF_UNICODE_EMPTY();
10505 if (!unicode_empty)
10506 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010507 u = unicode_empty;
10508 goto done;
10509 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010510 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010511 PyErr_SetString(PyExc_OverflowError,
10512 "replace string is too long");
10513 goto error;
10514 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010515 u = PyUnicode_New(new_size, maxchar);
10516 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010517 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010518 assert(PyUnicode_KIND(u) == rkind);
10519 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010520 ires = i = 0;
10521 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010522 while (n-- > 0) {
10523 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010524 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010525 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010526 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010527 if (j == -1)
10528 break;
10529 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010530 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010531 memcpy(res + rkind * ires,
10532 sbuf + rkind * i,
10533 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010534 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010535 }
10536 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010537 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010538 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010539 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010540 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010541 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010542 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010543 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010544 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010545 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010546 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010547 memcpy(res + rkind * ires,
10548 sbuf + rkind * i,
10549 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010550 }
10551 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010552 /* interleave */
10553 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010554 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010555 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010556 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010557 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010558 if (--n <= 0)
10559 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010560 memcpy(res + rkind * ires,
10561 sbuf + rkind * i,
10562 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010563 ires++;
10564 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010565 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010566 memcpy(res + rkind * ires,
10567 sbuf + rkind * i,
10568 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010569 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010570 }
10571
10572 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010573 unicode_adjust_maxchar(&u);
10574 if (u == NULL)
10575 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010576 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010577
10578 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010579 if (srelease)
10580 PyMem_FREE(sbuf);
10581 if (release1)
10582 PyMem_FREE(buf1);
10583 if (release2)
10584 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010585 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010586 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010587
Benjamin Peterson29060642009-01-31 22:14:21 +000010588 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010589 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010590 if (srelease)
10591 PyMem_FREE(sbuf);
10592 if (release1)
10593 PyMem_FREE(buf1);
10594 if (release2)
10595 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010596 return unicode_result_unchanged(self);
10597
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010598 error:
10599 if (srelease && sbuf)
10600 PyMem_FREE(sbuf);
10601 if (release1 && buf1)
10602 PyMem_FREE(buf1);
10603 if (release2 && buf2)
10604 PyMem_FREE(buf2);
10605 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010606}
10607
10608/* --- Unicode Object Methods --------------------------------------------- */
10609
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010610PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010611 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010612\n\
10613Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010614characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010615
10616static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010617unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010618{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010619 if (PyUnicode_READY(self) == -1)
10620 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010621 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010622}
10623
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010624PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010625 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010626\n\
10627Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010628have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010629
10630static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010631unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010632{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010633 if (PyUnicode_READY(self) == -1)
10634 return NULL;
10635 if (PyUnicode_GET_LENGTH(self) == 0)
10636 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010637 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010638}
10639
Benjamin Petersond5890c82012-01-14 13:23:30 -050010640PyDoc_STRVAR(casefold__doc__,
10641 "S.casefold() -> str\n\
10642\n\
10643Return a version of S suitable for caseless comparisons.");
10644
10645static PyObject *
10646unicode_casefold(PyObject *self)
10647{
10648 if (PyUnicode_READY(self) == -1)
10649 return NULL;
10650 if (PyUnicode_IS_ASCII(self))
10651 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010652 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010653}
10654
10655
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010656/* Argument converter. Coerces to a single unicode character */
10657
10658static int
10659convert_uc(PyObject *obj, void *addr)
10660{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010661 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010662 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010663
Benjamin Peterson14339b62009-01-31 16:36:08 +000010664 uniobj = PyUnicode_FromObject(obj);
10665 if (uniobj == NULL) {
10666 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010667 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010668 return 0;
10669 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010670 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010671 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010672 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010673 Py_DECREF(uniobj);
10674 return 0;
10675 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010676 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010677 Py_DECREF(uniobj);
10678 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010679}
10680
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010681PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010682 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010683\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010684Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010685done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010686
10687static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010688unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010689{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010690 Py_ssize_t marg, left;
10691 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010692 Py_UCS4 fillchar = ' ';
10693
Victor Stinnere9a29352011-10-01 02:14:59 +020010694 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010695 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010696
Benjamin Petersonbac79492012-01-14 13:34:47 -050010697 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010698 return NULL;
10699
Victor Stinnerc4b49542011-12-11 22:44:26 +010010700 if (PyUnicode_GET_LENGTH(self) >= width)
10701 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010702
Victor Stinnerc4b49542011-12-11 22:44:26 +010010703 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010704 left = marg / 2 + (marg & width & 1);
10705
Victor Stinner9310abb2011-10-05 00:59:23 +020010706 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010707}
10708
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010709/* This function assumes that str1 and str2 are readied by the caller. */
10710
Marc-André Lemburge5034372000-08-08 08:04:29 +000010711static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010712unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010713{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010714#define COMPARE(TYPE1, TYPE2) \
10715 do { \
10716 TYPE1* p1 = (TYPE1 *)data1; \
10717 TYPE2* p2 = (TYPE2 *)data2; \
10718 TYPE1* end = p1 + len; \
10719 Py_UCS4 c1, c2; \
10720 for (; p1 != end; p1++, p2++) { \
10721 c1 = *p1; \
10722 c2 = *p2; \
10723 if (c1 != c2) \
10724 return (c1 < c2) ? -1 : 1; \
10725 } \
10726 } \
10727 while (0)
10728
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010729 int kind1, kind2;
10730 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010731 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010732
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010733 kind1 = PyUnicode_KIND(str1);
10734 kind2 = PyUnicode_KIND(str2);
10735 data1 = PyUnicode_DATA(str1);
10736 data2 = PyUnicode_DATA(str2);
10737 len1 = PyUnicode_GET_LENGTH(str1);
10738 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010739 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010740
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010741 switch(kind1) {
10742 case PyUnicode_1BYTE_KIND:
10743 {
10744 switch(kind2) {
10745 case PyUnicode_1BYTE_KIND:
10746 {
10747 int cmp = memcmp(data1, data2, len);
10748 /* normalize result of memcmp() into the range [-1; 1] */
10749 if (cmp < 0)
10750 return -1;
10751 if (cmp > 0)
10752 return 1;
10753 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010754 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010755 case PyUnicode_2BYTE_KIND:
10756 COMPARE(Py_UCS1, Py_UCS2);
10757 break;
10758 case PyUnicode_4BYTE_KIND:
10759 COMPARE(Py_UCS1, Py_UCS4);
10760 break;
10761 default:
10762 assert(0);
10763 }
10764 break;
10765 }
10766 case PyUnicode_2BYTE_KIND:
10767 {
10768 switch(kind2) {
10769 case PyUnicode_1BYTE_KIND:
10770 COMPARE(Py_UCS2, Py_UCS1);
10771 break;
10772 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010773 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010774 COMPARE(Py_UCS2, Py_UCS2);
10775 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010776 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010777 case PyUnicode_4BYTE_KIND:
10778 COMPARE(Py_UCS2, Py_UCS4);
10779 break;
10780 default:
10781 assert(0);
10782 }
10783 break;
10784 }
10785 case PyUnicode_4BYTE_KIND:
10786 {
10787 switch(kind2) {
10788 case PyUnicode_1BYTE_KIND:
10789 COMPARE(Py_UCS4, Py_UCS1);
10790 break;
10791 case PyUnicode_2BYTE_KIND:
10792 COMPARE(Py_UCS4, Py_UCS2);
10793 break;
10794 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010795 {
10796#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10797 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10798 /* normalize result of wmemcmp() into the range [-1; 1] */
10799 if (cmp < 0)
10800 return -1;
10801 if (cmp > 0)
10802 return 1;
10803#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010804 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010805#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010806 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010807 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010808 default:
10809 assert(0);
10810 }
10811 break;
10812 }
10813 default:
10814 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010815 }
10816
Victor Stinner770e19e2012-10-04 22:59:45 +020010817 if (len1 == len2)
10818 return 0;
10819 if (len1 < len2)
10820 return -1;
10821 else
10822 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010823
10824#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010825}
10826
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010827Py_LOCAL(int)
Victor Stinnere5567ad2012-10-23 02:48:49 +020010828unicode_compare_eq(PyObject *str1, PyObject *str2)
10829{
10830 int kind;
10831 void *data1, *data2;
10832 Py_ssize_t len;
10833 int cmp;
10834
Victor Stinnere5567ad2012-10-23 02:48:49 +020010835 len = PyUnicode_GET_LENGTH(str1);
10836 if (PyUnicode_GET_LENGTH(str2) != len)
10837 return 0;
10838 kind = PyUnicode_KIND(str1);
10839 if (PyUnicode_KIND(str2) != kind)
10840 return 0;
10841 data1 = PyUnicode_DATA(str1);
10842 data2 = PyUnicode_DATA(str2);
10843
10844 cmp = memcmp(data1, data2, len * kind);
10845 return (cmp == 0);
10846}
10847
10848
Alexander Belopolsky40018472011-02-26 01:02:56 +000010849int
10850PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010851{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010852 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10853 if (PyUnicode_READY(left) == -1 ||
10854 PyUnicode_READY(right) == -1)
10855 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010856
10857 /* a string is equal to itself */
10858 if (left == right)
10859 return 0;
10860
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010861 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010862 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010863 PyErr_Format(PyExc_TypeError,
10864 "Can't compare %.100s and %.100s",
10865 left->ob_type->tp_name,
10866 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010867 return -1;
10868}
10869
Martin v. Löwis5b222132007-06-10 09:51:05 +000010870int
Victor Stinnerad14ccd2013-11-07 00:46:04 +010010871_PyUnicode_CompareWithId(PyObject *left, _Py_Identifier *right)
10872{
10873 PyObject *right_str = _PyUnicode_FromId(right); /* borrowed */
10874 if (right_str == NULL)
10875 return -1;
10876 return PyUnicode_Compare(left, right_str);
10877}
10878
10879int
Martin v. Löwis5b222132007-06-10 09:51:05 +000010880PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10881{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010882 Py_ssize_t i;
10883 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010884 Py_UCS4 chr;
10885
Victor Stinner910337b2011-10-03 03:20:16 +020010886 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010887 if (PyUnicode_READY(uni) == -1)
10888 return -1;
10889 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010890 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010010891 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010010892 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010893 size_t len, len2 = strlen(str);
10894 int cmp;
10895
10896 len = Py_MIN(len1, len2);
10897 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010010898 if (cmp != 0) {
10899 if (cmp < 0)
10900 return -1;
10901 else
10902 return 1;
10903 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010010904 if (len1 > len2)
10905 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010906 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010010907 return -1; /* str is longer */
10908 return 0;
10909 }
10910 else {
10911 void *data = PyUnicode_DATA(uni);
10912 /* Compare Unicode string and source character set string */
10913 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020010914 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010010915 return (chr < (unsigned char)(str[i])) ? -1 : 1;
10916 /* This check keeps Python strings that end in '\0' from comparing equal
10917 to C strings identical up to that point. */
10918 if (PyUnicode_GET_LENGTH(uni) != i || chr)
10919 return 1; /* uni is longer */
10920 if (str[i])
10921 return -1; /* str is longer */
10922 return 0;
10923 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000010924}
10925
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010926
Benjamin Peterson29060642009-01-31 22:14:21 +000010927#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010928 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010929
Alexander Belopolsky40018472011-02-26 01:02:56 +000010930PyObject *
10931PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010932{
10933 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020010934 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010935
Victor Stinnere5567ad2012-10-23 02:48:49 +020010936 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
10937 Py_RETURN_NOTIMPLEMENTED;
10938
10939 if (PyUnicode_READY(left) == -1 ||
10940 PyUnicode_READY(right) == -1)
10941 return NULL;
10942
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010010943 if (left == right) {
10944 switch (op) {
10945 case Py_EQ:
10946 case Py_LE:
10947 case Py_GE:
10948 /* a string is equal to itself */
10949 v = Py_True;
10950 break;
10951 case Py_NE:
10952 case Py_LT:
10953 case Py_GT:
10954 v = Py_False;
10955 break;
10956 default:
10957 PyErr_BadArgument();
10958 return NULL;
10959 }
10960 }
10961 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020010962 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010963 result ^= (op == Py_NE);
10964 v = TEST_COND(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020010965 }
10966 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020010967 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010968
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010969 /* Convert the return value to a Boolean */
10970 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010971 case Py_LE:
10972 v = TEST_COND(result <= 0);
10973 break;
10974 case Py_GE:
10975 v = TEST_COND(result >= 0);
10976 break;
10977 case Py_LT:
10978 v = TEST_COND(result == -1);
10979 break;
10980 case Py_GT:
10981 v = TEST_COND(result == 1);
10982 break;
10983 default:
10984 PyErr_BadArgument();
10985 return NULL;
10986 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010987 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020010988 Py_INCREF(v);
10989 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010990}
10991
Alexander Belopolsky40018472011-02-26 01:02:56 +000010992int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070010993_PyUnicode_EQ(PyObject *aa, PyObject *bb)
10994{
10995 return unicode_eq(aa, bb);
10996}
10997
10998int
Alexander Belopolsky40018472011-02-26 01:02:56 +000010999PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011000{
Thomas Wouters477c8d52006-05-27 19:21:47 +000011001 PyObject *str, *sub;
Victor Stinner77282cb2013-04-14 19:22:47 +020011002 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011003 void *buf1, *buf2;
11004 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011005 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011006
11007 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000011008 sub = PyUnicode_FromObject(element);
11009 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011010 PyErr_Format(PyExc_TypeError,
11011 "'in <string>' requires string as left operand, not %s",
11012 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011013 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011014 }
11015
Thomas Wouters477c8d52006-05-27 19:21:47 +000011016 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060011017 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000011018 Py_DECREF(sub);
11019 return -1;
11020 }
11021
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011022 kind1 = PyUnicode_KIND(str);
11023 kind2 = PyUnicode_KIND(sub);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011024 if (kind1 < kind2) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011025 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050011026 Py_DECREF(str);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011027 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011028 }
11029 len1 = PyUnicode_GET_LENGTH(str);
11030 len2 = PyUnicode_GET_LENGTH(sub);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011031 if (len1 < len2) {
11032 Py_DECREF(sub);
11033 Py_DECREF(str);
11034 return 0;
11035 }
11036 buf1 = PyUnicode_DATA(str);
11037 buf2 = PyUnicode_DATA(sub);
11038 if (len2 == 1) {
11039 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11040 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
11041 Py_DECREF(sub);
11042 Py_DECREF(str);
11043 return result;
11044 }
11045 if (kind2 != kind1) {
11046 buf2 = _PyUnicode_AsKind(sub, kind1);
11047 if (!buf2) {
11048 Py_DECREF(sub);
11049 Py_DECREF(str);
11050 return -1;
11051 }
11052 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011053
Victor Stinner77282cb2013-04-14 19:22:47 +020011054 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011055 case PyUnicode_1BYTE_KIND:
11056 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11057 break;
11058 case PyUnicode_2BYTE_KIND:
11059 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11060 break;
11061 case PyUnicode_4BYTE_KIND:
11062 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11063 break;
11064 default:
11065 result = -1;
11066 assert(0);
11067 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011068
11069 Py_DECREF(str);
11070 Py_DECREF(sub);
11071
Victor Stinner77282cb2013-04-14 19:22:47 +020011072 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011073 PyMem_Free(buf2);
11074
Guido van Rossum403d68b2000-03-13 15:55:09 +000011075 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011076}
11077
Guido van Rossumd57fd912000-03-10 22:53:23 +000011078/* Concat to string or Unicode object giving a new Unicode object. */
11079
Alexander Belopolsky40018472011-02-26 01:02:56 +000011080PyObject *
11081PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011082{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011083 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020011084 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010011085 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011086
11087 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011088 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011089 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011090 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011091 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011092 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011093 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011094
11095 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020011096 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011097 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011098 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011099 }
Victor Stinnera464fc12011-10-02 20:39:30 +020011100 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011101 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011102 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011103 }
11104
Victor Stinner488fa492011-12-12 00:01:39 +010011105 u_len = PyUnicode_GET_LENGTH(u);
11106 v_len = PyUnicode_GET_LENGTH(v);
11107 if (u_len > PY_SSIZE_T_MAX - v_len) {
11108 PyErr_SetString(PyExc_OverflowError,
11109 "strings are too large to concat");
11110 goto onError;
11111 }
11112 new_len = u_len + v_len;
11113
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011114 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020011115 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011116 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011117
Guido van Rossumd57fd912000-03-10 22:53:23 +000011118 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010011119 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011120 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011121 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011122 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
11123 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011124 Py_DECREF(u);
11125 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011126 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011127 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011128
Benjamin Peterson29060642009-01-31 22:14:21 +000011129 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000011130 Py_XDECREF(u);
11131 Py_XDECREF(v);
11132 return NULL;
11133}
11134
Walter Dörwald1ab83302007-05-18 17:15:44 +000011135void
Victor Stinner23e56682011-10-03 03:54:37 +020011136PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011137{
Victor Stinner23e56682011-10-03 03:54:37 +020011138 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011139 Py_UCS4 maxchar, maxchar2;
11140 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011141
11142 if (p_left == NULL) {
11143 if (!PyErr_Occurred())
11144 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011145 return;
11146 }
Victor Stinner23e56682011-10-03 03:54:37 +020011147 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011148 if (right == NULL || left == NULL
11149 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011150 if (!PyErr_Occurred())
11151 PyErr_BadInternalCall();
11152 goto error;
11153 }
11154
Benjamin Petersonbac79492012-01-14 13:34:47 -050011155 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011156 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011157 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011158 goto error;
11159
Victor Stinner488fa492011-12-12 00:01:39 +010011160 /* Shortcuts */
11161 if (left == unicode_empty) {
11162 Py_DECREF(left);
11163 Py_INCREF(right);
11164 *p_left = right;
11165 return;
11166 }
11167 if (right == unicode_empty)
11168 return;
11169
11170 left_len = PyUnicode_GET_LENGTH(left);
11171 right_len = PyUnicode_GET_LENGTH(right);
11172 if (left_len > PY_SSIZE_T_MAX - right_len) {
11173 PyErr_SetString(PyExc_OverflowError,
11174 "strings are too large to concat");
11175 goto error;
11176 }
11177 new_len = left_len + right_len;
11178
11179 if (unicode_modifiable(left)
11180 && PyUnicode_CheckExact(right)
11181 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011182 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11183 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011184 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011185 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011186 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11187 {
11188 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011189 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011190 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011191
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011192 /* copy 'right' into the newly allocated area of 'left' */
11193 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011194 }
Victor Stinner488fa492011-12-12 00:01:39 +010011195 else {
11196 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11197 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011198 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011199
Victor Stinner488fa492011-12-12 00:01:39 +010011200 /* Concat the two Unicode strings */
11201 res = PyUnicode_New(new_len, maxchar);
11202 if (res == NULL)
11203 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011204 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11205 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011206 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011207 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011208 }
11209 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011210 return;
11211
11212error:
Victor Stinner488fa492011-12-12 00:01:39 +010011213 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011214}
11215
11216void
11217PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11218{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011219 PyUnicode_Append(pleft, right);
11220 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011221}
11222
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011223PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011224 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011225\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011226Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011227string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011228interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011229
11230static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011231unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011232{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011233 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011234 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011235 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011236 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011237 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011238 void *buf1, *buf2;
11239 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011240
Jesus Ceaac451502011-04-20 17:09:23 +020011241 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
11242 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011243 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011244
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011245 kind1 = PyUnicode_KIND(self);
11246 kind2 = PyUnicode_KIND(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011247 if (kind1 < kind2) {
Christian Heimesd47802e2013-06-29 21:33:36 +020011248 Py_DECREF(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011249 return PyLong_FromLong(0);
Christian Heimesd47802e2013-06-29 21:33:36 +020011250 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011251 len1 = PyUnicode_GET_LENGTH(self);
11252 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011253 ADJUST_INDICES(start, end, len1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011254 if (end - start < len2) {
11255 Py_DECREF(substring);
11256 return PyLong_FromLong(0);
11257 }
11258 buf1 = PyUnicode_DATA(self);
11259 buf2 = PyUnicode_DATA(substring);
11260 if (kind2 != kind1) {
11261 buf2 = _PyUnicode_AsKind(substring, kind1);
11262 if (!buf2) {
11263 Py_DECREF(substring);
11264 return NULL;
11265 }
11266 }
11267 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011268 case PyUnicode_1BYTE_KIND:
11269 iresult = ucs1lib_count(
11270 ((Py_UCS1*)buf1) + start, end - start,
11271 buf2, len2, PY_SSIZE_T_MAX
11272 );
11273 break;
11274 case PyUnicode_2BYTE_KIND:
11275 iresult = ucs2lib_count(
11276 ((Py_UCS2*)buf1) + start, end - start,
11277 buf2, len2, PY_SSIZE_T_MAX
11278 );
11279 break;
11280 case PyUnicode_4BYTE_KIND:
11281 iresult = ucs4lib_count(
11282 ((Py_UCS4*)buf1) + start, end - start,
11283 buf2, len2, PY_SSIZE_T_MAX
11284 );
11285 break;
11286 default:
11287 assert(0); iresult = 0;
11288 }
11289
11290 result = PyLong_FromSsize_t(iresult);
11291
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011292 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011293 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011294
11295 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011296
Guido van Rossumd57fd912000-03-10 22:53:23 +000011297 return result;
11298}
11299
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011300PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011301 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011302\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011303Encode S using the codec registered for encoding. Default encoding\n\
11304is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011305handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011306a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11307'xmlcharrefreplace' as well as any other name registered with\n\
11308codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011309
11310static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011311unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011312{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011313 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011314 char *encoding = NULL;
11315 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011316
Benjamin Peterson308d6372009-09-18 21:42:35 +000011317 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11318 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011319 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011320 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011321}
11322
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011323PyDoc_STRVAR(expandtabs__doc__,
Ezio Melotti745d54d2013-11-16 19:10:57 +020011324 "S.expandtabs(tabsize=8) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011325\n\
11326Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011327If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011328
11329static PyObject*
Ezio Melotti745d54d2013-11-16 19:10:57 +020011330unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011331{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011332 Py_ssize_t i, j, line_pos, src_len, incr;
11333 Py_UCS4 ch;
11334 PyObject *u;
11335 void *src_data, *dest_data;
Ezio Melotti745d54d2013-11-16 19:10:57 +020011336 static char *kwlist[] = {"tabsize", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011337 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011338 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011339 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011340
Ezio Melotti745d54d2013-11-16 19:10:57 +020011341 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs",
11342 kwlist, &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011343 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011344
Antoine Pitrou22425222011-10-04 19:10:51 +020011345 if (PyUnicode_READY(self) == -1)
11346 return NULL;
11347
Thomas Wouters7e474022000-07-16 12:04:32 +000011348 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011349 src_len = PyUnicode_GET_LENGTH(self);
11350 i = j = line_pos = 0;
11351 kind = PyUnicode_KIND(self);
11352 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011353 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011354 for (; i < src_len; i++) {
11355 ch = PyUnicode_READ(kind, src_data, i);
11356 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011357 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011358 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011359 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011360 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011361 goto overflow;
11362 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011363 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011364 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011365 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011366 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011367 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011368 goto overflow;
11369 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011370 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011371 if (ch == '\n' || ch == '\r')
11372 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011373 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011374 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011375 if (!found)
11376 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011377
Guido van Rossumd57fd912000-03-10 22:53:23 +000011378 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011379 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011380 if (!u)
11381 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011382 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011383
Antoine Pitroue71d5742011-10-04 15:55:09 +020011384 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011385
Antoine Pitroue71d5742011-10-04 15:55:09 +020011386 for (; i < src_len; i++) {
11387 ch = PyUnicode_READ(kind, src_data, i);
11388 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011389 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011390 incr = tabsize - (line_pos % tabsize);
11391 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011392 FILL(kind, dest_data, ' ', j, incr);
11393 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011394 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011395 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011396 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011397 line_pos++;
11398 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011399 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011400 if (ch == '\n' || ch == '\r')
11401 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011402 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011403 }
11404 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011405 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011406
Antoine Pitroue71d5742011-10-04 15:55:09 +020011407 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011408 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11409 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011410}
11411
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011412PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011413 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011414\n\
11415Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011416such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011417arguments start and end are interpreted as in slice notation.\n\
11418\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011419Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011420
11421static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011422unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011423{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011424 /* initialize variables to prevent gcc warning */
11425 PyObject *substring = NULL;
11426 Py_ssize_t start = 0;
11427 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011428 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011429
Jesus Ceaac451502011-04-20 17:09:23 +020011430 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11431 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011432 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011433
Christian Heimesd47802e2013-06-29 21:33:36 +020011434 if (PyUnicode_READY(self) == -1) {
11435 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011436 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011437 }
11438 if (PyUnicode_READY(substring) == -1) {
11439 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011440 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011441 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011442
Victor Stinner7931d9a2011-11-04 00:22:48 +010011443 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011444
11445 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011446
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011447 if (result == -2)
11448 return NULL;
11449
Christian Heimes217cfd12007-12-02 14:31:20 +000011450 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011451}
11452
11453static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011454unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011455{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011456 void *data;
11457 enum PyUnicode_Kind kind;
11458 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011459
11460 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11461 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011462 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011463 }
11464 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11465 PyErr_SetString(PyExc_IndexError, "string index out of range");
11466 return NULL;
11467 }
11468 kind = PyUnicode_KIND(self);
11469 data = PyUnicode_DATA(self);
11470 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011471 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011472}
11473
Guido van Rossumc2504932007-09-18 19:42:40 +000011474/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011475 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011476static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011477unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011478{
Guido van Rossumc2504932007-09-18 19:42:40 +000011479 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011480 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011481
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011482#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011483 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011484#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011485 if (_PyUnicode_HASH(self) != -1)
11486 return _PyUnicode_HASH(self);
11487 if (PyUnicode_READY(self) == -1)
11488 return -1;
11489 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011490 /*
11491 We make the hash of the empty string be 0, rather than using
11492 (prefix ^ suffix), since this slightly obfuscates the hash secret
11493 */
11494 if (len == 0) {
11495 _PyUnicode_HASH(self) = 0;
11496 return 0;
11497 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011498 x = _Py_HashBytes(PyUnicode_DATA(self),
11499 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011500 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011501 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011502}
11503
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011504PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011505 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011506\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011507Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011508
11509static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011510unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011511{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011512 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011513 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011514 PyObject *substring = NULL;
11515 Py_ssize_t start = 0;
11516 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011517
Jesus Ceaac451502011-04-20 17:09:23 +020011518 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11519 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011520 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011521
Christian Heimesd47a0452013-06-29 21:21:37 +020011522 if (PyUnicode_READY(self) == -1) {
11523 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011524 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011525 }
11526 if (PyUnicode_READY(substring) == -1) {
11527 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011528 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011529 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011530
Victor Stinner7931d9a2011-11-04 00:22:48 +010011531 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011532
11533 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011534
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011535 if (result == -2)
11536 return NULL;
11537
Guido van Rossumd57fd912000-03-10 22:53:23 +000011538 if (result < 0) {
11539 PyErr_SetString(PyExc_ValueError, "substring not found");
11540 return NULL;
11541 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011542
Christian Heimes217cfd12007-12-02 14:31:20 +000011543 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011544}
11545
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011546PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011547 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011548\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011549Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011550at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011551
11552static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011553unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011554{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011555 Py_ssize_t i, length;
11556 int kind;
11557 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011558 int cased;
11559
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011560 if (PyUnicode_READY(self) == -1)
11561 return NULL;
11562 length = PyUnicode_GET_LENGTH(self);
11563 kind = PyUnicode_KIND(self);
11564 data = PyUnicode_DATA(self);
11565
Guido van Rossumd57fd912000-03-10 22:53:23 +000011566 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011567 if (length == 1)
11568 return PyBool_FromLong(
11569 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011570
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011571 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011572 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011573 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011574
Guido van Rossumd57fd912000-03-10 22:53:23 +000011575 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011576 for (i = 0; i < length; i++) {
11577 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011578
Benjamin Peterson29060642009-01-31 22:14:21 +000011579 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11580 return PyBool_FromLong(0);
11581 else if (!cased && Py_UNICODE_ISLOWER(ch))
11582 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011583 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011584 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011585}
11586
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011587PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011588 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011589\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011590Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011591at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011592
11593static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011594unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011595{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011596 Py_ssize_t i, length;
11597 int kind;
11598 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011599 int cased;
11600
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011601 if (PyUnicode_READY(self) == -1)
11602 return NULL;
11603 length = PyUnicode_GET_LENGTH(self);
11604 kind = PyUnicode_KIND(self);
11605 data = PyUnicode_DATA(self);
11606
Guido van Rossumd57fd912000-03-10 22:53:23 +000011607 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011608 if (length == 1)
11609 return PyBool_FromLong(
11610 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011611
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011612 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011613 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011614 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011615
Guido van Rossumd57fd912000-03-10 22:53:23 +000011616 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011617 for (i = 0; i < length; i++) {
11618 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011619
Benjamin Peterson29060642009-01-31 22:14:21 +000011620 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11621 return PyBool_FromLong(0);
11622 else if (!cased && Py_UNICODE_ISUPPER(ch))
11623 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011624 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011625 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011626}
11627
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011628PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011629 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011630\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011631Return True if S is a titlecased string and there is at least one\n\
11632character in S, i.e. upper- and titlecase characters may only\n\
11633follow uncased characters and lowercase characters only cased ones.\n\
11634Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011635
11636static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011637unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011638{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011639 Py_ssize_t i, length;
11640 int kind;
11641 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011642 int cased, previous_is_cased;
11643
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011644 if (PyUnicode_READY(self) == -1)
11645 return NULL;
11646 length = PyUnicode_GET_LENGTH(self);
11647 kind = PyUnicode_KIND(self);
11648 data = PyUnicode_DATA(self);
11649
Guido van Rossumd57fd912000-03-10 22:53:23 +000011650 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011651 if (length == 1) {
11652 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11653 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11654 (Py_UNICODE_ISUPPER(ch) != 0));
11655 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011656
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011657 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011658 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011659 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011660
Guido van Rossumd57fd912000-03-10 22:53:23 +000011661 cased = 0;
11662 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011663 for (i = 0; i < length; i++) {
11664 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011665
Benjamin Peterson29060642009-01-31 22:14:21 +000011666 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11667 if (previous_is_cased)
11668 return PyBool_FromLong(0);
11669 previous_is_cased = 1;
11670 cased = 1;
11671 }
11672 else if (Py_UNICODE_ISLOWER(ch)) {
11673 if (!previous_is_cased)
11674 return PyBool_FromLong(0);
11675 previous_is_cased = 1;
11676 cased = 1;
11677 }
11678 else
11679 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011680 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011681 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011682}
11683
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011684PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011685 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011686\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011687Return True if all characters in S are whitespace\n\
11688and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011689
11690static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011691unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011692{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011693 Py_ssize_t i, length;
11694 int kind;
11695 void *data;
11696
11697 if (PyUnicode_READY(self) == -1)
11698 return NULL;
11699 length = PyUnicode_GET_LENGTH(self);
11700 kind = PyUnicode_KIND(self);
11701 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011702
Guido van Rossumd57fd912000-03-10 22:53:23 +000011703 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011704 if (length == 1)
11705 return PyBool_FromLong(
11706 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011707
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011708 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011709 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011710 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011711
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011712 for (i = 0; i < length; i++) {
11713 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011714 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011715 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011716 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011717 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011718}
11719
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011720PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011721 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011722\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011723Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011724and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011725
11726static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011727unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011728{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011729 Py_ssize_t i, length;
11730 int kind;
11731 void *data;
11732
11733 if (PyUnicode_READY(self) == -1)
11734 return NULL;
11735 length = PyUnicode_GET_LENGTH(self);
11736 kind = PyUnicode_KIND(self);
11737 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011738
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011739 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011740 if (length == 1)
11741 return PyBool_FromLong(
11742 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011743
11744 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011745 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011746 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011747
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011748 for (i = 0; i < length; i++) {
11749 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011750 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011751 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011752 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011753}
11754
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011755PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011756 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011757\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011758Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011759and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011760
11761static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011762unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011763{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011764 int kind;
11765 void *data;
11766 Py_ssize_t len, i;
11767
11768 if (PyUnicode_READY(self) == -1)
11769 return NULL;
11770
11771 kind = PyUnicode_KIND(self);
11772 data = PyUnicode_DATA(self);
11773 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011774
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011775 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011776 if (len == 1) {
11777 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11778 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11779 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011780
11781 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011782 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011783 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011784
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011785 for (i = 0; i < len; i++) {
11786 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011787 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011788 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011789 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011790 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011791}
11792
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011793PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011794 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011795\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011796Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011797False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011798
11799static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011800unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011801{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011802 Py_ssize_t i, length;
11803 int kind;
11804 void *data;
11805
11806 if (PyUnicode_READY(self) == -1)
11807 return NULL;
11808 length = PyUnicode_GET_LENGTH(self);
11809 kind = PyUnicode_KIND(self);
11810 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011811
Guido van Rossumd57fd912000-03-10 22:53:23 +000011812 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011813 if (length == 1)
11814 return PyBool_FromLong(
11815 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011816
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011817 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011818 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011819 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011820
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011821 for (i = 0; i < length; i++) {
11822 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011823 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011824 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011825 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011826}
11827
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011828PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011829 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011830\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011831Return True if all characters in S are digits\n\
11832and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011833
11834static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011835unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011836{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011837 Py_ssize_t i, length;
11838 int kind;
11839 void *data;
11840
11841 if (PyUnicode_READY(self) == -1)
11842 return NULL;
11843 length = PyUnicode_GET_LENGTH(self);
11844 kind = PyUnicode_KIND(self);
11845 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011846
Guido van Rossumd57fd912000-03-10 22:53:23 +000011847 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011848 if (length == 1) {
11849 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11850 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11851 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011852
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011853 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011854 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011855 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011856
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011857 for (i = 0; i < length; i++) {
11858 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011859 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011860 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011861 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011862}
11863
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011864PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011865 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011866\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011867Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011868False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011869
11870static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011871unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011872{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011873 Py_ssize_t i, length;
11874 int kind;
11875 void *data;
11876
11877 if (PyUnicode_READY(self) == -1)
11878 return NULL;
11879 length = PyUnicode_GET_LENGTH(self);
11880 kind = PyUnicode_KIND(self);
11881 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011882
Guido van Rossumd57fd912000-03-10 22:53:23 +000011883 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011884 if (length == 1)
11885 return PyBool_FromLong(
11886 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011887
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011888 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011889 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011890 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011891
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011892 for (i = 0; i < length; i++) {
11893 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011894 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011895 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011896 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011897}
11898
Martin v. Löwis47383402007-08-15 07:32:56 +000011899int
11900PyUnicode_IsIdentifier(PyObject *self)
11901{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011902 int kind;
11903 void *data;
11904 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011905 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011906
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011907 if (PyUnicode_READY(self) == -1) {
11908 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011909 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011910 }
11911
11912 /* Special case for empty strings */
11913 if (PyUnicode_GET_LENGTH(self) == 0)
11914 return 0;
11915 kind = PyUnicode_KIND(self);
11916 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011917
11918 /* PEP 3131 says that the first character must be in
11919 XID_Start and subsequent characters in XID_Continue,
11920 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011921 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011922 letters, digits, underscore). However, given the current
11923 definition of XID_Start and XID_Continue, it is sufficient
11924 to check just for these, except that _ must be allowed
11925 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011926 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011927 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011928 return 0;
11929
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011930 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011931 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011932 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011933 return 1;
11934}
11935
11936PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011937 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011938\n\
11939Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070011940to the language definition.\n\
11941\n\
11942Use keyword.iskeyword() to test for reserved identifiers\n\
11943such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000011944
11945static PyObject*
11946unicode_isidentifier(PyObject *self)
11947{
11948 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11949}
11950
Georg Brandl559e5d72008-06-11 18:37:52 +000011951PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011952 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011953\n\
11954Return True if all characters in S are considered\n\
11955printable in repr() or S is empty, False otherwise.");
11956
11957static PyObject*
11958unicode_isprintable(PyObject *self)
11959{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011960 Py_ssize_t i, length;
11961 int kind;
11962 void *data;
11963
11964 if (PyUnicode_READY(self) == -1)
11965 return NULL;
11966 length = PyUnicode_GET_LENGTH(self);
11967 kind = PyUnicode_KIND(self);
11968 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011969
11970 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011971 if (length == 1)
11972 return PyBool_FromLong(
11973 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011974
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011975 for (i = 0; i < length; i++) {
11976 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011977 Py_RETURN_FALSE;
11978 }
11979 }
11980 Py_RETURN_TRUE;
11981}
11982
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011983PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011984 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011985\n\
11986Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011987iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011988
11989static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011990unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011991{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011992 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011993}
11994
Martin v. Löwis18e16552006-02-15 17:27:45 +000011995static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011996unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011997{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011998 if (PyUnicode_READY(self) == -1)
11999 return -1;
12000 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012001}
12002
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012003PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012004 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012005\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012006Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012007done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012008
12009static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012010unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012011{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012012 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012013 Py_UCS4 fillchar = ' ';
12014
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012015 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012016 return NULL;
12017
Benjamin Petersonbac79492012-01-14 13:34:47 -050012018 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012019 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012020
Victor Stinnerc4b49542011-12-11 22:44:26 +010012021 if (PyUnicode_GET_LENGTH(self) >= width)
12022 return unicode_result_unchanged(self);
12023
12024 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012025}
12026
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012027PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012028 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012029\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012030Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012031
12032static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012033unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012034{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012035 if (PyUnicode_READY(self) == -1)
12036 return NULL;
12037 if (PyUnicode_IS_ASCII(self))
12038 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012039 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012040}
12041
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012042#define LEFTSTRIP 0
12043#define RIGHTSTRIP 1
12044#define BOTHSTRIP 2
12045
12046/* Arrays indexed by above */
12047static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
12048
12049#define STRIPNAME(i) (stripformat[i]+3)
12050
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012051/* externally visible for str.strip(unicode) */
12052PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012053_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012054{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012055 void *data;
12056 int kind;
12057 Py_ssize_t i, j, len;
12058 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012059 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012060
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012061 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12062 return NULL;
12063
12064 kind = PyUnicode_KIND(self);
12065 data = PyUnicode_DATA(self);
12066 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012067 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012068 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12069 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012070 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012071
Benjamin Peterson14339b62009-01-31 16:36:08 +000012072 i = 0;
12073 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012074 while (i < len) {
12075 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12076 if (!BLOOM(sepmask, ch))
12077 break;
12078 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12079 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012080 i++;
12081 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012082 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012083
Benjamin Peterson14339b62009-01-31 16:36:08 +000012084 j = len;
12085 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012086 j--;
12087 while (j >= i) {
12088 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12089 if (!BLOOM(sepmask, ch))
12090 break;
12091 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12092 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012093 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012094 }
12095
Benjamin Peterson29060642009-01-31 22:14:21 +000012096 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012097 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012098
Victor Stinner7931d9a2011-11-04 00:22:48 +010012099 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012100}
12101
12102PyObject*
12103PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12104{
12105 unsigned char *data;
12106 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012107 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012108
Victor Stinnerde636f32011-10-01 03:55:54 +020012109 if (PyUnicode_READY(self) == -1)
12110 return NULL;
12111
Victor Stinner684d5fd2012-05-03 02:32:34 +020012112 length = PyUnicode_GET_LENGTH(self);
12113 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012114
Victor Stinner684d5fd2012-05-03 02:32:34 +020012115 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012116 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012117
Victor Stinnerde636f32011-10-01 03:55:54 +020012118 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012119 PyErr_SetString(PyExc_IndexError, "string index out of range");
12120 return NULL;
12121 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012122 if (start >= length || end < start)
12123 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012124
Victor Stinner684d5fd2012-05-03 02:32:34 +020012125 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012126 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012127 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012128 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012129 }
12130 else {
12131 kind = PyUnicode_KIND(self);
12132 data = PyUnicode_1BYTE_DATA(self);
12133 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012134 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012135 length);
12136 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012137}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012138
12139static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012140do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012141{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012142 Py_ssize_t len, i, j;
12143
12144 if (PyUnicode_READY(self) == -1)
12145 return NULL;
12146
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012147 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012148
Victor Stinnercc7af722013-04-09 22:39:24 +020012149 if (PyUnicode_IS_ASCII(self)) {
12150 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12151
12152 i = 0;
12153 if (striptype != RIGHTSTRIP) {
12154 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012155 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012156 if (!_Py_ascii_whitespace[ch])
12157 break;
12158 i++;
12159 }
12160 }
12161
12162 j = len;
12163 if (striptype != LEFTSTRIP) {
12164 j--;
12165 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012166 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012167 if (!_Py_ascii_whitespace[ch])
12168 break;
12169 j--;
12170 }
12171 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012172 }
12173 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012174 else {
12175 int kind = PyUnicode_KIND(self);
12176 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012177
Victor Stinnercc7af722013-04-09 22:39:24 +020012178 i = 0;
12179 if (striptype != RIGHTSTRIP) {
12180 while (i < len) {
12181 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12182 if (!Py_UNICODE_ISSPACE(ch))
12183 break;
12184 i++;
12185 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012186 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012187
12188 j = len;
12189 if (striptype != LEFTSTRIP) {
12190 j--;
12191 while (j >= i) {
12192 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12193 if (!Py_UNICODE_ISSPACE(ch))
12194 break;
12195 j--;
12196 }
12197 j++;
12198 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012199 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012200
Victor Stinner7931d9a2011-11-04 00:22:48 +010012201 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012202}
12203
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012204
12205static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012206do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012207{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012208 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012209
Serhiy Storchakac6792272013-10-19 21:03:34 +030012210 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012211 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012212
Benjamin Peterson14339b62009-01-31 16:36:08 +000012213 if (sep != NULL && sep != Py_None) {
12214 if (PyUnicode_Check(sep))
12215 return _PyUnicode_XStrip(self, striptype, sep);
12216 else {
12217 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012218 "%s arg must be None or str",
12219 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012220 return NULL;
12221 }
12222 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012223
Benjamin Peterson14339b62009-01-31 16:36:08 +000012224 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012225}
12226
12227
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012228PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012229 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012230\n\
12231Return a copy of the string S with leading and trailing\n\
12232whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012233If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012234
12235static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012236unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012237{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012238 if (PyTuple_GET_SIZE(args) == 0)
12239 return do_strip(self, BOTHSTRIP); /* Common case */
12240 else
12241 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012242}
12243
12244
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012245PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012246 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012247\n\
12248Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012249If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012250
12251static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012252unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012253{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012254 if (PyTuple_GET_SIZE(args) == 0)
12255 return do_strip(self, LEFTSTRIP); /* Common case */
12256 else
12257 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012258}
12259
12260
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012261PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012262 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012263\n\
12264Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012265If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012266
12267static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012268unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012269{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012270 if (PyTuple_GET_SIZE(args) == 0)
12271 return do_strip(self, RIGHTSTRIP); /* Common case */
12272 else
12273 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012274}
12275
12276
Guido van Rossumd57fd912000-03-10 22:53:23 +000012277static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012278unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012279{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012280 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012281 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012282
Serhiy Storchaka05997252013-01-26 12:14:02 +020012283 if (len < 1)
12284 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012285
Victor Stinnerc4b49542011-12-11 22:44:26 +010012286 /* no repeat, return original string */
12287 if (len == 1)
12288 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012289
Benjamin Petersonbac79492012-01-14 13:34:47 -050012290 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012291 return NULL;
12292
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012293 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012294 PyErr_SetString(PyExc_OverflowError,
12295 "repeated string is too long");
12296 return NULL;
12297 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012298 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012299
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012300 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012301 if (!u)
12302 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012303 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012304
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012305 if (PyUnicode_GET_LENGTH(str) == 1) {
12306 const int kind = PyUnicode_KIND(str);
12307 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012308 if (kind == PyUnicode_1BYTE_KIND) {
12309 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012310 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012311 }
12312 else if (kind == PyUnicode_2BYTE_KIND) {
12313 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012314 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012315 ucs2[n] = fill_char;
12316 } else {
12317 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12318 assert(kind == PyUnicode_4BYTE_KIND);
12319 for (n = 0; n < len; ++n)
12320 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012321 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012322 }
12323 else {
12324 /* number of characters copied this far */
12325 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012326 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012327 char *to = (char *) PyUnicode_DATA(u);
12328 Py_MEMCPY(to, PyUnicode_DATA(str),
12329 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012330 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012331 n = (done <= nchars-done) ? done : nchars-done;
12332 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012333 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012334 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012335 }
12336
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012337 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012338 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012339}
12340
Alexander Belopolsky40018472011-02-26 01:02:56 +000012341PyObject *
12342PyUnicode_Replace(PyObject *obj,
12343 PyObject *subobj,
12344 PyObject *replobj,
12345 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012346{
12347 PyObject *self;
12348 PyObject *str1;
12349 PyObject *str2;
12350 PyObject *result;
12351
12352 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012353 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012354 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012355 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012356 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012357 Py_DECREF(self);
12358 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012359 }
12360 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012361 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012362 Py_DECREF(self);
12363 Py_DECREF(str1);
12364 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012365 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012366 if (PyUnicode_READY(self) == -1 ||
12367 PyUnicode_READY(str1) == -1 ||
12368 PyUnicode_READY(str2) == -1)
12369 result = NULL;
12370 else
12371 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012372 Py_DECREF(self);
12373 Py_DECREF(str1);
12374 Py_DECREF(str2);
12375 return result;
12376}
12377
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012378PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012379 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012380\n\
12381Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012382old replaced by new. If the optional argument count is\n\
12383given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012384
12385static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012386unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012387{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012388 PyObject *str1;
12389 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012390 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012391 PyObject *result;
12392
Martin v. Löwis18e16552006-02-15 17:27:45 +000012393 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012394 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012395 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012396 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012397 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012398 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012399 return NULL;
12400 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012401 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012402 Py_DECREF(str1);
12403 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012404 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012405 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
12406 result = NULL;
12407 else
12408 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012409
12410 Py_DECREF(str1);
12411 Py_DECREF(str2);
12412 return result;
12413}
12414
Alexander Belopolsky40018472011-02-26 01:02:56 +000012415static PyObject *
12416unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012417{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012418 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012419 Py_ssize_t isize;
12420 Py_ssize_t osize, squote, dquote, i, o;
12421 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012422 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012423 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012424
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012425 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012426 return NULL;
12427
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012428 isize = PyUnicode_GET_LENGTH(unicode);
12429 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012430
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012431 /* Compute length of output, quote characters, and
12432 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012433 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012434 max = 127;
12435 squote = dquote = 0;
12436 ikind = PyUnicode_KIND(unicode);
12437 for (i = 0; i < isize; i++) {
12438 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012439 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012440 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012441 case '\'': squote++; break;
12442 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012443 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012444 incr = 2;
12445 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012446 default:
12447 /* Fast-path ASCII */
12448 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012449 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012450 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012451 ;
12452 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012453 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012454 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012455 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012456 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012457 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012458 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012459 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012460 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012461 if (osize > PY_SSIZE_T_MAX - incr) {
12462 PyErr_SetString(PyExc_OverflowError,
12463 "string is too long to generate repr");
12464 return NULL;
12465 }
12466 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012467 }
12468
12469 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012470 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012471 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012472 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012473 if (dquote)
12474 /* Both squote and dquote present. Use squote,
12475 and escape them */
12476 osize += squote;
12477 else
12478 quote = '"';
12479 }
Victor Stinner55c08782013-04-14 18:45:39 +020012480 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012481
12482 repr = PyUnicode_New(osize, max);
12483 if (repr == NULL)
12484 return NULL;
12485 okind = PyUnicode_KIND(repr);
12486 odata = PyUnicode_DATA(repr);
12487
12488 PyUnicode_WRITE(okind, odata, 0, quote);
12489 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012490 if (unchanged) {
12491 _PyUnicode_FastCopyCharacters(repr, 1,
12492 unicode, 0,
12493 isize);
12494 }
12495 else {
12496 for (i = 0, o = 1; i < isize; i++) {
12497 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012498
Victor Stinner55c08782013-04-14 18:45:39 +020012499 /* Escape quotes and backslashes */
12500 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012501 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012502 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012503 continue;
12504 }
12505
12506 /* Map special whitespace to '\t', \n', '\r' */
12507 if (ch == '\t') {
12508 PyUnicode_WRITE(okind, odata, o++, '\\');
12509 PyUnicode_WRITE(okind, odata, o++, 't');
12510 }
12511 else if (ch == '\n') {
12512 PyUnicode_WRITE(okind, odata, o++, '\\');
12513 PyUnicode_WRITE(okind, odata, o++, 'n');
12514 }
12515 else if (ch == '\r') {
12516 PyUnicode_WRITE(okind, odata, o++, '\\');
12517 PyUnicode_WRITE(okind, odata, o++, 'r');
12518 }
12519
12520 /* Map non-printable US ASCII to '\xhh' */
12521 else if (ch < ' ' || ch == 0x7F) {
12522 PyUnicode_WRITE(okind, odata, o++, '\\');
12523 PyUnicode_WRITE(okind, odata, o++, 'x');
12524 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12525 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12526 }
12527
12528 /* Copy ASCII characters as-is */
12529 else if (ch < 0x7F) {
12530 PyUnicode_WRITE(okind, odata, o++, ch);
12531 }
12532
12533 /* Non-ASCII characters */
12534 else {
12535 /* Map Unicode whitespace and control characters
12536 (categories Z* and C* except ASCII space)
12537 */
12538 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12539 PyUnicode_WRITE(okind, odata, o++, '\\');
12540 /* Map 8-bit characters to '\xhh' */
12541 if (ch <= 0xff) {
12542 PyUnicode_WRITE(okind, odata, o++, 'x');
12543 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12544 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12545 }
12546 /* Map 16-bit characters to '\uxxxx' */
12547 else if (ch <= 0xffff) {
12548 PyUnicode_WRITE(okind, odata, o++, 'u');
12549 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12550 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12551 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12552 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12553 }
12554 /* Map 21-bit characters to '\U00xxxxxx' */
12555 else {
12556 PyUnicode_WRITE(okind, odata, o++, 'U');
12557 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12558 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12559 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12560 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12561 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12562 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12563 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12564 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12565 }
12566 }
12567 /* Copy characters as-is */
12568 else {
12569 PyUnicode_WRITE(okind, odata, o++, ch);
12570 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012571 }
12572 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012573 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012574 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012575 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012576 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012577}
12578
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012579PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012580 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012581\n\
12582Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012583such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012584arguments start and end are interpreted as in slice notation.\n\
12585\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012586Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012587
12588static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012589unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012590{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012591 /* initialize variables to prevent gcc warning */
12592 PyObject *substring = NULL;
12593 Py_ssize_t start = 0;
12594 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012595 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012596
Jesus Ceaac451502011-04-20 17:09:23 +020012597 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12598 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012599 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012600
Christian Heimesea71a522013-06-29 21:17:34 +020012601 if (PyUnicode_READY(self) == -1) {
12602 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012603 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012604 }
12605 if (PyUnicode_READY(substring) == -1) {
12606 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012607 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012608 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012609
Victor Stinner7931d9a2011-11-04 00:22:48 +010012610 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012611
12612 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012613
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012614 if (result == -2)
12615 return NULL;
12616
Christian Heimes217cfd12007-12-02 14:31:20 +000012617 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012618}
12619
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012620PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012621 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012622\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012623Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012624
12625static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012626unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012627{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012628 /* initialize variables to prevent gcc warning */
12629 PyObject *substring = NULL;
12630 Py_ssize_t start = 0;
12631 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012632 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012633
Jesus Ceaac451502011-04-20 17:09:23 +020012634 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12635 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012636 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012637
Christian Heimesea71a522013-06-29 21:17:34 +020012638 if (PyUnicode_READY(self) == -1) {
12639 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012640 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012641 }
12642 if (PyUnicode_READY(substring) == -1) {
12643 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012644 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012645 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012646
Victor Stinner7931d9a2011-11-04 00:22:48 +010012647 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012648
12649 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012650
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012651 if (result == -2)
12652 return NULL;
12653
Guido van Rossumd57fd912000-03-10 22:53:23 +000012654 if (result < 0) {
12655 PyErr_SetString(PyExc_ValueError, "substring not found");
12656 return NULL;
12657 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012658
Christian Heimes217cfd12007-12-02 14:31:20 +000012659 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012660}
12661
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012662PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012663 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012664\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012665Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012666done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012667
12668static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012669unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012670{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012671 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012672 Py_UCS4 fillchar = ' ';
12673
Victor Stinnere9a29352011-10-01 02:14:59 +020012674 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012675 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012676
Benjamin Petersonbac79492012-01-14 13:34:47 -050012677 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012678 return NULL;
12679
Victor Stinnerc4b49542011-12-11 22:44:26 +010012680 if (PyUnicode_GET_LENGTH(self) >= width)
12681 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012682
Victor Stinnerc4b49542011-12-11 22:44:26 +010012683 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012684}
12685
Alexander Belopolsky40018472011-02-26 01:02:56 +000012686PyObject *
12687PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012688{
12689 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012690
Guido van Rossumd57fd912000-03-10 22:53:23 +000012691 s = PyUnicode_FromObject(s);
12692 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012693 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012694 if (sep != NULL) {
12695 sep = PyUnicode_FromObject(sep);
12696 if (sep == NULL) {
12697 Py_DECREF(s);
12698 return NULL;
12699 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012700 }
12701
Victor Stinner9310abb2011-10-05 00:59:23 +020012702 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012703
12704 Py_DECREF(s);
12705 Py_XDECREF(sep);
12706 return result;
12707}
12708
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012709PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012710 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012711\n\
12712Return a list of the words in S, using sep as the\n\
12713delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012714splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012715whitespace string is a separator and empty strings are\n\
12716removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012717
12718static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012719unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012720{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012721 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012722 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012723 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012724
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012725 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12726 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012727 return NULL;
12728
12729 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012730 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012731 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012732 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012733 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012734 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012735}
12736
Thomas Wouters477c8d52006-05-27 19:21:47 +000012737PyObject *
12738PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12739{
12740 PyObject* str_obj;
12741 PyObject* sep_obj;
12742 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012743 int kind1, kind2;
12744 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012745 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012746
12747 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012748 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012749 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012750 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012751 if (!sep_obj) {
12752 Py_DECREF(str_obj);
12753 return NULL;
12754 }
12755 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12756 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012757 Py_DECREF(str_obj);
12758 return NULL;
12759 }
12760
Victor Stinner14f8f022011-10-05 20:58:25 +020012761 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012762 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012763 len1 = PyUnicode_GET_LENGTH(str_obj);
12764 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012765 if (kind1 < kind2 || len1 < len2) {
12766 _Py_INCREF_UNICODE_EMPTY();
12767 if (!unicode_empty)
12768 out = NULL;
12769 else {
12770 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12771 Py_DECREF(unicode_empty);
12772 }
12773 Py_DECREF(sep_obj);
12774 Py_DECREF(str_obj);
12775 return out;
12776 }
12777 buf1 = PyUnicode_DATA(str_obj);
12778 buf2 = PyUnicode_DATA(sep_obj);
12779 if (kind2 != kind1) {
12780 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12781 if (!buf2)
12782 goto onError;
12783 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012784
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012785 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012786 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012787 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12788 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12789 else
12790 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012791 break;
12792 case PyUnicode_2BYTE_KIND:
12793 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12794 break;
12795 case PyUnicode_4BYTE_KIND:
12796 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12797 break;
12798 default:
12799 assert(0);
12800 out = 0;
12801 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012802
12803 Py_DECREF(sep_obj);
12804 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012805 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012806 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012807
12808 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012809 onError:
12810 Py_DECREF(sep_obj);
12811 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012812 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012813 PyMem_Free(buf2);
12814 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012815}
12816
12817
12818PyObject *
12819PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12820{
12821 PyObject* str_obj;
12822 PyObject* sep_obj;
12823 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012824 int kind1, kind2;
12825 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012826 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012827
12828 str_obj = PyUnicode_FromObject(str_in);
12829 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012830 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012831 sep_obj = PyUnicode_FromObject(sep_in);
12832 if (!sep_obj) {
12833 Py_DECREF(str_obj);
12834 return NULL;
12835 }
12836
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012837 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012838 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012839 len1 = PyUnicode_GET_LENGTH(str_obj);
12840 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012841 if (kind1 < kind2 || len1 < len2) {
12842 _Py_INCREF_UNICODE_EMPTY();
12843 if (!unicode_empty)
12844 out = NULL;
12845 else {
12846 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
12847 Py_DECREF(unicode_empty);
12848 }
12849 Py_DECREF(sep_obj);
12850 Py_DECREF(str_obj);
12851 return out;
12852 }
12853 buf1 = PyUnicode_DATA(str_obj);
12854 buf2 = PyUnicode_DATA(sep_obj);
12855 if (kind2 != kind1) {
12856 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12857 if (!buf2)
12858 goto onError;
12859 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012860
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012861 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012862 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012863 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12864 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12865 else
12866 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012867 break;
12868 case PyUnicode_2BYTE_KIND:
12869 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12870 break;
12871 case PyUnicode_4BYTE_KIND:
12872 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12873 break;
12874 default:
12875 assert(0);
12876 out = 0;
12877 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012878
12879 Py_DECREF(sep_obj);
12880 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012881 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012882 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012883
12884 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012885 onError:
12886 Py_DECREF(sep_obj);
12887 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012888 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012889 PyMem_Free(buf2);
12890 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012891}
12892
12893PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012894 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012895\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012896Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012897the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012898found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012899
12900static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012901unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012902{
Victor Stinner9310abb2011-10-05 00:59:23 +020012903 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012904}
12905
12906PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012907 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012908\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012909Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012910the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012911separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012912
12913static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012914unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012915{
Victor Stinner9310abb2011-10-05 00:59:23 +020012916 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012917}
12918
Alexander Belopolsky40018472011-02-26 01:02:56 +000012919PyObject *
12920PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012921{
12922 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012923
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012924 s = PyUnicode_FromObject(s);
12925 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012926 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012927 if (sep != NULL) {
12928 sep = PyUnicode_FromObject(sep);
12929 if (sep == NULL) {
12930 Py_DECREF(s);
12931 return NULL;
12932 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012933 }
12934
Victor Stinner9310abb2011-10-05 00:59:23 +020012935 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012936
12937 Py_DECREF(s);
12938 Py_XDECREF(sep);
12939 return result;
12940}
12941
12942PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012943 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012944\n\
12945Return a list of the words in S, using sep as the\n\
12946delimiter string, starting at the end of the string and\n\
12947working to the front. If maxsplit is given, at most maxsplit\n\
12948splits are done. If sep is not specified, any whitespace string\n\
12949is a separator.");
12950
12951static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012952unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012953{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012954 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012955 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012956 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012957
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012958 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12959 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012960 return NULL;
12961
12962 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012963 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012964 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012965 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012966 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012967 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012968}
12969
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012970PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012971 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012972\n\
12973Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012974Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012975is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012976
12977static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012978unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012979{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012980 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012981 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012982
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012983 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12984 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012985 return NULL;
12986
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012987 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012988}
12989
12990static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012991PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012992{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012993 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012994}
12995
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012996PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012997 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012998\n\
12999Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013000and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013001
13002static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013003unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013004{
Benjamin Petersoneea48462012-01-16 14:28:50 -050013005 if (PyUnicode_READY(self) == -1)
13006 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013007 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013008}
13009
Larry Hastings61272b72014-01-07 12:41:53 -080013010/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000013011
Larry Hastings31826802013-10-19 00:09:25 -070013012@staticmethod
13013str.maketrans as unicode_maketrans
13014
13015 x: object
13016
13017 y: unicode=NULL
13018
13019 z: unicode=NULL
13020
13021 /
13022
13023Return a translation table usable for str.translate().
13024
13025If there is only one argument, it must be a dictionary mapping Unicode
13026ordinals (integers) or characters to Unicode ordinals, strings or None.
13027Character keys will be then converted to ordinals.
13028If there are two arguments, they must be strings of equal length, and
13029in the resulting dictionary, each character in x will be mapped to the
13030character at the same position in y. If there is a third argument, it
13031must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080013032[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070013033
Larry Hastings31826802013-10-19 00:09:25 -070013034static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080013035unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030013036/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070013037{
Georg Brandlceee0772007-11-27 23:48:05 +000013038 PyObject *new = NULL, *key, *value;
13039 Py_ssize_t i = 0;
13040 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013041
Georg Brandlceee0772007-11-27 23:48:05 +000013042 new = PyDict_New();
13043 if (!new)
13044 return NULL;
13045 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013046 int x_kind, y_kind, z_kind;
13047 void *x_data, *y_data, *z_data;
13048
Georg Brandlceee0772007-11-27 23:48:05 +000013049 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000013050 if (!PyUnicode_Check(x)) {
13051 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13052 "be a string if there is a second argument");
13053 goto err;
13054 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013055 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013056 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13057 "arguments must have equal length");
13058 goto err;
13059 }
13060 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013061 x_kind = PyUnicode_KIND(x);
13062 y_kind = PyUnicode_KIND(y);
13063 x_data = PyUnicode_DATA(x);
13064 y_data = PyUnicode_DATA(y);
13065 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13066 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013067 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013068 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013069 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013070 if (!value) {
13071 Py_DECREF(key);
13072 goto err;
13073 }
Georg Brandlceee0772007-11-27 23:48:05 +000013074 res = PyDict_SetItem(new, key, value);
13075 Py_DECREF(key);
13076 Py_DECREF(value);
13077 if (res < 0)
13078 goto err;
13079 }
13080 /* create entries for deleting chars in z */
13081 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013082 z_kind = PyUnicode_KIND(z);
13083 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013084 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013085 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013086 if (!key)
13087 goto err;
13088 res = PyDict_SetItem(new, key, Py_None);
13089 Py_DECREF(key);
13090 if (res < 0)
13091 goto err;
13092 }
13093 }
13094 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013095 int kind;
13096 void *data;
13097
Georg Brandlceee0772007-11-27 23:48:05 +000013098 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013099 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013100 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13101 "to maketrans it must be a dict");
13102 goto err;
13103 }
13104 /* copy entries into the new dict, converting string keys to int keys */
13105 while (PyDict_Next(x, &i, &key, &value)) {
13106 if (PyUnicode_Check(key)) {
13107 /* convert string keys to integer keys */
13108 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013109 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013110 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13111 "table must be of length 1");
13112 goto err;
13113 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013114 kind = PyUnicode_KIND(key);
13115 data = PyUnicode_DATA(key);
13116 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013117 if (!newkey)
13118 goto err;
13119 res = PyDict_SetItem(new, newkey, value);
13120 Py_DECREF(newkey);
13121 if (res < 0)
13122 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013123 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013124 /* just keep integer keys */
13125 if (PyDict_SetItem(new, key, value) < 0)
13126 goto err;
13127 } else {
13128 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13129 "be strings or integers");
13130 goto err;
13131 }
13132 }
13133 }
13134 return new;
13135 err:
13136 Py_DECREF(new);
13137 return NULL;
13138}
13139
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013140PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013141 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013142\n\
Zachary Ware79b98df2015-08-05 23:54:15 -050013143Return a copy of the string S in which each character has been mapped\n\
13144through the given translation table. The table must implement\n\
13145lookup/indexing via __getitem__, for instance a dictionary or list,\n\
13146mapping Unicode ordinals to Unicode ordinals, strings, or None. If\n\
13147this operation raises LookupError, the character is left untouched.\n\
13148Characters mapped to None are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013149
13150static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013151unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013152{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013153 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013154}
13155
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013156PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013157 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013158\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013159Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013160
13161static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013162unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013163{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013164 if (PyUnicode_READY(self) == -1)
13165 return NULL;
13166 if (PyUnicode_IS_ASCII(self))
13167 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013168 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013169}
13170
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013171PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013172 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013173\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000013174Pad a numeric string S with zeros on the left, to fill a field\n\
13175of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013176
13177static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020013178unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013179{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013180 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013181 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013182 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013183 int kind;
13184 void *data;
13185 Py_UCS4 chr;
13186
Martin v. Löwis18e16552006-02-15 17:27:45 +000013187 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013188 return NULL;
13189
Benjamin Petersonbac79492012-01-14 13:34:47 -050013190 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013191 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013192
Victor Stinnerc4b49542011-12-11 22:44:26 +010013193 if (PyUnicode_GET_LENGTH(self) >= width)
13194 return unicode_result_unchanged(self);
13195
13196 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013197
13198 u = pad(self, fill, 0, '0');
13199
Walter Dörwald068325e2002-04-15 13:36:47 +000013200 if (u == NULL)
13201 return NULL;
13202
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013203 kind = PyUnicode_KIND(u);
13204 data = PyUnicode_DATA(u);
13205 chr = PyUnicode_READ(kind, data, fill);
13206
13207 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013208 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013209 PyUnicode_WRITE(kind, data, 0, chr);
13210 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013211 }
13212
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013213 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013214 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013215}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013216
13217#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013218static PyObject *
13219unicode__decimal2ascii(PyObject *self)
13220{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013221 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013222}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013223#endif
13224
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013225PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013226 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013227\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013228Return True if S starts with the specified prefix, False otherwise.\n\
13229With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013230With optional end, stop comparing S at that position.\n\
13231prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013232
13233static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013234unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013235 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013236{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013237 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013238 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013239 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013240 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013241 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013242
Jesus Ceaac451502011-04-20 17:09:23 +020013243 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013244 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013245 if (PyTuple_Check(subobj)) {
13246 Py_ssize_t i;
13247 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013248 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013249 if (substring == NULL)
13250 return NULL;
13251 result = tailmatch(self, substring, start, end, -1);
13252 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013253 if (result == -1)
13254 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013255 if (result) {
13256 Py_RETURN_TRUE;
13257 }
13258 }
13259 /* nothing matched */
13260 Py_RETURN_FALSE;
13261 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013262 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013263 if (substring == NULL) {
13264 if (PyErr_ExceptionMatches(PyExc_TypeError))
13265 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
13266 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013267 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013268 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013269 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013270 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013271 if (result == -1)
13272 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013273 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013274}
13275
13276
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013277PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013278 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013279\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013280Return True if S ends with the specified suffix, False otherwise.\n\
13281With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013282With optional end, stop comparing S at that position.\n\
13283suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013284
13285static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013286unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013287 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013288{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013289 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013290 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013291 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013292 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013293 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013294
Jesus Ceaac451502011-04-20 17:09:23 +020013295 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013296 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013297 if (PyTuple_Check(subobj)) {
13298 Py_ssize_t i;
13299 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013300 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000013301 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013302 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013303 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013304 result = tailmatch(self, substring, start, end, +1);
13305 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013306 if (result == -1)
13307 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013308 if (result) {
13309 Py_RETURN_TRUE;
13310 }
13311 }
13312 Py_RETURN_FALSE;
13313 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013314 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013315 if (substring == NULL) {
13316 if (PyErr_ExceptionMatches(PyExc_TypeError))
13317 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
13318 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013319 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013320 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013321 result = tailmatch(self, substring, start, end, +1);
Christian Heimes305e49e2013-06-29 20:41:06 +020013322 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013323 if (result == -1)
13324 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013325 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013326}
13327
Victor Stinner202fdca2012-05-07 12:47:02 +020013328Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013329_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013330{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013331 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13332 writer->data = PyUnicode_DATA(writer->buffer);
13333
13334 if (!writer->readonly) {
13335 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013336 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013337 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013338 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013339 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13340 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13341 writer->kind = PyUnicode_WCHAR_KIND;
13342 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13343
Victor Stinner8f674cc2013-04-17 23:02:17 +020013344 /* Copy-on-write mode: set buffer size to 0 so
13345 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13346 * next write. */
13347 writer->size = 0;
13348 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013349}
13350
Victor Stinnerd3f08822012-05-29 12:57:52 +020013351void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013352_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013353{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013354 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013355
13356 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013357 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013358
13359 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13360 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13361 writer->kind = PyUnicode_WCHAR_KIND;
13362 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013363}
13364
Victor Stinnerd3f08822012-05-29 12:57:52 +020013365int
13366_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13367 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013368{
Victor Stinner6989ba02013-11-18 21:08:39 +010013369#ifdef MS_WINDOWS
13370 /* On Windows, overallocate by 50% is the best factor */
13371# define OVERALLOCATE_FACTOR 2
13372#else
13373 /* On Linux, overallocate by 25% is the best factor */
13374# define OVERALLOCATE_FACTOR 4
13375#endif
Victor Stinner202fdca2012-05-07 12:47:02 +020013376 Py_ssize_t newlen;
13377 PyObject *newbuffer;
13378
Victor Stinnerca9381e2015-09-22 00:58:32 +020013379 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013380 assert((maxchar > writer->maxchar && length >= 0)
13381 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013382
Victor Stinner202fdca2012-05-07 12:47:02 +020013383 if (length > PY_SSIZE_T_MAX - writer->pos) {
13384 PyErr_NoMemory();
13385 return -1;
13386 }
13387 newlen = writer->pos + length;
13388
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013389 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013390
Victor Stinnerd3f08822012-05-29 12:57:52 +020013391 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013392 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013393 if (writer->overallocate
13394 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13395 /* overallocate to limit the number of realloc() */
13396 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013397 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013398 if (newlen < writer->min_length)
13399 newlen = writer->min_length;
13400
Victor Stinnerd3f08822012-05-29 12:57:52 +020013401 writer->buffer = PyUnicode_New(newlen, maxchar);
13402 if (writer->buffer == NULL)
13403 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013404 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013405 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013406 if (writer->overallocate
13407 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13408 /* overallocate to limit the number of realloc() */
13409 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013410 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013411 if (newlen < writer->min_length)
13412 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013413
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013414 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013415 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013416 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013417 newbuffer = PyUnicode_New(newlen, maxchar);
13418 if (newbuffer == NULL)
13419 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013420 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13421 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013422 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013423 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013424 }
13425 else {
13426 newbuffer = resize_compact(writer->buffer, newlen);
13427 if (newbuffer == NULL)
13428 return -1;
13429 }
13430 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013431 }
13432 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013433 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013434 newbuffer = PyUnicode_New(writer->size, maxchar);
13435 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013436 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013437 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13438 writer->buffer, 0, writer->pos);
13439 Py_DECREF(writer->buffer);
13440 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013441 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013442 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013443 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013444
13445#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013446}
13447
Victor Stinnerca9381e2015-09-22 00:58:32 +020013448int
13449_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13450 enum PyUnicode_Kind kind)
13451{
13452 Py_UCS4 maxchar;
13453
13454 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13455 assert(writer->kind < kind);
13456
13457 switch (kind)
13458 {
13459 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13460 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13461 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13462 default:
13463 assert(0 && "invalid kind");
13464 return -1;
13465 }
13466
13467 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13468}
13469
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013470Py_LOCAL_INLINE(int)
13471_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013472{
13473 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13474 return -1;
13475 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13476 writer->pos++;
13477 return 0;
13478}
13479
13480int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013481_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13482{
13483 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13484}
13485
13486int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013487_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13488{
13489 Py_UCS4 maxchar;
13490 Py_ssize_t len;
13491
13492 if (PyUnicode_READY(str) == -1)
13493 return -1;
13494 len = PyUnicode_GET_LENGTH(str);
13495 if (len == 0)
13496 return 0;
13497 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13498 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013499 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013500 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013501 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013502 Py_INCREF(str);
13503 writer->buffer = str;
13504 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013505 writer->pos += len;
13506 return 0;
13507 }
13508 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13509 return -1;
13510 }
13511 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13512 str, 0, len);
13513 writer->pos += len;
13514 return 0;
13515}
13516
Victor Stinnere215d962012-10-06 23:03:36 +020013517int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013518_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13519 Py_ssize_t start, Py_ssize_t end)
13520{
13521 Py_UCS4 maxchar;
13522 Py_ssize_t len;
13523
13524 if (PyUnicode_READY(str) == -1)
13525 return -1;
13526
13527 assert(0 <= start);
13528 assert(end <= PyUnicode_GET_LENGTH(str));
13529 assert(start <= end);
13530
13531 if (end == 0)
13532 return 0;
13533
13534 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13535 return _PyUnicodeWriter_WriteStr(writer, str);
13536
13537 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13538 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13539 else
13540 maxchar = writer->maxchar;
13541 len = end - start;
13542
13543 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13544 return -1;
13545
13546 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13547 str, start, len);
13548 writer->pos += len;
13549 return 0;
13550}
13551
13552int
Victor Stinner4a587072013-11-19 12:54:53 +010013553_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13554 const char *ascii, Py_ssize_t len)
13555{
13556 if (len == -1)
13557 len = strlen(ascii);
13558
13559 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13560
13561 if (writer->buffer == NULL && !writer->overallocate) {
13562 PyObject *str;
13563
13564 str = _PyUnicode_FromASCII(ascii, len);
13565 if (str == NULL)
13566 return -1;
13567
13568 writer->readonly = 1;
13569 writer->buffer = str;
13570 _PyUnicodeWriter_Update(writer);
13571 writer->pos += len;
13572 return 0;
13573 }
13574
13575 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13576 return -1;
13577
13578 switch (writer->kind)
13579 {
13580 case PyUnicode_1BYTE_KIND:
13581 {
13582 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13583 Py_UCS1 *data = writer->data;
13584
13585 Py_MEMCPY(data + writer->pos, str, len);
13586 break;
13587 }
13588 case PyUnicode_2BYTE_KIND:
13589 {
13590 _PyUnicode_CONVERT_BYTES(
13591 Py_UCS1, Py_UCS2,
13592 ascii, ascii + len,
13593 (Py_UCS2 *)writer->data + writer->pos);
13594 break;
13595 }
13596 case PyUnicode_4BYTE_KIND:
13597 {
13598 _PyUnicode_CONVERT_BYTES(
13599 Py_UCS1, Py_UCS4,
13600 ascii, ascii + len,
13601 (Py_UCS4 *)writer->data + writer->pos);
13602 break;
13603 }
13604 default:
13605 assert(0);
13606 }
13607
13608 writer->pos += len;
13609 return 0;
13610}
13611
13612int
13613_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13614 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013615{
13616 Py_UCS4 maxchar;
13617
13618 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13619 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13620 return -1;
13621 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13622 writer->pos += len;
13623 return 0;
13624}
13625
Victor Stinnerd3f08822012-05-29 12:57:52 +020013626PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013627_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013628{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013629 PyObject *str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013630 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013631 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013632 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013633 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013634 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013635 str = writer->buffer;
13636 writer->buffer = NULL;
13637 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13638 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013639 }
13640 if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
13641 PyObject *newbuffer;
13642 newbuffer = resize_compact(writer->buffer, writer->pos);
13643 if (newbuffer == NULL) {
Serhiy Storchakadfe98a12014-02-09 13:46:20 +020013644 Py_CLEAR(writer->buffer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013645 return NULL;
13646 }
13647 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013648 }
Victor Stinner15a0bd32013-07-08 22:29:55 +020013649 str = writer->buffer;
13650 writer->buffer = NULL;
13651 assert(_PyUnicode_CheckConsistency(str, 1));
13652 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013653}
13654
Victor Stinnerd3f08822012-05-29 12:57:52 +020013655void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013656_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013657{
13658 Py_CLEAR(writer->buffer);
13659}
13660
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013661#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013662
13663PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013664 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013665\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013666Return a formatted version of S, using substitutions from args and kwargs.\n\
13667The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013668
Eric Smith27bbca62010-11-04 17:06:58 +000013669PyDoc_STRVAR(format_map__doc__,
13670 "S.format_map(mapping) -> str\n\
13671\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013672Return a formatted version of S, using substitutions from mapping.\n\
13673The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013674
Eric Smith4a7d76d2008-05-30 18:10:19 +000013675static PyObject *
13676unicode__format__(PyObject* self, PyObject* args)
13677{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013678 PyObject *format_spec;
13679 _PyUnicodeWriter writer;
13680 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013681
13682 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13683 return NULL;
13684
Victor Stinnerd3f08822012-05-29 12:57:52 +020013685 if (PyUnicode_READY(self) == -1)
13686 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013687 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013688 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13689 self, format_spec, 0,
13690 PyUnicode_GET_LENGTH(format_spec));
13691 if (ret == -1) {
13692 _PyUnicodeWriter_Dealloc(&writer);
13693 return NULL;
13694 }
13695 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013696}
13697
Eric Smith8c663262007-08-25 02:26:07 +000013698PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013699 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013700\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013701Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013702
13703static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013704unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013705{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013706 Py_ssize_t size;
13707
13708 /* If it's a compact object, account for base structure +
13709 character data. */
13710 if (PyUnicode_IS_COMPACT_ASCII(v))
13711 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13712 else if (PyUnicode_IS_COMPACT(v))
13713 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013714 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013715 else {
13716 /* If it is a two-block object, account for base object, and
13717 for character block if present. */
13718 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013719 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013720 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013721 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013722 }
13723 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013724 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013725 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013726 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013727 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013728 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013729
13730 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013731}
13732
13733PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013734 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013735
13736static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013737unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013738{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013739 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013740 if (!copy)
13741 return NULL;
13742 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013743}
13744
Guido van Rossumd57fd912000-03-10 22:53:23 +000013745static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013746 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013747 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013748 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13749 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013750 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13751 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013752 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013753 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13754 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13755 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013756 {"expandtabs", (PyCFunction) unicode_expandtabs,
13757 METH_VARARGS | METH_KEYWORDS, expandtabs__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013758 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013759 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013760 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13761 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13762 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013763 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013764 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13765 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13766 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013767 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013768 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013769 {"splitlines", (PyCFunction) unicode_splitlines,
13770 METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013771 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013772 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13773 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13774 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13775 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13776 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13777 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13778 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13779 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13780 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13781 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13782 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13783 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13784 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13785 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013786 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013787 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013788 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013789 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013790 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013791 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013792 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013793 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013794#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013795 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013796 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013797#endif
13798
Benjamin Peterson14339b62009-01-31 16:36:08 +000013799 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013800 {NULL, NULL}
13801};
13802
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013803static PyObject *
13804unicode_mod(PyObject *v, PyObject *w)
13805{
Brian Curtindfc80e32011-08-10 20:28:54 -050013806 if (!PyUnicode_Check(v))
13807 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013808 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013809}
13810
13811static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013812 0, /*nb_add*/
13813 0, /*nb_subtract*/
13814 0, /*nb_multiply*/
13815 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013816};
13817
Guido van Rossumd57fd912000-03-10 22:53:23 +000013818static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013819 (lenfunc) unicode_length, /* sq_length */
13820 PyUnicode_Concat, /* sq_concat */
13821 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13822 (ssizeargfunc) unicode_getitem, /* sq_item */
13823 0, /* sq_slice */
13824 0, /* sq_ass_item */
13825 0, /* sq_ass_slice */
13826 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013827};
13828
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013829static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013830unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013831{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013832 if (PyUnicode_READY(self) == -1)
13833 return NULL;
13834
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013835 if (PyIndex_Check(item)) {
13836 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013837 if (i == -1 && PyErr_Occurred())
13838 return NULL;
13839 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013840 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013841 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013842 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013843 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013844 PyObject *result;
13845 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013846 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013847 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013848
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013849 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013850 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013851 return NULL;
13852 }
13853
13854 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013855 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013856 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013857 slicelength == PyUnicode_GET_LENGTH(self)) {
13858 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013859 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013860 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013861 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013862 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013863 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013864 src_kind = PyUnicode_KIND(self);
13865 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013866 if (!PyUnicode_IS_ASCII(self)) {
13867 kind_limit = kind_maxchar_limit(src_kind);
13868 max_char = 0;
13869 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13870 ch = PyUnicode_READ(src_kind, src_data, cur);
13871 if (ch > max_char) {
13872 max_char = ch;
13873 if (max_char >= kind_limit)
13874 break;
13875 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013876 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013877 }
Victor Stinner55c99112011-10-13 01:17:06 +020013878 else
13879 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013880 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013881 if (result == NULL)
13882 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013883 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013884 dest_data = PyUnicode_DATA(result);
13885
13886 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013887 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13888 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013889 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013890 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013891 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013892 } else {
13893 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13894 return NULL;
13895 }
13896}
13897
13898static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013899 (lenfunc)unicode_length, /* mp_length */
13900 (binaryfunc)unicode_subscript, /* mp_subscript */
13901 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013902};
13903
Guido van Rossumd57fd912000-03-10 22:53:23 +000013904
Guido van Rossumd57fd912000-03-10 22:53:23 +000013905/* Helpers for PyUnicode_Format() */
13906
Victor Stinnera47082312012-10-04 02:19:54 +020013907struct unicode_formatter_t {
13908 PyObject *args;
13909 int args_owned;
13910 Py_ssize_t arglen, argidx;
13911 PyObject *dict;
13912
13913 enum PyUnicode_Kind fmtkind;
13914 Py_ssize_t fmtcnt, fmtpos;
13915 void *fmtdata;
13916 PyObject *fmtstr;
13917
13918 _PyUnicodeWriter writer;
13919};
13920
13921struct unicode_format_arg_t {
13922 Py_UCS4 ch;
13923 int flags;
13924 Py_ssize_t width;
13925 int prec;
13926 int sign;
13927};
13928
Guido van Rossumd57fd912000-03-10 22:53:23 +000013929static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013930unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013931{
Victor Stinnera47082312012-10-04 02:19:54 +020013932 Py_ssize_t argidx = ctx->argidx;
13933
13934 if (argidx < ctx->arglen) {
13935 ctx->argidx++;
13936 if (ctx->arglen < 0)
13937 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013938 else
Victor Stinnera47082312012-10-04 02:19:54 +020013939 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013940 }
13941 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013942 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013943 return NULL;
13944}
13945
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013946/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013947
Victor Stinnera47082312012-10-04 02:19:54 +020013948/* Format a float into the writer if the writer is not NULL, or into *p_output
13949 otherwise.
13950
13951 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020013952static int
Victor Stinnera47082312012-10-04 02:19:54 +020013953formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
13954 PyObject **p_output,
13955 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013956{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013957 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013958 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013959 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020013960 int prec;
13961 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000013962
Guido van Rossumd57fd912000-03-10 22:53:23 +000013963 x = PyFloat_AsDouble(v);
13964 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013965 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013966
Victor Stinnera47082312012-10-04 02:19:54 +020013967 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013968 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013969 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013970
Victor Stinnera47082312012-10-04 02:19:54 +020013971 if (arg->flags & F_ALT)
13972 dtoa_flags = Py_DTSF_ALT;
13973 else
13974 dtoa_flags = 0;
13975 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013976 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013977 return -1;
13978 len = strlen(p);
13979 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010013980 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013981 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013982 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013983 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013984 }
13985 else
13986 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013987 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013988 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013989}
13990
Victor Stinnerd0880d52012-04-27 23:40:13 +020013991/* formatlong() emulates the format codes d, u, o, x and X, and
13992 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13993 * Python's regular ints.
13994 * Return value: a new PyUnicodeObject*, or NULL if error.
13995 * The output string is of the form
13996 * "-"? ("0x" | "0X")? digit+
13997 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13998 * set in flags. The case of hex digits will be correct,
13999 * There will be at least prec digits, zero-filled on the left if
14000 * necessary to get that many.
14001 * val object to be converted
14002 * flags bitmask of format flags; only F_ALT is looked at
14003 * prec minimum number of digits; 0-fill on left if needed
14004 * type a character in [duoxX]; u acts the same as d
14005 *
14006 * CAUTION: o, x and X conversions on regular ints can never
14007 * produce a '-' sign, but can for Python's unbounded ints.
14008 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014009PyObject *
14010_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000014011{
Victor Stinnerd0880d52012-04-27 23:40:13 +020014012 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014013 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014014 Py_ssize_t i;
14015 int sign; /* 1 if '-', else 0 */
14016 int len; /* number of characters */
14017 Py_ssize_t llen;
14018 int numdigits; /* len == numnondigits + numdigits */
14019 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000014020
Victor Stinnerd0880d52012-04-27 23:40:13 +020014021 /* Avoid exceeding SSIZE_T_MAX */
14022 if (prec > INT_MAX-3) {
14023 PyErr_SetString(PyExc_OverflowError,
14024 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000014025 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014026 }
14027
14028 assert(PyLong_Check(val));
14029
14030 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020014031 default:
14032 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014033 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020014034 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020014035 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070014036 /* int and int subclasses should print numerically when a numeric */
14037 /* format code is used (see issue18780) */
14038 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014039 break;
14040 case 'o':
14041 numnondigits = 2;
14042 result = PyNumber_ToBase(val, 8);
14043 break;
14044 case 'x':
14045 case 'X':
14046 numnondigits = 2;
14047 result = PyNumber_ToBase(val, 16);
14048 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014049 }
14050 if (!result)
14051 return NULL;
14052
14053 assert(unicode_modifiable(result));
14054 assert(PyUnicode_IS_READY(result));
14055 assert(PyUnicode_IS_ASCII(result));
14056
14057 /* To modify the string in-place, there can only be one reference. */
14058 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014059 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014060 PyErr_BadInternalCall();
14061 return NULL;
14062 }
14063 buf = PyUnicode_DATA(result);
14064 llen = PyUnicode_GET_LENGTH(result);
14065 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014066 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014067 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080014068 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014069 return NULL;
14070 }
14071 len = (int)llen;
14072 sign = buf[0] == '-';
14073 numnondigits += sign;
14074 numdigits = len - numnondigits;
14075 assert(numdigits > 0);
14076
14077 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014078 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014079 (type == 'o' || type == 'x' || type == 'X'))) {
14080 assert(buf[sign] == '0');
14081 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14082 buf[sign+1] == 'o');
14083 numnondigits -= 2;
14084 buf += 2;
14085 len -= 2;
14086 if (sign)
14087 buf[0] = '-';
14088 assert(len == numnondigits + numdigits);
14089 assert(numdigits > 0);
14090 }
14091
14092 /* Fill with leading zeroes to meet minimum width. */
14093 if (prec > numdigits) {
14094 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14095 numnondigits + prec);
14096 char *b1;
14097 if (!r1) {
14098 Py_DECREF(result);
14099 return NULL;
14100 }
14101 b1 = PyBytes_AS_STRING(r1);
14102 for (i = 0; i < numnondigits; ++i)
14103 *b1++ = *buf++;
14104 for (i = 0; i < prec - numdigits; i++)
14105 *b1++ = '0';
14106 for (i = 0; i < numdigits; i++)
14107 *b1++ = *buf++;
14108 *b1 = '\0';
14109 Py_DECREF(result);
14110 result = r1;
14111 buf = PyBytes_AS_STRING(result);
14112 len = numnondigits + prec;
14113 }
14114
14115 /* Fix up case for hex conversions. */
14116 if (type == 'X') {
14117 /* Need to convert all lower case letters to upper case.
14118 and need to convert 0x to 0X (and -0x to -0X). */
14119 for (i = 0; i < len; i++)
14120 if (buf[i] >= 'a' && buf[i] <= 'x')
14121 buf[i] -= 'a'-'A';
14122 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014123 if (!PyUnicode_Check(result)
14124 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014125 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014126 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014127 Py_DECREF(result);
14128 result = unicode;
14129 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014130 else if (len != PyUnicode_GET_LENGTH(result)) {
14131 if (PyUnicode_Resize(&result, len) < 0)
14132 Py_CLEAR(result);
14133 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014134 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014135}
14136
Ethan Furmandf3ed242014-01-05 06:50:30 -080014137/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014138 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014139 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014140 * -1 and raise an exception on error */
14141static int
Victor Stinnera47082312012-10-04 02:19:54 +020014142mainformatlong(PyObject *v,
14143 struct unicode_format_arg_t *arg,
14144 PyObject **p_output,
14145 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014146{
14147 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014148 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014149
14150 if (!PyNumber_Check(v))
14151 goto wrongtype;
14152
Ethan Furman9ab74802014-03-21 06:38:46 -070014153 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014154 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014155 if (type == 'o' || type == 'x' || type == 'X') {
14156 iobj = PyNumber_Index(v);
14157 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014158 if (PyErr_ExceptionMatches(PyExc_TypeError))
14159 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014160 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014161 }
14162 }
14163 else {
14164 iobj = PyNumber_Long(v);
14165 if (iobj == NULL ) {
14166 if (PyErr_ExceptionMatches(PyExc_TypeError))
14167 goto wrongtype;
14168 return -1;
14169 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014170 }
14171 assert(PyLong_Check(iobj));
14172 }
14173 else {
14174 iobj = v;
14175 Py_INCREF(iobj);
14176 }
14177
14178 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014179 && arg->width == -1 && arg->prec == -1
14180 && !(arg->flags & (F_SIGN | F_BLANK))
14181 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014182 {
14183 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014184 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014185 int base;
14186
Victor Stinnera47082312012-10-04 02:19:54 +020014187 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014188 {
14189 default:
14190 assert(0 && "'type' not in [diuoxX]");
14191 case 'd':
14192 case 'i':
14193 case 'u':
14194 base = 10;
14195 break;
14196 case 'o':
14197 base = 8;
14198 break;
14199 case 'x':
14200 case 'X':
14201 base = 16;
14202 break;
14203 }
14204
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014205 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14206 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014207 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014208 }
14209 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014210 return 1;
14211 }
14212
Ethan Furmanb95b5612015-01-23 20:05:18 -080014213 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014214 Py_DECREF(iobj);
14215 if (res == NULL)
14216 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014217 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014218 return 0;
14219
14220wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014221 switch(type)
14222 {
14223 case 'o':
14224 case 'x':
14225 case 'X':
14226 PyErr_Format(PyExc_TypeError,
14227 "%%%c format: an integer is required, "
14228 "not %.200s",
14229 type, Py_TYPE(v)->tp_name);
14230 break;
14231 default:
14232 PyErr_Format(PyExc_TypeError,
14233 "%%%c format: a number is required, "
14234 "not %.200s",
14235 type, Py_TYPE(v)->tp_name);
14236 break;
14237 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014238 return -1;
14239}
14240
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014241static Py_UCS4
14242formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014243{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014244 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014245 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014246 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014247 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014248 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014249 goto onError;
14250 }
14251 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014252 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014253 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014254 /* make sure number is a type of integer */
14255 if (!PyLong_Check(v)) {
14256 iobj = PyNumber_Index(v);
14257 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014258 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014259 }
14260 v = iobj;
14261 Py_DECREF(iobj);
14262 }
14263 /* Integer input truncated to a character */
Benjamin Peterson29060642009-01-31 22:14:21 +000014264 x = PyLong_AsLong(v);
14265 if (x == -1 && PyErr_Occurred())
14266 goto onError;
14267
Victor Stinner8faf8212011-12-08 22:14:11 +010014268 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014269 PyErr_SetString(PyExc_OverflowError,
14270 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014271 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014272 }
14273
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014274 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014275 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014276
Benjamin Peterson29060642009-01-31 22:14:21 +000014277 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014278 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014279 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014280 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014281}
14282
Victor Stinnera47082312012-10-04 02:19:54 +020014283/* Parse options of an argument: flags, width, precision.
14284 Handle also "%(name)" syntax.
14285
14286 Return 0 if the argument has been formatted into arg->str.
14287 Return 1 if the argument has been written into ctx->writer,
14288 Raise an exception and return -1 on error. */
14289static int
14290unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14291 struct unicode_format_arg_t *arg)
14292{
14293#define FORMAT_READ(ctx) \
14294 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14295
14296 PyObject *v;
14297
Victor Stinnera47082312012-10-04 02:19:54 +020014298 if (arg->ch == '(') {
14299 /* Get argument value from a dictionary. Example: "%(name)s". */
14300 Py_ssize_t keystart;
14301 Py_ssize_t keylen;
14302 PyObject *key;
14303 int pcount = 1;
14304
14305 if (ctx->dict == NULL) {
14306 PyErr_SetString(PyExc_TypeError,
14307 "format requires a mapping");
14308 return -1;
14309 }
14310 ++ctx->fmtpos;
14311 --ctx->fmtcnt;
14312 keystart = ctx->fmtpos;
14313 /* Skip over balanced parentheses */
14314 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14315 arg->ch = FORMAT_READ(ctx);
14316 if (arg->ch == ')')
14317 --pcount;
14318 else if (arg->ch == '(')
14319 ++pcount;
14320 ctx->fmtpos++;
14321 }
14322 keylen = ctx->fmtpos - keystart - 1;
14323 if (ctx->fmtcnt < 0 || pcount > 0) {
14324 PyErr_SetString(PyExc_ValueError,
14325 "incomplete format key");
14326 return -1;
14327 }
14328 key = PyUnicode_Substring(ctx->fmtstr,
14329 keystart, keystart + keylen);
14330 if (key == NULL)
14331 return -1;
14332 if (ctx->args_owned) {
14333 Py_DECREF(ctx->args);
14334 ctx->args_owned = 0;
14335 }
14336 ctx->args = PyObject_GetItem(ctx->dict, key);
14337 Py_DECREF(key);
14338 if (ctx->args == NULL)
14339 return -1;
14340 ctx->args_owned = 1;
14341 ctx->arglen = -1;
14342 ctx->argidx = -2;
14343 }
14344
14345 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014346 while (--ctx->fmtcnt >= 0) {
14347 arg->ch = FORMAT_READ(ctx);
14348 ctx->fmtpos++;
14349 switch (arg->ch) {
14350 case '-': arg->flags |= F_LJUST; continue;
14351 case '+': arg->flags |= F_SIGN; continue;
14352 case ' ': arg->flags |= F_BLANK; continue;
14353 case '#': arg->flags |= F_ALT; continue;
14354 case '0': arg->flags |= F_ZERO; continue;
14355 }
14356 break;
14357 }
14358
14359 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014360 if (arg->ch == '*') {
14361 v = unicode_format_getnextarg(ctx);
14362 if (v == NULL)
14363 return -1;
14364 if (!PyLong_Check(v)) {
14365 PyErr_SetString(PyExc_TypeError,
14366 "* wants int");
14367 return -1;
14368 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014369 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014370 if (arg->width == -1 && PyErr_Occurred())
14371 return -1;
14372 if (arg->width < 0) {
14373 arg->flags |= F_LJUST;
14374 arg->width = -arg->width;
14375 }
14376 if (--ctx->fmtcnt >= 0) {
14377 arg->ch = FORMAT_READ(ctx);
14378 ctx->fmtpos++;
14379 }
14380 }
14381 else if (arg->ch >= '0' && arg->ch <= '9') {
14382 arg->width = arg->ch - '0';
14383 while (--ctx->fmtcnt >= 0) {
14384 arg->ch = FORMAT_READ(ctx);
14385 ctx->fmtpos++;
14386 if (arg->ch < '0' || arg->ch > '9')
14387 break;
14388 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14389 mixing signed and unsigned comparison. Since arg->ch is between
14390 '0' and '9', casting to int is safe. */
14391 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14392 PyErr_SetString(PyExc_ValueError,
14393 "width too big");
14394 return -1;
14395 }
14396 arg->width = arg->width*10 + (arg->ch - '0');
14397 }
14398 }
14399
14400 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014401 if (arg->ch == '.') {
14402 arg->prec = 0;
14403 if (--ctx->fmtcnt >= 0) {
14404 arg->ch = FORMAT_READ(ctx);
14405 ctx->fmtpos++;
14406 }
14407 if (arg->ch == '*') {
14408 v = unicode_format_getnextarg(ctx);
14409 if (v == NULL)
14410 return -1;
14411 if (!PyLong_Check(v)) {
14412 PyErr_SetString(PyExc_TypeError,
14413 "* wants int");
14414 return -1;
14415 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014416 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014417 if (arg->prec == -1 && PyErr_Occurred())
14418 return -1;
14419 if (arg->prec < 0)
14420 arg->prec = 0;
14421 if (--ctx->fmtcnt >= 0) {
14422 arg->ch = FORMAT_READ(ctx);
14423 ctx->fmtpos++;
14424 }
14425 }
14426 else if (arg->ch >= '0' && arg->ch <= '9') {
14427 arg->prec = arg->ch - '0';
14428 while (--ctx->fmtcnt >= 0) {
14429 arg->ch = FORMAT_READ(ctx);
14430 ctx->fmtpos++;
14431 if (arg->ch < '0' || arg->ch > '9')
14432 break;
14433 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14434 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014435 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014436 return -1;
14437 }
14438 arg->prec = arg->prec*10 + (arg->ch - '0');
14439 }
14440 }
14441 }
14442
14443 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14444 if (ctx->fmtcnt >= 0) {
14445 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14446 if (--ctx->fmtcnt >= 0) {
14447 arg->ch = FORMAT_READ(ctx);
14448 ctx->fmtpos++;
14449 }
14450 }
14451 }
14452 if (ctx->fmtcnt < 0) {
14453 PyErr_SetString(PyExc_ValueError,
14454 "incomplete format");
14455 return -1;
14456 }
14457 return 0;
14458
14459#undef FORMAT_READ
14460}
14461
14462/* Format one argument. Supported conversion specifiers:
14463
14464 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014465 - "i", "d", "u": int or float
14466 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014467 - "e", "E", "f", "F", "g", "G": float
14468 - "c": int or str (1 character)
14469
Victor Stinner8dbd4212012-12-04 09:30:24 +010014470 When possible, the output is written directly into the Unicode writer
14471 (ctx->writer). A string is created when padding is required.
14472
Victor Stinnera47082312012-10-04 02:19:54 +020014473 Return 0 if the argument has been formatted into *p_str,
14474 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014475 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014476static int
14477unicode_format_arg_format(struct unicode_formatter_t *ctx,
14478 struct unicode_format_arg_t *arg,
14479 PyObject **p_str)
14480{
14481 PyObject *v;
14482 _PyUnicodeWriter *writer = &ctx->writer;
14483
14484 if (ctx->fmtcnt == 0)
14485 ctx->writer.overallocate = 0;
14486
14487 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014488 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014489 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014490 return 1;
14491 }
14492
14493 v = unicode_format_getnextarg(ctx);
14494 if (v == NULL)
14495 return -1;
14496
Victor Stinnera47082312012-10-04 02:19:54 +020014497
14498 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014499 case 's':
14500 case 'r':
14501 case 'a':
14502 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14503 /* Fast path */
14504 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14505 return -1;
14506 return 1;
14507 }
14508
14509 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14510 *p_str = v;
14511 Py_INCREF(*p_str);
14512 }
14513 else {
14514 if (arg->ch == 's')
14515 *p_str = PyObject_Str(v);
14516 else if (arg->ch == 'r')
14517 *p_str = PyObject_Repr(v);
14518 else
14519 *p_str = PyObject_ASCII(v);
14520 }
14521 break;
14522
14523 case 'i':
14524 case 'd':
14525 case 'u':
14526 case 'o':
14527 case 'x':
14528 case 'X':
14529 {
14530 int ret = mainformatlong(v, arg, p_str, writer);
14531 if (ret != 0)
14532 return ret;
14533 arg->sign = 1;
14534 break;
14535 }
14536
14537 case 'e':
14538 case 'E':
14539 case 'f':
14540 case 'F':
14541 case 'g':
14542 case 'G':
14543 if (arg->width == -1 && arg->prec == -1
14544 && !(arg->flags & (F_SIGN | F_BLANK)))
14545 {
14546 /* Fast path */
14547 if (formatfloat(v, arg, NULL, writer) == -1)
14548 return -1;
14549 return 1;
14550 }
14551
14552 arg->sign = 1;
14553 if (formatfloat(v, arg, p_str, NULL) == -1)
14554 return -1;
14555 break;
14556
14557 case 'c':
14558 {
14559 Py_UCS4 ch = formatchar(v);
14560 if (ch == (Py_UCS4) -1)
14561 return -1;
14562 if (arg->width == -1 && arg->prec == -1) {
14563 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014564 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014565 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014566 return 1;
14567 }
14568 *p_str = PyUnicode_FromOrdinal(ch);
14569 break;
14570 }
14571
14572 default:
14573 PyErr_Format(PyExc_ValueError,
14574 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014575 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014576 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14577 (int)arg->ch,
14578 ctx->fmtpos - 1);
14579 return -1;
14580 }
14581 if (*p_str == NULL)
14582 return -1;
14583 assert (PyUnicode_Check(*p_str));
14584 return 0;
14585}
14586
14587static int
14588unicode_format_arg_output(struct unicode_formatter_t *ctx,
14589 struct unicode_format_arg_t *arg,
14590 PyObject *str)
14591{
14592 Py_ssize_t len;
14593 enum PyUnicode_Kind kind;
14594 void *pbuf;
14595 Py_ssize_t pindex;
14596 Py_UCS4 signchar;
14597 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014598 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014599 Py_ssize_t sublen;
14600 _PyUnicodeWriter *writer = &ctx->writer;
14601 Py_UCS4 fill;
14602
14603 fill = ' ';
14604 if (arg->sign && arg->flags & F_ZERO)
14605 fill = '0';
14606
14607 if (PyUnicode_READY(str) == -1)
14608 return -1;
14609
14610 len = PyUnicode_GET_LENGTH(str);
14611 if ((arg->width == -1 || arg->width <= len)
14612 && (arg->prec == -1 || arg->prec >= len)
14613 && !(arg->flags & (F_SIGN | F_BLANK)))
14614 {
14615 /* Fast path */
14616 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14617 return -1;
14618 return 0;
14619 }
14620
14621 /* Truncate the string for "s", "r" and "a" formats
14622 if the precision is set */
14623 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14624 if (arg->prec >= 0 && len > arg->prec)
14625 len = arg->prec;
14626 }
14627
14628 /* Adjust sign and width */
14629 kind = PyUnicode_KIND(str);
14630 pbuf = PyUnicode_DATA(str);
14631 pindex = 0;
14632 signchar = '\0';
14633 if (arg->sign) {
14634 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14635 if (ch == '-' || ch == '+') {
14636 signchar = ch;
14637 len--;
14638 pindex++;
14639 }
14640 else if (arg->flags & F_SIGN)
14641 signchar = '+';
14642 else if (arg->flags & F_BLANK)
14643 signchar = ' ';
14644 else
14645 arg->sign = 0;
14646 }
14647 if (arg->width < len)
14648 arg->width = len;
14649
14650 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014651 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014652 if (!(arg->flags & F_LJUST)) {
14653 if (arg->sign) {
14654 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014655 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014656 }
14657 else {
14658 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014659 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014660 }
14661 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014662 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14663 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014664 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014665 }
14666
Victor Stinnera47082312012-10-04 02:19:54 +020014667 buflen = arg->width;
14668 if (arg->sign && len == arg->width)
14669 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014670 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014671 return -1;
14672
14673 /* Write the sign if needed */
14674 if (arg->sign) {
14675 if (fill != ' ') {
14676 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14677 writer->pos += 1;
14678 }
14679 if (arg->width > len)
14680 arg->width--;
14681 }
14682
14683 /* Write the numeric prefix for "x", "X" and "o" formats
14684 if the alternate form is used.
14685 For example, write "0x" for the "%#x" format. */
14686 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14687 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14688 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14689 if (fill != ' ') {
14690 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14691 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14692 writer->pos += 2;
14693 pindex += 2;
14694 }
14695 arg->width -= 2;
14696 if (arg->width < 0)
14697 arg->width = 0;
14698 len -= 2;
14699 }
14700
14701 /* Pad left with the fill character if needed */
14702 if (arg->width > len && !(arg->flags & F_LJUST)) {
14703 sublen = arg->width - len;
14704 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14705 writer->pos += sublen;
14706 arg->width = len;
14707 }
14708
14709 /* If padding with spaces: write sign if needed and/or numeric prefix if
14710 the alternate form is used */
14711 if (fill == ' ') {
14712 if (arg->sign) {
14713 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14714 writer->pos += 1;
14715 }
14716 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14717 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14718 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14719 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14720 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14721 writer->pos += 2;
14722 pindex += 2;
14723 }
14724 }
14725
14726 /* Write characters */
14727 if (len) {
14728 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14729 str, pindex, len);
14730 writer->pos += len;
14731 }
14732
14733 /* Pad right with the fill character if needed */
14734 if (arg->width > len) {
14735 sublen = arg->width - len;
14736 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14737 writer->pos += sublen;
14738 }
14739 return 0;
14740}
14741
14742/* Helper of PyUnicode_Format(): format one arg.
14743 Return 0 on success, raise an exception and return -1 on error. */
14744static int
14745unicode_format_arg(struct unicode_formatter_t *ctx)
14746{
14747 struct unicode_format_arg_t arg;
14748 PyObject *str;
14749 int ret;
14750
Victor Stinner8dbd4212012-12-04 09:30:24 +010014751 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14752 arg.flags = 0;
14753 arg.width = -1;
14754 arg.prec = -1;
14755 arg.sign = 0;
14756 str = NULL;
14757
Victor Stinnera47082312012-10-04 02:19:54 +020014758 ret = unicode_format_arg_parse(ctx, &arg);
14759 if (ret == -1)
14760 return -1;
14761
14762 ret = unicode_format_arg_format(ctx, &arg, &str);
14763 if (ret == -1)
14764 return -1;
14765
14766 if (ret != 1) {
14767 ret = unicode_format_arg_output(ctx, &arg, str);
14768 Py_DECREF(str);
14769 if (ret == -1)
14770 return -1;
14771 }
14772
14773 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14774 PyErr_SetString(PyExc_TypeError,
14775 "not all arguments converted during string formatting");
14776 return -1;
14777 }
14778 return 0;
14779}
14780
Alexander Belopolsky40018472011-02-26 01:02:56 +000014781PyObject *
14782PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014783{
Victor Stinnera47082312012-10-04 02:19:54 +020014784 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014785
Guido van Rossumd57fd912000-03-10 22:53:23 +000014786 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014787 PyErr_BadInternalCall();
14788 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014789 }
Victor Stinnera47082312012-10-04 02:19:54 +020014790
14791 ctx.fmtstr = PyUnicode_FromObject(format);
14792 if (ctx.fmtstr == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000014793 return NULL;
Victor Stinnera47082312012-10-04 02:19:54 +020014794 if (PyUnicode_READY(ctx.fmtstr) == -1) {
14795 Py_DECREF(ctx.fmtstr);
14796 return NULL;
14797 }
14798 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14799 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14800 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14801 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014802
Victor Stinner8f674cc2013-04-17 23:02:17 +020014803 _PyUnicodeWriter_Init(&ctx.writer);
14804 ctx.writer.min_length = ctx.fmtcnt + 100;
14805 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014806
Guido van Rossumd57fd912000-03-10 22:53:23 +000014807 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014808 ctx.arglen = PyTuple_Size(args);
14809 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014810 }
14811 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014812 ctx.arglen = -1;
14813 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014814 }
Victor Stinnera47082312012-10-04 02:19:54 +020014815 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014816 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014817 ctx.dict = args;
14818 else
14819 ctx.dict = NULL;
14820 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014821
Victor Stinnera47082312012-10-04 02:19:54 +020014822 while (--ctx.fmtcnt >= 0) {
14823 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014824 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014825
14826 nonfmtpos = ctx.fmtpos++;
14827 while (ctx.fmtcnt >= 0 &&
14828 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14829 ctx.fmtpos++;
14830 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014831 }
Victor Stinnera47082312012-10-04 02:19:54 +020014832 if (ctx.fmtcnt < 0) {
14833 ctx.fmtpos--;
14834 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014835 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014836
Victor Stinnercfc4c132013-04-03 01:48:39 +020014837 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14838 nonfmtpos, ctx.fmtpos) < 0)
14839 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014840 }
14841 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014842 ctx.fmtpos++;
14843 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014844 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014845 }
14846 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014847
Victor Stinnera47082312012-10-04 02:19:54 +020014848 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014849 PyErr_SetString(PyExc_TypeError,
14850 "not all arguments converted during string formatting");
14851 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014852 }
14853
Victor Stinnera47082312012-10-04 02:19:54 +020014854 if (ctx.args_owned) {
14855 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014856 }
Victor Stinnera47082312012-10-04 02:19:54 +020014857 Py_DECREF(ctx.fmtstr);
14858 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014859
Benjamin Peterson29060642009-01-31 22:14:21 +000014860 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014861 Py_DECREF(ctx.fmtstr);
14862 _PyUnicodeWriter_Dealloc(&ctx.writer);
14863 if (ctx.args_owned) {
14864 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014865 }
14866 return NULL;
14867}
14868
Jeremy Hylton938ace62002-07-17 16:30:39 +000014869static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014870unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14871
Tim Peters6d6c1a32001-08-02 04:15:00 +000014872static PyObject *
14873unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14874{
Benjamin Peterson29060642009-01-31 22:14:21 +000014875 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014876 static char *kwlist[] = {"object", "encoding", "errors", 0};
14877 char *encoding = NULL;
14878 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014879
Benjamin Peterson14339b62009-01-31 16:36:08 +000014880 if (type != &PyUnicode_Type)
14881 return unicode_subtype_new(type, args, kwds);
14882 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014883 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014884 return NULL;
14885 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014886 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014887 if (encoding == NULL && errors == NULL)
14888 return PyObject_Str(x);
14889 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014890 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014891}
14892
Guido van Rossume023fe02001-08-30 03:12:59 +000014893static PyObject *
14894unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14895{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014896 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014897 Py_ssize_t length, char_size;
14898 int share_wstr, share_utf8;
14899 unsigned int kind;
14900 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014901
Benjamin Peterson14339b62009-01-31 16:36:08 +000014902 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014903
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014904 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014905 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014906 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014907 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014908 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014909 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014910 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014911 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014912
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014913 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014914 if (self == NULL) {
14915 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014916 return NULL;
14917 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014918 kind = PyUnicode_KIND(unicode);
14919 length = PyUnicode_GET_LENGTH(unicode);
14920
14921 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014922#ifdef Py_DEBUG
14923 _PyUnicode_HASH(self) = -1;
14924#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014925 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014926#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014927 _PyUnicode_STATE(self).interned = 0;
14928 _PyUnicode_STATE(self).kind = kind;
14929 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014930 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014931 _PyUnicode_STATE(self).ready = 1;
14932 _PyUnicode_WSTR(self) = NULL;
14933 _PyUnicode_UTF8_LENGTH(self) = 0;
14934 _PyUnicode_UTF8(self) = NULL;
14935 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014936 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014937
14938 share_utf8 = 0;
14939 share_wstr = 0;
14940 if (kind == PyUnicode_1BYTE_KIND) {
14941 char_size = 1;
14942 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14943 share_utf8 = 1;
14944 }
14945 else if (kind == PyUnicode_2BYTE_KIND) {
14946 char_size = 2;
14947 if (sizeof(wchar_t) == 2)
14948 share_wstr = 1;
14949 }
14950 else {
14951 assert(kind == PyUnicode_4BYTE_KIND);
14952 char_size = 4;
14953 if (sizeof(wchar_t) == 4)
14954 share_wstr = 1;
14955 }
14956
14957 /* Ensure we won't overflow the length. */
14958 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14959 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014960 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014961 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014962 data = PyObject_MALLOC((length + 1) * char_size);
14963 if (data == NULL) {
14964 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014965 goto onError;
14966 }
14967
Victor Stinnerc3c74152011-10-02 20:39:55 +020014968 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014969 if (share_utf8) {
14970 _PyUnicode_UTF8_LENGTH(self) = length;
14971 _PyUnicode_UTF8(self) = data;
14972 }
14973 if (share_wstr) {
14974 _PyUnicode_WSTR_LENGTH(self) = length;
14975 _PyUnicode_WSTR(self) = (wchar_t *)data;
14976 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014977
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014978 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014979 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014980 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014981#ifdef Py_DEBUG
14982 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14983#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014984 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014985 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014986
14987onError:
14988 Py_DECREF(unicode);
14989 Py_DECREF(self);
14990 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014991}
14992
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014993PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014994"str(object='') -> str\n\
14995str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014996\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014997Create a new string object from the given object. If encoding or\n\
14998errors is specified, then the object must expose a data buffer\n\
14999that will be decoded using the given encoding and error handler.\n\
15000Otherwise, returns the result of object.__str__() (if defined)\n\
15001or repr(object).\n\
15002encoding defaults to sys.getdefaultencoding().\n\
15003errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000015004
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015005static PyObject *unicode_iter(PyObject *seq);
15006
Guido van Rossumd57fd912000-03-10 22:53:23 +000015007PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000015008 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000015009 "str", /* tp_name */
15010 sizeof(PyUnicodeObject), /* tp_size */
15011 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015012 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015013 (destructor)unicode_dealloc, /* tp_dealloc */
15014 0, /* tp_print */
15015 0, /* tp_getattr */
15016 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015017 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015018 unicode_repr, /* tp_repr */
15019 &unicode_as_number, /* tp_as_number */
15020 &unicode_as_sequence, /* tp_as_sequence */
15021 &unicode_as_mapping, /* tp_as_mapping */
15022 (hashfunc) unicode_hash, /* tp_hash*/
15023 0, /* tp_call*/
15024 (reprfunc) unicode_str, /* tp_str */
15025 PyObject_GenericGetAttr, /* tp_getattro */
15026 0, /* tp_setattro */
15027 0, /* tp_as_buffer */
15028 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000015029 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015030 unicode_doc, /* tp_doc */
15031 0, /* tp_traverse */
15032 0, /* tp_clear */
15033 PyUnicode_RichCompare, /* tp_richcompare */
15034 0, /* tp_weaklistoffset */
15035 unicode_iter, /* tp_iter */
15036 0, /* tp_iternext */
15037 unicode_methods, /* tp_methods */
15038 0, /* tp_members */
15039 0, /* tp_getset */
15040 &PyBaseObject_Type, /* tp_base */
15041 0, /* tp_dict */
15042 0, /* tp_descr_get */
15043 0, /* tp_descr_set */
15044 0, /* tp_dictoffset */
15045 0, /* tp_init */
15046 0, /* tp_alloc */
15047 unicode_new, /* tp_new */
15048 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015049};
15050
15051/* Initialize the Unicode implementation */
15052
Victor Stinner3a50e702011-10-18 21:21:00 +020015053int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015054{
Thomas Wouters477c8d52006-05-27 19:21:47 +000015055 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015056 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000015057 0x000A, /* LINE FEED */
15058 0x000D, /* CARRIAGE RETURN */
15059 0x001C, /* FILE SEPARATOR */
15060 0x001D, /* GROUP SEPARATOR */
15061 0x001E, /* RECORD SEPARATOR */
15062 0x0085, /* NEXT LINE */
15063 0x2028, /* LINE SEPARATOR */
15064 0x2029, /* PARAGRAPH SEPARATOR */
15065 };
15066
Fred Drakee4315f52000-05-09 19:53:39 +000015067 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020015068 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015069 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015070 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020015071 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015072
Guido van Rossumcacfc072002-05-24 19:01:59 +000015073 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000015074 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000015075
15076 /* initialize the linebreak bloom filter */
15077 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015078 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015079 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015080
Christian Heimes26532f72013-07-20 14:57:16 +020015081 if (PyType_Ready(&EncodingMapType) < 0)
15082 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020015083
Benjamin Petersonc4311282012-10-30 23:21:10 -040015084 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
15085 Py_FatalError("Can't initialize field name iterator type");
15086
15087 if (PyType_Ready(&PyFormatterIter_Type) < 0)
15088 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040015089
Victor Stinner3a50e702011-10-18 21:21:00 +020015090 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015091}
15092
15093/* Finalize the Unicode implementation */
15094
Christian Heimesa156e092008-02-16 07:38:31 +000015095int
15096PyUnicode_ClearFreeList(void)
15097{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015098 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015099}
15100
Guido van Rossumd57fd912000-03-10 22:53:23 +000015101void
Thomas Wouters78890102000-07-22 19:25:51 +000015102_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015103{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015104 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015105
Serhiy Storchaka05997252013-01-26 12:14:02 +020015106 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015107
Serhiy Storchaka05997252013-01-26 12:14:02 +020015108 for (i = 0; i < 256; i++)
15109 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015110 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015111 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015112}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015113
Walter Dörwald16807132007-05-25 13:52:07 +000015114void
15115PyUnicode_InternInPlace(PyObject **p)
15116{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015117 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015118 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015119#ifdef Py_DEBUG
15120 assert(s != NULL);
15121 assert(_PyUnicode_CHECK(s));
15122#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015123 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015124 return;
15125#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015126 /* If it's a subclass, we don't really know what putting
15127 it in the interned dict might do. */
15128 if (!PyUnicode_CheckExact(s))
15129 return;
15130 if (PyUnicode_CHECK_INTERNED(s))
15131 return;
15132 if (interned == NULL) {
15133 interned = PyDict_New();
15134 if (interned == NULL) {
15135 PyErr_Clear(); /* Don't leave an exception */
15136 return;
15137 }
15138 }
15139 /* It might be that the GetItem call fails even
15140 though the key is present in the dictionary,
15141 namely when this happens during a stack overflow. */
15142 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010015143 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015144 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000015145
Victor Stinnerf0335102013-04-14 19:13:03 +020015146 if (t) {
15147 Py_INCREF(t);
15148 Py_DECREF(*p);
15149 *p = t;
15150 return;
15151 }
Walter Dörwald16807132007-05-25 13:52:07 +000015152
Benjamin Peterson14339b62009-01-31 16:36:08 +000015153 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010015154 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015155 PyErr_Clear();
15156 PyThreadState_GET()->recursion_critical = 0;
15157 return;
15158 }
15159 PyThreadState_GET()->recursion_critical = 0;
15160 /* The two references in interned are not counted by refcnt.
15161 The deallocator will take care of this */
15162 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015163 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015164}
15165
15166void
15167PyUnicode_InternImmortal(PyObject **p)
15168{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015169 PyUnicode_InternInPlace(p);
15170 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015171 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015172 Py_INCREF(*p);
15173 }
Walter Dörwald16807132007-05-25 13:52:07 +000015174}
15175
15176PyObject *
15177PyUnicode_InternFromString(const char *cp)
15178{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015179 PyObject *s = PyUnicode_FromString(cp);
15180 if (s == NULL)
15181 return NULL;
15182 PyUnicode_InternInPlace(&s);
15183 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015184}
15185
Alexander Belopolsky40018472011-02-26 01:02:56 +000015186void
15187_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015188{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015189 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015190 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015191 Py_ssize_t i, n;
15192 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015193
Benjamin Peterson14339b62009-01-31 16:36:08 +000015194 if (interned == NULL || !PyDict_Check(interned))
15195 return;
15196 keys = PyDict_Keys(interned);
15197 if (keys == NULL || !PyList_Check(keys)) {
15198 PyErr_Clear();
15199 return;
15200 }
Walter Dörwald16807132007-05-25 13:52:07 +000015201
Benjamin Peterson14339b62009-01-31 16:36:08 +000015202 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15203 detector, interned unicode strings are not forcibly deallocated;
15204 rather, we give them their stolen references back, and then clear
15205 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015206
Benjamin Peterson14339b62009-01-31 16:36:08 +000015207 n = PyList_GET_SIZE(keys);
15208 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015209 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015210 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015211 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015212 if (PyUnicode_READY(s) == -1) {
15213 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015214 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015215 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015216 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015217 case SSTATE_NOT_INTERNED:
15218 /* XXX Shouldn't happen */
15219 break;
15220 case SSTATE_INTERNED_IMMORTAL:
15221 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015222 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015223 break;
15224 case SSTATE_INTERNED_MORTAL:
15225 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015226 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015227 break;
15228 default:
15229 Py_FatalError("Inconsistent interned string state.");
15230 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015231 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015232 }
15233 fprintf(stderr, "total size of all interned strings: "
15234 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15235 "mortal/immortal\n", mortal_size, immortal_size);
15236 Py_DECREF(keys);
15237 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015238 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015239}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015240
15241
15242/********************* Unicode Iterator **************************/
15243
15244typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015245 PyObject_HEAD
15246 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015247 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015248} unicodeiterobject;
15249
15250static void
15251unicodeiter_dealloc(unicodeiterobject *it)
15252{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015253 _PyObject_GC_UNTRACK(it);
15254 Py_XDECREF(it->it_seq);
15255 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015256}
15257
15258static int
15259unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15260{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015261 Py_VISIT(it->it_seq);
15262 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015263}
15264
15265static PyObject *
15266unicodeiter_next(unicodeiterobject *it)
15267{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015268 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015269
Benjamin Peterson14339b62009-01-31 16:36:08 +000015270 assert(it != NULL);
15271 seq = it->it_seq;
15272 if (seq == NULL)
15273 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015274 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015275
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015276 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15277 int kind = PyUnicode_KIND(seq);
15278 void *data = PyUnicode_DATA(seq);
15279 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15280 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015281 if (item != NULL)
15282 ++it->it_index;
15283 return item;
15284 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015285
Benjamin Peterson14339b62009-01-31 16:36:08 +000015286 Py_DECREF(seq);
15287 it->it_seq = NULL;
15288 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015289}
15290
15291static PyObject *
15292unicodeiter_len(unicodeiterobject *it)
15293{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015294 Py_ssize_t len = 0;
15295 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015296 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015297 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015298}
15299
15300PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15301
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015302static PyObject *
15303unicodeiter_reduce(unicodeiterobject *it)
15304{
15305 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015306 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015307 it->it_seq, it->it_index);
15308 } else {
15309 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
15310 if (u == NULL)
15311 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015312 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015313 }
15314}
15315
15316PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15317
15318static PyObject *
15319unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15320{
15321 Py_ssize_t index = PyLong_AsSsize_t(state);
15322 if (index == -1 && PyErr_Occurred())
15323 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015324 if (it->it_seq != NULL) {
15325 if (index < 0)
15326 index = 0;
15327 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15328 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15329 it->it_index = index;
15330 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015331 Py_RETURN_NONE;
15332}
15333
15334PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15335
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015336static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015337 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015338 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015339 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15340 reduce_doc},
15341 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15342 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015343 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015344};
15345
15346PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015347 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15348 "str_iterator", /* tp_name */
15349 sizeof(unicodeiterobject), /* tp_basicsize */
15350 0, /* tp_itemsize */
15351 /* methods */
15352 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15353 0, /* tp_print */
15354 0, /* tp_getattr */
15355 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015356 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015357 0, /* tp_repr */
15358 0, /* tp_as_number */
15359 0, /* tp_as_sequence */
15360 0, /* tp_as_mapping */
15361 0, /* tp_hash */
15362 0, /* tp_call */
15363 0, /* tp_str */
15364 PyObject_GenericGetAttr, /* tp_getattro */
15365 0, /* tp_setattro */
15366 0, /* tp_as_buffer */
15367 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15368 0, /* tp_doc */
15369 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15370 0, /* tp_clear */
15371 0, /* tp_richcompare */
15372 0, /* tp_weaklistoffset */
15373 PyObject_SelfIter, /* tp_iter */
15374 (iternextfunc)unicodeiter_next, /* tp_iternext */
15375 unicodeiter_methods, /* tp_methods */
15376 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015377};
15378
15379static PyObject *
15380unicode_iter(PyObject *seq)
15381{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015382 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015383
Benjamin Peterson14339b62009-01-31 16:36:08 +000015384 if (!PyUnicode_Check(seq)) {
15385 PyErr_BadInternalCall();
15386 return NULL;
15387 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015388 if (PyUnicode_READY(seq) == -1)
15389 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015390 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15391 if (it == NULL)
15392 return NULL;
15393 it->it_index = 0;
15394 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015395 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015396 _PyObject_GC_TRACK(it);
15397 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015398}
15399
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015400
15401size_t
15402Py_UNICODE_strlen(const Py_UNICODE *u)
15403{
15404 int res = 0;
15405 while(*u++)
15406 res++;
15407 return res;
15408}
15409
15410Py_UNICODE*
15411Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15412{
15413 Py_UNICODE *u = s1;
15414 while ((*u++ = *s2++));
15415 return s1;
15416}
15417
15418Py_UNICODE*
15419Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15420{
15421 Py_UNICODE *u = s1;
15422 while ((*u++ = *s2++))
15423 if (n-- == 0)
15424 break;
15425 return s1;
15426}
15427
15428Py_UNICODE*
15429Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15430{
15431 Py_UNICODE *u1 = s1;
15432 u1 += Py_UNICODE_strlen(u1);
15433 Py_UNICODE_strcpy(u1, s2);
15434 return s1;
15435}
15436
15437int
15438Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15439{
15440 while (*s1 && *s2 && *s1 == *s2)
15441 s1++, s2++;
15442 if (*s1 && *s2)
15443 return (*s1 < *s2) ? -1 : +1;
15444 if (*s1)
15445 return 1;
15446 if (*s2)
15447 return -1;
15448 return 0;
15449}
15450
15451int
15452Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15453{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015454 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015455 for (; n != 0; n--) {
15456 u1 = *s1;
15457 u2 = *s2;
15458 if (u1 != u2)
15459 return (u1 < u2) ? -1 : +1;
15460 if (u1 == '\0')
15461 return 0;
15462 s1++;
15463 s2++;
15464 }
15465 return 0;
15466}
15467
15468Py_UNICODE*
15469Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15470{
15471 const Py_UNICODE *p;
15472 for (p = s; *p; p++)
15473 if (*p == c)
15474 return (Py_UNICODE*)p;
15475 return NULL;
15476}
15477
15478Py_UNICODE*
15479Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15480{
15481 const Py_UNICODE *p;
15482 p = s + Py_UNICODE_strlen(s);
15483 while (p != s) {
15484 p--;
15485 if (*p == c)
15486 return (Py_UNICODE*)p;
15487 }
15488 return NULL;
15489}
Victor Stinner331ea922010-08-10 16:37:20 +000015490
Victor Stinner71133ff2010-09-01 23:43:53 +000015491Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015492PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015493{
Victor Stinner577db2c2011-10-11 22:12:48 +020015494 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015495 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015496
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015497 if (!PyUnicode_Check(unicode)) {
15498 PyErr_BadArgument();
15499 return NULL;
15500 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015501 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015502 if (u == NULL)
15503 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015504 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015505 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015506 PyErr_NoMemory();
15507 return NULL;
15508 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015509 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015510 size *= sizeof(Py_UNICODE);
15511 copy = PyMem_Malloc(size);
15512 if (copy == NULL) {
15513 PyErr_NoMemory();
15514 return NULL;
15515 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015516 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015517 return copy;
15518}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015519
Georg Brandl66c221e2010-10-14 07:04:07 +000015520/* A _string module, to export formatter_parser and formatter_field_name_split
15521 to the string.Formatter class implemented in Python. */
15522
15523static PyMethodDef _string_methods[] = {
15524 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15525 METH_O, PyDoc_STR("split the argument as a field name")},
15526 {"formatter_parser", (PyCFunction) formatter_parser,
15527 METH_O, PyDoc_STR("parse the argument as a format string")},
15528 {NULL, NULL}
15529};
15530
15531static struct PyModuleDef _string_module = {
15532 PyModuleDef_HEAD_INIT,
15533 "_string",
15534 PyDoc_STR("string helper module"),
15535 0,
15536 _string_methods,
15537 NULL,
15538 NULL,
15539 NULL,
15540 NULL
15541};
15542
15543PyMODINIT_FUNC
15544PyInit__string(void)
15545{
15546 return PyModule_Create(&_string_module);
15547}
15548
15549
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015550#ifdef __cplusplus
15551}
15552#endif