blob: 0709789991e9337537045e963bc95ed9e1d29a03 [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
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300296/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
297 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000298Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000299PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000300{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000301#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000302 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000303#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000304 /* This is actually an illegal character, so it should
305 not be passed to unichr. */
306 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000307#endif
308}
309
Victor Stinner910337b2011-10-03 03:20:16 +0200310#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200311int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100312_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200313{
314 PyASCIIObject *ascii;
315 unsigned int kind;
316
317 assert(PyUnicode_Check(op));
318
319 ascii = (PyASCIIObject *)op;
320 kind = ascii->state.kind;
321
Victor Stinnera3b334d2011-10-03 13:53:37 +0200322 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200323 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200324 assert(ascii->state.ready == 1);
325 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200326 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200327 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200328 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200329
Victor Stinnera41463c2011-10-04 01:05:08 +0200330 if (ascii->state.compact == 1) {
331 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200332 assert(kind == PyUnicode_1BYTE_KIND
333 || kind == PyUnicode_2BYTE_KIND
334 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200335 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200336 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200337 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100338 }
339 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200340 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
341
342 data = unicode->data.any;
343 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100344 assert(ascii->length == 0);
345 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200346 assert(ascii->state.compact == 0);
347 assert(ascii->state.ascii == 0);
348 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100349 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200350 assert(ascii->wstr != NULL);
351 assert(data == NULL);
352 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200353 }
354 else {
355 assert(kind == PyUnicode_1BYTE_KIND
356 || kind == PyUnicode_2BYTE_KIND
357 || kind == PyUnicode_4BYTE_KIND);
358 assert(ascii->state.compact == 0);
359 assert(ascii->state.ready == 1);
360 assert(data != NULL);
361 if (ascii->state.ascii) {
362 assert (compact->utf8 == data);
363 assert (compact->utf8_length == ascii->length);
364 }
365 else
366 assert (compact->utf8 != data);
367 }
368 }
369 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200370 if (
371#if SIZEOF_WCHAR_T == 2
372 kind == PyUnicode_2BYTE_KIND
373#else
374 kind == PyUnicode_4BYTE_KIND
375#endif
376 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200377 {
378 assert(ascii->wstr == data);
379 assert(compact->wstr_length == ascii->length);
380 } else
381 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200382 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200383
384 if (compact->utf8 == NULL)
385 assert(compact->utf8_length == 0);
386 if (ascii->wstr == NULL)
387 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200388 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200389 /* check that the best kind is used */
390 if (check_content && kind != PyUnicode_WCHAR_KIND)
391 {
392 Py_ssize_t i;
393 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200394 void *data;
395 Py_UCS4 ch;
396
397 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200398 for (i=0; i < ascii->length; i++)
399 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200400 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200401 if (ch > maxchar)
402 maxchar = ch;
403 }
404 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100405 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200406 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100407 assert(maxchar <= 255);
408 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200409 else
410 assert(maxchar < 128);
411 }
Victor Stinner77faf692011-11-20 18:56:05 +0100412 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200413 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100414 assert(maxchar <= 0xFFFF);
415 }
416 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200417 assert(maxchar >= 0x10000);
Victor Stinner8faf8212011-12-08 22:14:11 +0100418 assert(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100419 }
Victor Stinner718fbf02012-04-26 00:39:37 +0200420 assert(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200421 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400422 return 1;
423}
Victor Stinner910337b2011-10-03 03:20:16 +0200424#endif
425
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100426static PyObject*
427unicode_result_wchar(PyObject *unicode)
428{
429#ifndef Py_DEBUG
430 Py_ssize_t len;
431
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100432 len = _PyUnicode_WSTR_LENGTH(unicode);
433 if (len == 0) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100434 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200435 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100436 }
437
438 if (len == 1) {
439 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100440 if ((Py_UCS4)ch < 256) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100441 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
442 Py_DECREF(unicode);
443 return latin1_char;
444 }
445 }
446
447 if (_PyUnicode_Ready(unicode) < 0) {
Victor Stinneraa771272012-10-04 02:32:58 +0200448 Py_DECREF(unicode);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100449 return NULL;
450 }
451#else
Victor Stinneraa771272012-10-04 02:32:58 +0200452 assert(Py_REFCNT(unicode) == 1);
453
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100454 /* don't make the result ready in debug mode to ensure that the caller
455 makes the string ready before using it */
456 assert(_PyUnicode_CheckConsistency(unicode, 1));
457#endif
458 return unicode;
459}
460
461static PyObject*
462unicode_result_ready(PyObject *unicode)
463{
464 Py_ssize_t length;
465
466 length = PyUnicode_GET_LENGTH(unicode);
467 if (length == 0) {
468 if (unicode != unicode_empty) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100469 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200470 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100471 }
472 return unicode_empty;
473 }
474
475 if (length == 1) {
Victor Stinner69ed0f42013-04-09 21:48:24 +0200476 void *data = PyUnicode_DATA(unicode);
477 int kind = PyUnicode_KIND(unicode);
478 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100479 if (ch < 256) {
480 PyObject *latin1_char = unicode_latin1[ch];
481 if (latin1_char != NULL) {
482 if (unicode != latin1_char) {
483 Py_INCREF(latin1_char);
484 Py_DECREF(unicode);
485 }
486 return latin1_char;
487 }
488 else {
489 assert(_PyUnicode_CheckConsistency(unicode, 1));
490 Py_INCREF(unicode);
491 unicode_latin1[ch] = unicode;
492 return unicode;
493 }
494 }
495 }
496
497 assert(_PyUnicode_CheckConsistency(unicode, 1));
498 return unicode;
499}
500
501static PyObject*
502unicode_result(PyObject *unicode)
503{
504 assert(_PyUnicode_CHECK(unicode));
505 if (PyUnicode_IS_READY(unicode))
506 return unicode_result_ready(unicode);
507 else
508 return unicode_result_wchar(unicode);
509}
510
Victor Stinnerc4b49542011-12-11 22:44:26 +0100511static PyObject*
512unicode_result_unchanged(PyObject *unicode)
513{
514 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500515 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100516 return NULL;
517 Py_INCREF(unicode);
518 return unicode;
519 }
520 else
521 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100522 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100523}
524
Thomas Wouters477c8d52006-05-27 19:21:47 +0000525/* --- Bloom Filters ----------------------------------------------------- */
526
527/* stuff to implement simple "bloom filters" for Unicode characters.
528 to keep things simple, we use a single bitmask, using the least 5
529 bits from each unicode characters as the bit index. */
530
531/* the linebreak mask is set up by Unicode_Init below */
532
Antoine Pitrouf068f942010-01-13 14:19:12 +0000533#if LONG_BIT >= 128
534#define BLOOM_WIDTH 128
535#elif LONG_BIT >= 64
536#define BLOOM_WIDTH 64
537#elif LONG_BIT >= 32
538#define BLOOM_WIDTH 32
539#else
540#error "LONG_BIT is smaller than 32"
541#endif
542
Thomas Wouters477c8d52006-05-27 19:21:47 +0000543#define BLOOM_MASK unsigned long
544
Serhiy Storchaka05997252013-01-26 12:14:02 +0200545static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000546
Antoine Pitrouf068f942010-01-13 14:19:12 +0000547#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000548
Benjamin Peterson29060642009-01-31 22:14:21 +0000549#define BLOOM_LINEBREAK(ch) \
550 ((ch) < 128U ? ascii_linebreak[(ch)] : \
551 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000552
Alexander Belopolsky40018472011-02-26 01:02:56 +0000553Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200554make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000555{
Victor Stinnera85af502013-04-09 21:53:54 +0200556#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
557 do { \
558 TYPE *data = (TYPE *)PTR; \
559 TYPE *end = data + LEN; \
560 Py_UCS4 ch; \
561 for (; data != end; data++) { \
562 ch = *data; \
563 MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
564 } \
565 break; \
566 } while (0)
567
Thomas Wouters477c8d52006-05-27 19:21:47 +0000568 /* calculate simple bloom-style bitmask for a given unicode string */
569
Antoine Pitrouf068f942010-01-13 14:19:12 +0000570 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000571
572 mask = 0;
Victor Stinnera85af502013-04-09 21:53:54 +0200573 switch (kind) {
574 case PyUnicode_1BYTE_KIND:
575 BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
576 break;
577 case PyUnicode_2BYTE_KIND:
578 BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
579 break;
580 case PyUnicode_4BYTE_KIND:
581 BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
582 break;
583 default:
584 assert(0);
585 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000586 return mask;
Victor Stinnera85af502013-04-09 21:53:54 +0200587
588#undef BLOOM_UPDATE
Thomas Wouters477c8d52006-05-27 19:21:47 +0000589}
590
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200591/* Compilation of templated routines */
592
593#include "stringlib/asciilib.h"
594#include "stringlib/fastsearch.h"
595#include "stringlib/partition.h"
596#include "stringlib/split.h"
597#include "stringlib/count.h"
598#include "stringlib/find.h"
599#include "stringlib/find_max_char.h"
600#include "stringlib/localeutil.h"
601#include "stringlib/undef.h"
602
603#include "stringlib/ucs1lib.h"
604#include "stringlib/fastsearch.h"
605#include "stringlib/partition.h"
606#include "stringlib/split.h"
607#include "stringlib/count.h"
608#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300609#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200610#include "stringlib/find_max_char.h"
611#include "stringlib/localeutil.h"
612#include "stringlib/undef.h"
613
614#include "stringlib/ucs2lib.h"
615#include "stringlib/fastsearch.h"
616#include "stringlib/partition.h"
617#include "stringlib/split.h"
618#include "stringlib/count.h"
619#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300620#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200621#include "stringlib/find_max_char.h"
622#include "stringlib/localeutil.h"
623#include "stringlib/undef.h"
624
625#include "stringlib/ucs4lib.h"
626#include "stringlib/fastsearch.h"
627#include "stringlib/partition.h"
628#include "stringlib/split.h"
629#include "stringlib/count.h"
630#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300631#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200632#include "stringlib/find_max_char.h"
633#include "stringlib/localeutil.h"
634#include "stringlib/undef.h"
635
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200636#include "stringlib/unicodedefs.h"
637#include "stringlib/fastsearch.h"
638#include "stringlib/count.h"
639#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100640#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200641
Guido van Rossumd57fd912000-03-10 22:53:23 +0000642/* --- Unicode Object ----------------------------------------------------- */
643
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200644static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200645fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200646
Serhiy Storchakad9d769f2015-03-24 21:55:47 +0200647Py_LOCAL_INLINE(Py_ssize_t) findchar(const void *s, int kind,
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200648 Py_ssize_t size, Py_UCS4 ch,
649 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200650{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200651 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
652
653 switch (kind) {
654 case PyUnicode_1BYTE_KIND:
655 {
656 Py_UCS1 ch1 = (Py_UCS1) ch;
657 if (ch1 == ch)
658 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
659 else
660 return -1;
661 }
662 case PyUnicode_2BYTE_KIND:
663 {
664 Py_UCS2 ch2 = (Py_UCS2) ch;
665 if (ch2 == ch)
666 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
667 else
668 return -1;
669 }
670 case PyUnicode_4BYTE_KIND:
671 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
672 default:
673 assert(0);
674 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200675 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200676}
677
Victor Stinnerafffce42012-10-03 23:03:17 +0200678#ifdef Py_DEBUG
679/* Fill the data of an Unicode string with invalid characters to detect bugs
680 earlier.
681
682 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
683 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
684 invalid character in Unicode 6.0. */
685static void
686unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
687{
688 int kind = PyUnicode_KIND(unicode);
689 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
690 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
691 if (length <= old_length)
692 return;
693 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
694}
695#endif
696
Victor Stinnerfe226c02011-10-03 03:52:20 +0200697static PyObject*
698resize_compact(PyObject *unicode, Py_ssize_t length)
699{
700 Py_ssize_t char_size;
701 Py_ssize_t struct_size;
702 Py_ssize_t new_size;
703 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100704 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +0200705#ifdef Py_DEBUG
706 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
707#endif
708
Victor Stinner79891572012-05-03 13:43:07 +0200709 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200710 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100711 assert(PyUnicode_IS_COMPACT(unicode));
712
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200713 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100714 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200715 struct_size = sizeof(PyASCIIObject);
716 else
717 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200718 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200719
Victor Stinnerfe226c02011-10-03 03:52:20 +0200720 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
721 PyErr_NoMemory();
722 return NULL;
723 }
724 new_size = (struct_size + (length + 1) * char_size);
725
Victor Stinner84def372011-12-11 20:04:56 +0100726 _Py_DEC_REFTOTAL;
727 _Py_ForgetReference(unicode);
728
Serhiy Storchaka20b39b22014-09-28 11:27:24 +0300729 new_unicode = (PyObject *)PyObject_REALLOC(unicode, new_size);
Victor Stinner84def372011-12-11 20:04:56 +0100730 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100731 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200732 PyErr_NoMemory();
733 return NULL;
734 }
Victor Stinner84def372011-12-11 20:04:56 +0100735 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200736 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100737
Victor Stinnerfe226c02011-10-03 03:52:20 +0200738 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200739 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200740 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100741 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200742 _PyUnicode_WSTR_LENGTH(unicode) = length;
743 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100744 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
745 PyObject_DEL(_PyUnicode_WSTR(unicode));
746 _PyUnicode_WSTR(unicode) = NULL;
747 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200748#ifdef Py_DEBUG
749 unicode_fill_invalid(unicode, old_length);
750#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200751 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
752 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200753 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200754 return unicode;
755}
756
Alexander Belopolsky40018472011-02-26 01:02:56 +0000757static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200758resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000759{
Victor Stinner95663112011-10-04 01:03:50 +0200760 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100761 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200762 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200763 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000764
Victor Stinnerfe226c02011-10-03 03:52:20 +0200765 if (PyUnicode_IS_READY(unicode)) {
766 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200767 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200768 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +0200769#ifdef Py_DEBUG
770 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
771#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200772
773 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200774 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200775 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
776 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200777
778 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
779 PyErr_NoMemory();
780 return -1;
781 }
782 new_size = (length + 1) * char_size;
783
Victor Stinner7a9105a2011-12-12 00:13:42 +0100784 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
785 {
786 PyObject_DEL(_PyUnicode_UTF8(unicode));
787 _PyUnicode_UTF8(unicode) = NULL;
788 _PyUnicode_UTF8_LENGTH(unicode) = 0;
789 }
790
Victor Stinnerfe226c02011-10-03 03:52:20 +0200791 data = (PyObject *)PyObject_REALLOC(data, new_size);
792 if (data == NULL) {
793 PyErr_NoMemory();
794 return -1;
795 }
796 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200797 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200798 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200799 _PyUnicode_WSTR_LENGTH(unicode) = length;
800 }
801 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200802 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200803 _PyUnicode_UTF8_LENGTH(unicode) = length;
804 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200805 _PyUnicode_LENGTH(unicode) = length;
806 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +0200807#ifdef Py_DEBUG
808 unicode_fill_invalid(unicode, old_length);
809#endif
Victor Stinner95663112011-10-04 01:03:50 +0200810 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200811 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200812 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200813 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200814 }
Victor Stinner95663112011-10-04 01:03:50 +0200815 assert(_PyUnicode_WSTR(unicode) != NULL);
816
817 /* check for integer overflow */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -0700818 if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
Victor Stinner95663112011-10-04 01:03:50 +0200819 PyErr_NoMemory();
820 return -1;
821 }
Victor Stinner7a9105a2011-12-12 00:13:42 +0100822 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +0200823 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +0100824 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +0200825 if (!wstr) {
826 PyErr_NoMemory();
827 return -1;
828 }
829 _PyUnicode_WSTR(unicode) = wstr;
830 _PyUnicode_WSTR(unicode)[length] = 0;
831 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200832 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000833 return 0;
834}
835
Victor Stinnerfe226c02011-10-03 03:52:20 +0200836static PyObject*
837resize_copy(PyObject *unicode, Py_ssize_t length)
838{
839 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100840 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200841 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100842
Benjamin Petersonbac79492012-01-14 13:34:47 -0500843 if (PyUnicode_READY(unicode) == -1)
Victor Stinner7a9105a2011-12-12 00:13:42 +0100844 return NULL;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200845
846 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
847 if (copy == NULL)
848 return NULL;
849
850 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +0200851 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200852 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200853 }
854 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200855 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100856
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200857 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200858 if (w == NULL)
859 return NULL;
860 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
861 copy_length = Py_MIN(copy_length, length);
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +0200862 Py_MEMCPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
863 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200864 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200865 }
866}
867
Guido van Rossumd57fd912000-03-10 22:53:23 +0000868/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000869 Ux0000 terminated; some code (e.g. new_identifier)
870 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000871
872 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000873 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000874
875*/
876
Alexander Belopolsky40018472011-02-26 01:02:56 +0000877static PyUnicodeObject *
878_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000879{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +0200880 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200881 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000882
Thomas Wouters477c8d52006-05-27 19:21:47 +0000883 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000884 if (length == 0 && unicode_empty != NULL) {
885 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200886 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000887 }
888
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000889 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -0700890 if (length > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000891 return (PyUnicodeObject *)PyErr_NoMemory();
892 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200893 if (length < 0) {
894 PyErr_SetString(PyExc_SystemError,
895 "Negative size passed to _PyUnicode_New");
896 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000897 }
898
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200899 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
900 if (unicode == NULL)
901 return NULL;
902 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +0100903
904 _PyUnicode_WSTR_LENGTH(unicode) = length;
905 _PyUnicode_HASH(unicode) = -1;
906 _PyUnicode_STATE(unicode).interned = 0;
907 _PyUnicode_STATE(unicode).kind = 0;
908 _PyUnicode_STATE(unicode).compact = 0;
909 _PyUnicode_STATE(unicode).ready = 0;
910 _PyUnicode_STATE(unicode).ascii = 0;
911 _PyUnicode_DATA_ANY(unicode) = NULL;
912 _PyUnicode_LENGTH(unicode) = 0;
913 _PyUnicode_UTF8(unicode) = NULL;
914 _PyUnicode_UTF8_LENGTH(unicode) = 0;
915
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200916 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
917 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100918 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +0000919 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100920 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000921 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200922
Jeremy Hyltond8082792003-09-16 19:41:39 +0000923 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000924 * the caller fails before initializing str -- unicode_resize()
925 * reads str[0], and the Keep-Alive optimization can keep memory
926 * allocated for str alive across a call to unicode_dealloc(unicode).
927 * We don't want unicode_resize to read uninitialized memory in
928 * that case.
929 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200930 _PyUnicode_WSTR(unicode)[0] = 0;
931 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +0100932
Victor Stinner7931d9a2011-11-04 00:22:48 +0100933 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000934 return unicode;
935}
936
Victor Stinnerf42dc442011-10-02 23:33:16 +0200937static const char*
938unicode_kind_name(PyObject *unicode)
939{
Victor Stinner42dfd712011-10-03 14:41:45 +0200940 /* don't check consistency: unicode_kind_name() is called from
941 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200942 if (!PyUnicode_IS_COMPACT(unicode))
943 {
944 if (!PyUnicode_IS_READY(unicode))
945 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -0600946 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200947 {
948 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200949 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200950 return "legacy ascii";
951 else
952 return "legacy latin1";
953 case PyUnicode_2BYTE_KIND:
954 return "legacy UCS2";
955 case PyUnicode_4BYTE_KIND:
956 return "legacy UCS4";
957 default:
958 return "<legacy invalid kind>";
959 }
960 }
961 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -0600962 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +0200963 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200964 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200965 return "ascii";
966 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200967 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200968 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200969 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200970 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200971 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200972 default:
973 return "<invalid compact kind>";
974 }
975}
976
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200977#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200978/* Functions wrapping macros for use in debugger */
979char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200980 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200981}
982
983void *_PyUnicode_compact_data(void *unicode) {
984 return _PyUnicode_COMPACT_DATA(unicode);
985}
986void *_PyUnicode_data(void *unicode){
987 printf("obj %p\n", unicode);
988 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
989 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
990 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
991 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
992 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
993 return PyUnicode_DATA(unicode);
994}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200995
996void
997_PyUnicode_Dump(PyObject *op)
998{
999 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001000 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1001 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
1002 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001003
Victor Stinnera849a4b2011-10-03 12:12:11 +02001004 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001005 {
1006 if (ascii->state.ascii)
1007 data = (ascii + 1);
1008 else
1009 data = (compact + 1);
1010 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001011 else
1012 data = unicode->data.any;
Victor Stinner293f3f52014-07-01 08:57:10 +02001013 printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
1014 unicode_kind_name(op), ascii->length);
Victor Stinner0d60e872011-10-23 19:47:19 +02001015
Victor Stinnera849a4b2011-10-03 12:12:11 +02001016 if (ascii->wstr == data)
1017 printf("shared ");
1018 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001019
Victor Stinnera3b334d2011-10-03 13:53:37 +02001020 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinner293f3f52014-07-01 08:57:10 +02001021 printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
Victor Stinnera849a4b2011-10-03 12:12:11 +02001022 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1023 printf("shared ");
Victor Stinner293f3f52014-07-01 08:57:10 +02001024 printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
1025 compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001026 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001027 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001028}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001029#endif
1030
1031PyObject *
1032PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1033{
1034 PyObject *obj;
1035 PyCompactUnicodeObject *unicode;
1036 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001037 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001038 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001039 Py_ssize_t char_size;
1040 Py_ssize_t struct_size;
1041
1042 /* Optimization for empty strings */
1043 if (size == 0 && unicode_empty != NULL) {
1044 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001045 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001046 }
1047
Victor Stinner9e9d6892011-10-04 01:02:02 +02001048 is_ascii = 0;
1049 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001050 struct_size = sizeof(PyCompactUnicodeObject);
1051 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001052 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001053 char_size = 1;
1054 is_ascii = 1;
1055 struct_size = sizeof(PyASCIIObject);
1056 }
1057 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001058 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001059 char_size = 1;
1060 }
1061 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001062 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001063 char_size = 2;
1064 if (sizeof(wchar_t) == 2)
1065 is_sharing = 1;
1066 }
1067 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001068 if (maxchar > MAX_UNICODE) {
1069 PyErr_SetString(PyExc_SystemError,
1070 "invalid maximum character passed to PyUnicode_New");
1071 return NULL;
1072 }
Victor Stinner8f825062012-04-27 13:55:39 +02001073 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001074 char_size = 4;
1075 if (sizeof(wchar_t) == 4)
1076 is_sharing = 1;
1077 }
1078
1079 /* Ensure we won't overflow the size. */
1080 if (size < 0) {
1081 PyErr_SetString(PyExc_SystemError,
1082 "Negative size passed to PyUnicode_New");
1083 return NULL;
1084 }
1085 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1086 return PyErr_NoMemory();
1087
1088 /* Duplicated allocation code from _PyObject_New() instead of a call to
1089 * PyObject_New() so we are able to allocate space for the object and
1090 * it's data buffer.
1091 */
1092 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1093 if (obj == NULL)
1094 return PyErr_NoMemory();
1095 obj = PyObject_INIT(obj, &PyUnicode_Type);
1096 if (obj == NULL)
1097 return NULL;
1098
1099 unicode = (PyCompactUnicodeObject *)obj;
1100 if (is_ascii)
1101 data = ((PyASCIIObject*)obj) + 1;
1102 else
1103 data = unicode + 1;
1104 _PyUnicode_LENGTH(unicode) = size;
1105 _PyUnicode_HASH(unicode) = -1;
1106 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001107 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001108 _PyUnicode_STATE(unicode).compact = 1;
1109 _PyUnicode_STATE(unicode).ready = 1;
1110 _PyUnicode_STATE(unicode).ascii = is_ascii;
1111 if (is_ascii) {
1112 ((char*)data)[size] = 0;
1113 _PyUnicode_WSTR(unicode) = NULL;
1114 }
Victor Stinner8f825062012-04-27 13:55:39 +02001115 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001116 ((char*)data)[size] = 0;
1117 _PyUnicode_WSTR(unicode) = NULL;
1118 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001119 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001120 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001121 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001122 else {
1123 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001124 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001125 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001126 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001127 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001128 ((Py_UCS4*)data)[size] = 0;
1129 if (is_sharing) {
1130 _PyUnicode_WSTR_LENGTH(unicode) = size;
1131 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1132 }
1133 else {
1134 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1135 _PyUnicode_WSTR(unicode) = NULL;
1136 }
1137 }
Victor Stinner8f825062012-04-27 13:55:39 +02001138#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001139 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001140#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001141 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001142 return obj;
1143}
1144
1145#if SIZEOF_WCHAR_T == 2
1146/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1147 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001148 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001149
1150 This function assumes that unicode can hold one more code point than wstr
1151 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001152static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001153unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001154 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001155{
1156 const wchar_t *iter;
1157 Py_UCS4 *ucs4_out;
1158
Victor Stinner910337b2011-10-03 03:20:16 +02001159 assert(unicode != NULL);
1160 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001161 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1162 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1163
1164 for (iter = begin; iter < end; ) {
1165 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1166 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001167 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1168 && (iter+1) < end
1169 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001170 {
Victor Stinner551ac952011-11-29 22:58:13 +01001171 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001172 iter += 2;
1173 }
1174 else {
1175 *ucs4_out++ = *iter;
1176 iter++;
1177 }
1178 }
1179 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1180 _PyUnicode_GET_LENGTH(unicode)));
1181
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001182}
1183#endif
1184
Victor Stinnercd9950f2011-10-02 00:34:53 +02001185static int
Victor Stinner488fa492011-12-12 00:01:39 +01001186unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001187{
Victor Stinner488fa492011-12-12 00:01:39 +01001188 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001189 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001190 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001191 return -1;
1192 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001193 return 0;
1194}
1195
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001196static int
1197_copy_characters(PyObject *to, Py_ssize_t to_start,
1198 PyObject *from, Py_ssize_t from_start,
1199 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001200{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001201 unsigned int from_kind, to_kind;
1202 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001203
Victor Stinneree4544c2012-05-09 22:24:08 +02001204 assert(0 <= how_many);
1205 assert(0 <= from_start);
1206 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001207 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001208 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001209 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001210
Victor Stinnerd3f08822012-05-29 12:57:52 +02001211 assert(PyUnicode_Check(to));
1212 assert(PyUnicode_IS_READY(to));
1213 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1214
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001215 if (how_many == 0)
1216 return 0;
1217
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001218 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001219 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001220 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001221 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001222
Victor Stinnerf1852262012-06-16 16:38:26 +02001223#ifdef Py_DEBUG
1224 if (!check_maxchar
1225 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1226 {
1227 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1228 Py_UCS4 ch;
1229 Py_ssize_t i;
1230 for (i=0; i < how_many; i++) {
1231 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1232 assert(ch <= to_maxchar);
1233 }
1234 }
1235#endif
1236
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001237 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001238 if (check_maxchar
1239 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1240 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001241 /* Writing Latin-1 characters into an ASCII string requires to
1242 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001243 Py_UCS4 max_char;
1244 max_char = ucs1lib_find_max_char(from_data,
1245 (Py_UCS1*)from_data + how_many);
1246 if (max_char >= 128)
1247 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001248 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001249 Py_MEMCPY((char*)to_data + to_kind * to_start,
1250 (char*)from_data + from_kind * from_start,
1251 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001252 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001253 else if (from_kind == PyUnicode_1BYTE_KIND
1254 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001255 {
1256 _PyUnicode_CONVERT_BYTES(
1257 Py_UCS1, Py_UCS2,
1258 PyUnicode_1BYTE_DATA(from) + from_start,
1259 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1260 PyUnicode_2BYTE_DATA(to) + to_start
1261 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001262 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001263 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001264 && to_kind == PyUnicode_4BYTE_KIND)
1265 {
1266 _PyUnicode_CONVERT_BYTES(
1267 Py_UCS1, Py_UCS4,
1268 PyUnicode_1BYTE_DATA(from) + from_start,
1269 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1270 PyUnicode_4BYTE_DATA(to) + to_start
1271 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001272 }
1273 else if (from_kind == PyUnicode_2BYTE_KIND
1274 && to_kind == PyUnicode_4BYTE_KIND)
1275 {
1276 _PyUnicode_CONVERT_BYTES(
1277 Py_UCS2, Py_UCS4,
1278 PyUnicode_2BYTE_DATA(from) + from_start,
1279 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1280 PyUnicode_4BYTE_DATA(to) + to_start
1281 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001282 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001283 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001284 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1285
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001286 if (!check_maxchar) {
1287 if (from_kind == PyUnicode_2BYTE_KIND
1288 && to_kind == PyUnicode_1BYTE_KIND)
1289 {
1290 _PyUnicode_CONVERT_BYTES(
1291 Py_UCS2, Py_UCS1,
1292 PyUnicode_2BYTE_DATA(from) + from_start,
1293 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1294 PyUnicode_1BYTE_DATA(to) + to_start
1295 );
1296 }
1297 else if (from_kind == PyUnicode_4BYTE_KIND
1298 && to_kind == PyUnicode_1BYTE_KIND)
1299 {
1300 _PyUnicode_CONVERT_BYTES(
1301 Py_UCS4, Py_UCS1,
1302 PyUnicode_4BYTE_DATA(from) + from_start,
1303 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1304 PyUnicode_1BYTE_DATA(to) + to_start
1305 );
1306 }
1307 else if (from_kind == PyUnicode_4BYTE_KIND
1308 && to_kind == PyUnicode_2BYTE_KIND)
1309 {
1310 _PyUnicode_CONVERT_BYTES(
1311 Py_UCS4, Py_UCS2,
1312 PyUnicode_4BYTE_DATA(from) + from_start,
1313 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1314 PyUnicode_2BYTE_DATA(to) + to_start
1315 );
1316 }
1317 else {
1318 assert(0);
1319 return -1;
1320 }
1321 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001322 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001323 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001324 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001325 Py_ssize_t i;
1326
Victor Stinnera0702ab2011-09-29 14:14:38 +02001327 for (i=0; i < how_many; i++) {
1328 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001329 if (ch > to_maxchar)
1330 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001331 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1332 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001333 }
1334 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001335 return 0;
1336}
1337
Victor Stinnerd3f08822012-05-29 12:57:52 +02001338void
1339_PyUnicode_FastCopyCharacters(
1340 PyObject *to, Py_ssize_t to_start,
1341 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001342{
1343 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1344}
1345
1346Py_ssize_t
1347PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1348 PyObject *from, Py_ssize_t from_start,
1349 Py_ssize_t how_many)
1350{
1351 int err;
1352
1353 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1354 PyErr_BadInternalCall();
1355 return -1;
1356 }
1357
Benjamin Petersonbac79492012-01-14 13:34:47 -05001358 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001359 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001360 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001361 return -1;
1362
Victor Stinnerd3f08822012-05-29 12:57:52 +02001363 if (from_start < 0) {
1364 PyErr_SetString(PyExc_IndexError, "string index out of range");
1365 return -1;
1366 }
1367 if (to_start < 0) {
1368 PyErr_SetString(PyExc_IndexError, "string index out of range");
1369 return -1;
1370 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001371 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1372 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1373 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001374 "Cannot write %zi characters at %zi "
1375 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001376 how_many, to_start, PyUnicode_GET_LENGTH(to));
1377 return -1;
1378 }
1379
1380 if (how_many == 0)
1381 return 0;
1382
Victor Stinner488fa492011-12-12 00:01:39 +01001383 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001384 return -1;
1385
1386 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1387 if (err) {
1388 PyErr_Format(PyExc_SystemError,
1389 "Cannot copy %s characters "
1390 "into a string of %s characters",
1391 unicode_kind_name(from),
1392 unicode_kind_name(to));
1393 return -1;
1394 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001395 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001396}
1397
Victor Stinner17222162011-09-28 22:15:37 +02001398/* Find the maximum code point and count the number of surrogate pairs so a
1399 correct string length can be computed before converting a string to UCS4.
1400 This function counts single surrogates as a character and not as a pair.
1401
1402 Return 0 on success, or -1 on error. */
1403static int
1404find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1405 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001406{
1407 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001408 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001409
Victor Stinnerc53be962011-10-02 21:33:54 +02001410 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001411 *num_surrogates = 0;
1412 *maxchar = 0;
1413
1414 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001415#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001416 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1417 && (iter+1) < end
1418 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1419 {
1420 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1421 ++(*num_surrogates);
1422 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001423 }
1424 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001425#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001426 {
1427 ch = *iter;
1428 iter++;
1429 }
1430 if (ch > *maxchar) {
1431 *maxchar = ch;
1432 if (*maxchar > MAX_UNICODE) {
1433 PyErr_Format(PyExc_ValueError,
1434 "character U+%x is not in range [U+0000; U+10ffff]",
1435 ch);
1436 return -1;
1437 }
1438 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001439 }
1440 return 0;
1441}
1442
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001443int
1444_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001445{
1446 wchar_t *end;
1447 Py_UCS4 maxchar = 0;
1448 Py_ssize_t num_surrogates;
1449#if SIZEOF_WCHAR_T == 2
1450 Py_ssize_t length_wo_surrogates;
1451#endif
1452
Georg Brandl7597add2011-10-05 16:36:47 +02001453 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001454 strings were created using _PyObject_New() and where no canonical
1455 representation (the str field) has been set yet aka strings
1456 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001457 assert(_PyUnicode_CHECK(unicode));
1458 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001459 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001460 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001461 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001462 /* Actually, it should neither be interned nor be anything else: */
1463 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001464
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001465 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001466 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001467 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001468 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001469
1470 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001471 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1472 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001473 PyErr_NoMemory();
1474 return -1;
1475 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001476 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001477 _PyUnicode_WSTR(unicode), end,
1478 PyUnicode_1BYTE_DATA(unicode));
1479 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1480 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1481 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1482 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001483 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001484 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001485 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001486 }
1487 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001488 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001489 _PyUnicode_UTF8(unicode) = NULL;
1490 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001491 }
1492 PyObject_FREE(_PyUnicode_WSTR(unicode));
1493 _PyUnicode_WSTR(unicode) = NULL;
1494 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1495 }
1496 /* In this case we might have to convert down from 4-byte native
1497 wchar_t to 2-byte unicode. */
1498 else if (maxchar < 65536) {
1499 assert(num_surrogates == 0 &&
1500 "FindMaxCharAndNumSurrogatePairs() messed up");
1501
Victor Stinner506f5922011-09-28 22:34:18 +02001502#if SIZEOF_WCHAR_T == 2
1503 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001504 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001505 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1506 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1507 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001508 _PyUnicode_UTF8(unicode) = NULL;
1509 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001510#else
1511 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001512 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001513 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001514 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001515 PyErr_NoMemory();
1516 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001517 }
Victor Stinner506f5922011-09-28 22:34:18 +02001518 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1519 _PyUnicode_WSTR(unicode), end,
1520 PyUnicode_2BYTE_DATA(unicode));
1521 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1522 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1523 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001524 _PyUnicode_UTF8(unicode) = NULL;
1525 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001526 PyObject_FREE(_PyUnicode_WSTR(unicode));
1527 _PyUnicode_WSTR(unicode) = NULL;
1528 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1529#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001530 }
1531 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1532 else {
1533#if SIZEOF_WCHAR_T == 2
1534 /* in case the native representation is 2-bytes, we need to allocate a
1535 new normalized 4-byte version. */
1536 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Serhiy Storchakae55181f2015-02-20 21:34:06 +02001537 if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) {
1538 PyErr_NoMemory();
1539 return -1;
1540 }
Victor Stinnerc3c74152011-10-02 20:39:55 +02001541 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1542 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001543 PyErr_NoMemory();
1544 return -1;
1545 }
1546 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1547 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001548 _PyUnicode_UTF8(unicode) = NULL;
1549 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001550 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1551 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001552 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001553 PyObject_FREE(_PyUnicode_WSTR(unicode));
1554 _PyUnicode_WSTR(unicode) = NULL;
1555 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1556#else
1557 assert(num_surrogates == 0);
1558
Victor Stinnerc3c74152011-10-02 20:39:55 +02001559 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001560 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001561 _PyUnicode_UTF8(unicode) = NULL;
1562 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001563 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1564#endif
1565 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1566 }
1567 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001568 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001569 return 0;
1570}
1571
Alexander Belopolsky40018472011-02-26 01:02:56 +00001572static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001573unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001574{
Walter Dörwald16807132007-05-25 13:52:07 +00001575 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001576 case SSTATE_NOT_INTERNED:
1577 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001578
Benjamin Peterson29060642009-01-31 22:14:21 +00001579 case SSTATE_INTERNED_MORTAL:
1580 /* revive dead object temporarily for DelItem */
1581 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001582 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001583 Py_FatalError(
1584 "deletion of interned string failed");
1585 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001586
Benjamin Peterson29060642009-01-31 22:14:21 +00001587 case SSTATE_INTERNED_IMMORTAL:
1588 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001589
Benjamin Peterson29060642009-01-31 22:14:21 +00001590 default:
1591 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001592 }
1593
Victor Stinner03490912011-10-03 23:45:12 +02001594 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001595 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001596 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001597 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001598 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1599 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001600
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001601 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001602}
1603
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001604#ifdef Py_DEBUG
1605static int
1606unicode_is_singleton(PyObject *unicode)
1607{
1608 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1609 if (unicode == unicode_empty)
1610 return 1;
1611 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1612 {
1613 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1614 if (ch < 256 && unicode_latin1[ch] == unicode)
1615 return 1;
1616 }
1617 return 0;
1618}
1619#endif
1620
Alexander Belopolsky40018472011-02-26 01:02:56 +00001621static int
Victor Stinner488fa492011-12-12 00:01:39 +01001622unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001623{
Victor Stinner488fa492011-12-12 00:01:39 +01001624 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001625 if (Py_REFCNT(unicode) != 1)
1626 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001627 if (_PyUnicode_HASH(unicode) != -1)
1628 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001629 if (PyUnicode_CHECK_INTERNED(unicode))
1630 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001631 if (!PyUnicode_CheckExact(unicode))
1632 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001633#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001634 /* singleton refcount is greater than 1 */
1635 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001636#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001637 return 1;
1638}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001639
Victor Stinnerfe226c02011-10-03 03:52:20 +02001640static int
1641unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1642{
1643 PyObject *unicode;
1644 Py_ssize_t old_length;
1645
1646 assert(p_unicode != NULL);
1647 unicode = *p_unicode;
1648
1649 assert(unicode != NULL);
1650 assert(PyUnicode_Check(unicode));
1651 assert(0 <= length);
1652
Victor Stinner910337b2011-10-03 03:20:16 +02001653 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001654 old_length = PyUnicode_WSTR_LENGTH(unicode);
1655 else
1656 old_length = PyUnicode_GET_LENGTH(unicode);
1657 if (old_length == length)
1658 return 0;
1659
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001660 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001661 _Py_INCREF_UNICODE_EMPTY();
1662 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001663 return -1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001664 Py_DECREF(*p_unicode);
1665 *p_unicode = unicode_empty;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001666 return 0;
1667 }
1668
Victor Stinner488fa492011-12-12 00:01:39 +01001669 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001670 PyObject *copy = resize_copy(unicode, length);
1671 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001672 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001673 Py_DECREF(*p_unicode);
1674 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001675 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001676 }
1677
Victor Stinnerfe226c02011-10-03 03:52:20 +02001678 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001679 PyObject *new_unicode = resize_compact(unicode, length);
1680 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001681 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001682 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001683 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001684 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001685 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001686}
1687
Alexander Belopolsky40018472011-02-26 01:02:56 +00001688int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001689PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001690{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001691 PyObject *unicode;
1692 if (p_unicode == NULL) {
1693 PyErr_BadInternalCall();
1694 return -1;
1695 }
1696 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001697 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001698 {
1699 PyErr_BadInternalCall();
1700 return -1;
1701 }
1702 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001703}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001704
Victor Stinnerc5166102012-02-22 13:55:02 +01001705/* Copy a ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001706
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001707 WARNING: The function doesn't copy the terminating null character and
1708 doesn't check the maximum character (may write a latin1 character in an
1709 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001710static void
1711unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1712 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001713{
1714 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1715 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001716 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001717
1718 switch (kind) {
1719 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001720 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001721#ifdef Py_DEBUG
1722 if (PyUnicode_IS_ASCII(unicode)) {
1723 Py_UCS4 maxchar = ucs1lib_find_max_char(
1724 (const Py_UCS1*)str,
1725 (const Py_UCS1*)str + len);
1726 assert(maxchar < 128);
1727 }
1728#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001729 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001730 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001731 }
1732 case PyUnicode_2BYTE_KIND: {
1733 Py_UCS2 *start = (Py_UCS2 *)data + index;
1734 Py_UCS2 *ucs2 = start;
1735 assert(index <= PyUnicode_GET_LENGTH(unicode));
1736
Victor Stinner184252a2012-06-16 02:57:41 +02001737 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001738 *ucs2 = (Py_UCS2)*str;
1739
1740 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001741 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001742 }
1743 default: {
1744 Py_UCS4 *start = (Py_UCS4 *)data + index;
1745 Py_UCS4 *ucs4 = start;
1746 assert(kind == PyUnicode_4BYTE_KIND);
1747 assert(index <= PyUnicode_GET_LENGTH(unicode));
1748
Victor Stinner184252a2012-06-16 02:57:41 +02001749 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001750 *ucs4 = (Py_UCS4)*str;
1751
1752 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001753 }
1754 }
1755}
1756
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001757static PyObject*
1758get_latin1_char(unsigned char ch)
1759{
Victor Stinnera464fc12011-10-02 20:39:30 +02001760 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001761 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001762 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001763 if (!unicode)
1764 return NULL;
1765 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001766 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001767 unicode_latin1[ch] = unicode;
1768 }
1769 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001770 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001771}
1772
Victor Stinner985a82a2014-01-03 12:53:47 +01001773static PyObject*
1774unicode_char(Py_UCS4 ch)
1775{
1776 PyObject *unicode;
1777
1778 assert(ch <= MAX_UNICODE);
1779
Victor Stinnerf3b46b42014-01-03 13:16:00 +01001780 if (ch < 256)
1781 return get_latin1_char(ch);
1782
Victor Stinner985a82a2014-01-03 12:53:47 +01001783 unicode = PyUnicode_New(1, ch);
1784 if (unicode == NULL)
1785 return NULL;
1786 switch (PyUnicode_KIND(unicode)) {
1787 case PyUnicode_1BYTE_KIND:
1788 PyUnicode_1BYTE_DATA(unicode)[0] = (Py_UCS1)ch;
1789 break;
1790 case PyUnicode_2BYTE_KIND:
1791 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
1792 break;
1793 default:
1794 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1795 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
1796 }
1797 assert(_PyUnicode_CheckConsistency(unicode, 1));
1798 return unicode;
1799}
1800
Alexander Belopolsky40018472011-02-26 01:02:56 +00001801PyObject *
1802PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001803{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001804 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001805 Py_UCS4 maxchar = 0;
1806 Py_ssize_t num_surrogates;
1807
1808 if (u == NULL)
1809 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001810
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001811 /* If the Unicode data is known at construction time, we can apply
1812 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001813
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001814 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02001815 if (size == 0)
1816 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00001817
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001818 /* Single character Unicode objects in the Latin-1 range are
1819 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001820 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001821 return get_latin1_char((unsigned char)*u);
1822
1823 /* If not empty and not single character, copy the Unicode data
1824 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001825 if (find_maxchar_surrogates(u, u + size,
1826 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001827 return NULL;
1828
Victor Stinner8faf8212011-12-08 22:14:11 +01001829 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001830 if (!unicode)
1831 return NULL;
1832
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001833 switch (PyUnicode_KIND(unicode)) {
1834 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001835 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001836 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1837 break;
1838 case PyUnicode_2BYTE_KIND:
1839#if Py_UNICODE_SIZE == 2
1840 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1841#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001842 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001843 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1844#endif
1845 break;
1846 case PyUnicode_4BYTE_KIND:
1847#if SIZEOF_WCHAR_T == 2
1848 /* This is the only case which has to process surrogates, thus
1849 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001850 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001851#else
1852 assert(num_surrogates == 0);
1853 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1854#endif
1855 break;
1856 default:
1857 assert(0 && "Impossible state");
1858 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001859
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001860 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001861}
1862
Alexander Belopolsky40018472011-02-26 01:02:56 +00001863PyObject *
1864PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001865{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001866 if (size < 0) {
1867 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001868 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001869 return NULL;
1870 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001871 if (u != NULL)
1872 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
1873 else
1874 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001875}
1876
Alexander Belopolsky40018472011-02-26 01:02:56 +00001877PyObject *
1878PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001879{
1880 size_t size = strlen(u);
1881 if (size > PY_SSIZE_T_MAX) {
1882 PyErr_SetString(PyExc_OverflowError, "input too long");
1883 return NULL;
1884 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01001885 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00001886}
1887
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001888PyObject *
1889_PyUnicode_FromId(_Py_Identifier *id)
1890{
1891 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01001892 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
1893 strlen(id->string),
1894 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001895 if (!id->object)
1896 return NULL;
1897 PyUnicode_InternInPlace(&id->object);
1898 assert(!id->next);
1899 id->next = static_strings;
1900 static_strings = id;
1901 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001902 return id->object;
1903}
1904
1905void
1906_PyUnicode_ClearStaticStrings()
1907{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001908 _Py_Identifier *tmp, *s = static_strings;
1909 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02001910 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001911 tmp = s->next;
1912 s->next = NULL;
1913 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001914 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06001915 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001916}
1917
Benjamin Peterson0df54292012-03-26 14:50:32 -04001918/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001919
Victor Stinnerd3f08822012-05-29 12:57:52 +02001920PyObject*
1921_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001922{
Victor Stinnerd3f08822012-05-29 12:57:52 +02001923 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01001924 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01001925 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02001926#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001927 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001928#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001929 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01001930 }
Victor Stinner785938e2011-12-11 20:09:03 +01001931 unicode = PyUnicode_New(size, 127);
1932 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02001933 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01001934 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
1935 assert(_PyUnicode_CheckConsistency(unicode, 1));
1936 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02001937}
1938
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001939static Py_UCS4
1940kind_maxchar_limit(unsigned int kind)
1941{
Benjamin Petersonead6b532011-12-20 17:23:42 -06001942 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001943 case PyUnicode_1BYTE_KIND:
1944 return 0x80;
1945 case PyUnicode_2BYTE_KIND:
1946 return 0x100;
1947 case PyUnicode_4BYTE_KIND:
1948 return 0x10000;
1949 default:
1950 assert(0 && "invalid kind");
Victor Stinner8faf8212011-12-08 22:14:11 +01001951 return MAX_UNICODE;
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001952 }
1953}
1954
Victor Stinnere6abb482012-05-02 01:15:40 +02001955Py_LOCAL_INLINE(Py_UCS4)
1956align_maxchar(Py_UCS4 maxchar)
1957{
1958 if (maxchar <= 127)
1959 return 127;
1960 else if (maxchar <= 255)
1961 return 255;
1962 else if (maxchar <= 65535)
1963 return 65535;
1964 else
1965 return MAX_UNICODE;
1966}
1967
Victor Stinner702c7342011-10-05 13:50:52 +02001968static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01001969_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001970{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001971 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001972 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001973
Serhiy Storchaka678db842013-01-26 12:16:36 +02001974 if (size == 0)
1975 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001976 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001977 if (size == 1)
1978 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001979
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001980 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001981 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001982 if (!res)
1983 return NULL;
1984 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001985 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001986 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001987}
1988
Victor Stinnere57b1c02011-09-28 22:20:48 +02001989static PyObject*
1990_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001991{
1992 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001993 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001994
Serhiy Storchaka678db842013-01-26 12:16:36 +02001995 if (size == 0)
1996 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001997 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01001998 if (size == 1)
1999 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002000
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002001 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002002 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002003 if (!res)
2004 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002005 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002006 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002007 else {
2008 _PyUnicode_CONVERT_BYTES(
2009 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2010 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002011 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002012 return res;
2013}
2014
Victor Stinnere57b1c02011-09-28 22:20:48 +02002015static PyObject*
2016_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002017{
2018 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002019 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002020
Serhiy Storchaka678db842013-01-26 12:16:36 +02002021 if (size == 0)
2022 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002023 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002024 if (size == 1)
2025 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002026
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002027 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002028 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002029 if (!res)
2030 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002031 if (max_char < 256)
2032 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2033 PyUnicode_1BYTE_DATA(res));
2034 else if (max_char < 0x10000)
2035 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2036 PyUnicode_2BYTE_DATA(res));
2037 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002038 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002039 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002040 return res;
2041}
2042
2043PyObject*
2044PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2045{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002046 if (size < 0) {
2047 PyErr_SetString(PyExc_ValueError, "size must be positive");
2048 return NULL;
2049 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002050 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002051 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002052 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002053 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002054 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002055 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002056 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002057 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002058 PyErr_SetString(PyExc_SystemError, "invalid kind");
2059 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002060 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002061}
2062
Victor Stinnerece58de2012-04-23 23:36:38 +02002063Py_UCS4
2064_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2065{
2066 enum PyUnicode_Kind kind;
2067 void *startptr, *endptr;
2068
2069 assert(PyUnicode_IS_READY(unicode));
2070 assert(0 <= start);
2071 assert(end <= PyUnicode_GET_LENGTH(unicode));
2072 assert(start <= end);
2073
2074 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2075 return PyUnicode_MAX_CHAR_VALUE(unicode);
2076
2077 if (start == end)
2078 return 127;
2079
Victor Stinner94d558b2012-04-27 22:26:58 +02002080 if (PyUnicode_IS_ASCII(unicode))
2081 return 127;
2082
Victor Stinnerece58de2012-04-23 23:36:38 +02002083 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002084 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002085 endptr = (char *)startptr + end * kind;
2086 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002087 switch(kind) {
2088 case PyUnicode_1BYTE_KIND:
2089 return ucs1lib_find_max_char(startptr, endptr);
2090 case PyUnicode_2BYTE_KIND:
2091 return ucs2lib_find_max_char(startptr, endptr);
2092 case PyUnicode_4BYTE_KIND:
2093 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002094 default:
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002095 assert(0);
2096 return 0;
Victor Stinnerece58de2012-04-23 23:36:38 +02002097 }
2098}
2099
Victor Stinner25a4b292011-10-06 12:31:55 +02002100/* Ensure that a string uses the most efficient storage, if it is not the
2101 case: create a new string with of the right kind. Write NULL into *p_unicode
2102 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002103static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002104unicode_adjust_maxchar(PyObject **p_unicode)
2105{
2106 PyObject *unicode, *copy;
2107 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002108 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002109 unsigned int kind;
2110
2111 assert(p_unicode != NULL);
2112 unicode = *p_unicode;
2113 assert(PyUnicode_IS_READY(unicode));
2114 if (PyUnicode_IS_ASCII(unicode))
2115 return;
2116
2117 len = PyUnicode_GET_LENGTH(unicode);
2118 kind = PyUnicode_KIND(unicode);
2119 if (kind == PyUnicode_1BYTE_KIND) {
2120 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002121 max_char = ucs1lib_find_max_char(u, u + len);
2122 if (max_char >= 128)
2123 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002124 }
2125 else if (kind == PyUnicode_2BYTE_KIND) {
2126 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002127 max_char = ucs2lib_find_max_char(u, u + len);
2128 if (max_char >= 256)
2129 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002130 }
2131 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002132 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002133 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002134 max_char = ucs4lib_find_max_char(u, u + len);
2135 if (max_char >= 0x10000)
2136 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002137 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002138 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002139 if (copy != NULL)
2140 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002141 Py_DECREF(unicode);
2142 *p_unicode = copy;
2143}
2144
Victor Stinner034f6cf2011-09-30 02:26:44 +02002145PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002146_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002147{
Victor Stinner87af4f22011-11-21 23:03:47 +01002148 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002149 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002150
Victor Stinner034f6cf2011-09-30 02:26:44 +02002151 if (!PyUnicode_Check(unicode)) {
2152 PyErr_BadInternalCall();
2153 return NULL;
2154 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002155 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002156 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002157
Victor Stinner87af4f22011-11-21 23:03:47 +01002158 length = PyUnicode_GET_LENGTH(unicode);
2159 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002160 if (!copy)
2161 return NULL;
2162 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2163
Victor Stinner87af4f22011-11-21 23:03:47 +01002164 Py_MEMCPY(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
2165 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002166 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002167 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002168}
2169
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002170
Victor Stinnerbc603d12011-10-02 01:00:40 +02002171/* Widen Unicode objects to larger buffers. Don't write terminating null
2172 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002173
2174void*
2175_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2176{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002177 Py_ssize_t len;
2178 void *result;
2179 unsigned int skind;
2180
Benjamin Petersonbac79492012-01-14 13:34:47 -05002181 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002182 return NULL;
2183
2184 len = PyUnicode_GET_LENGTH(s);
2185 skind = PyUnicode_KIND(s);
2186 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002187 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002188 return NULL;
2189 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002190 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002191 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002192 result = PyMem_New(Py_UCS2, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002193 if (!result)
2194 return PyErr_NoMemory();
2195 assert(skind == PyUnicode_1BYTE_KIND);
2196 _PyUnicode_CONVERT_BYTES(
2197 Py_UCS1, Py_UCS2,
2198 PyUnicode_1BYTE_DATA(s),
2199 PyUnicode_1BYTE_DATA(s) + len,
2200 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002201 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002202 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002203 result = PyMem_New(Py_UCS4, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002204 if (!result)
2205 return PyErr_NoMemory();
2206 if (skind == PyUnicode_2BYTE_KIND) {
2207 _PyUnicode_CONVERT_BYTES(
2208 Py_UCS2, Py_UCS4,
2209 PyUnicode_2BYTE_DATA(s),
2210 PyUnicode_2BYTE_DATA(s) + len,
2211 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002212 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002213 else {
2214 assert(skind == PyUnicode_1BYTE_KIND);
2215 _PyUnicode_CONVERT_BYTES(
2216 Py_UCS1, Py_UCS4,
2217 PyUnicode_1BYTE_DATA(s),
2218 PyUnicode_1BYTE_DATA(s) + len,
2219 result);
2220 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002221 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002222 default:
2223 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002224 }
Victor Stinner01698042011-10-04 00:04:26 +02002225 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002226 return NULL;
2227}
2228
2229static Py_UCS4*
2230as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2231 int copy_null)
2232{
2233 int kind;
2234 void *data;
2235 Py_ssize_t len, targetlen;
2236 if (PyUnicode_READY(string) == -1)
2237 return NULL;
2238 kind = PyUnicode_KIND(string);
2239 data = PyUnicode_DATA(string);
2240 len = PyUnicode_GET_LENGTH(string);
2241 targetlen = len;
2242 if (copy_null)
2243 targetlen++;
2244 if (!target) {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002245 target = PyMem_New(Py_UCS4, targetlen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002246 if (!target) {
2247 PyErr_NoMemory();
2248 return NULL;
2249 }
2250 }
2251 else {
2252 if (targetsize < targetlen) {
2253 PyErr_Format(PyExc_SystemError,
2254 "string is longer than the buffer");
2255 if (copy_null && 0 < targetsize)
2256 target[0] = 0;
2257 return NULL;
2258 }
2259 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002260 if (kind == PyUnicode_1BYTE_KIND) {
2261 Py_UCS1 *start = (Py_UCS1 *) data;
2262 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002263 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002264 else if (kind == PyUnicode_2BYTE_KIND) {
2265 Py_UCS2 *start = (Py_UCS2 *) data;
2266 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2267 }
2268 else {
2269 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002270 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002271 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002272 if (copy_null)
2273 target[len] = 0;
2274 return target;
2275}
2276
2277Py_UCS4*
2278PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2279 int copy_null)
2280{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002281 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002282 PyErr_BadInternalCall();
2283 return NULL;
2284 }
2285 return as_ucs4(string, target, targetsize, copy_null);
2286}
2287
2288Py_UCS4*
2289PyUnicode_AsUCS4Copy(PyObject *string)
2290{
2291 return as_ucs4(string, NULL, 0, 1);
2292}
2293
2294#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002295
Alexander Belopolsky40018472011-02-26 01:02:56 +00002296PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002297PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002298{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002299 if (w == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00002300 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02002301 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson29060642009-01-31 22:14:21 +00002302 PyErr_BadInternalCall();
2303 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002304 }
2305
Martin v. Löwis790465f2008-04-05 20:41:37 +00002306 if (size == -1) {
2307 size = wcslen(w);
2308 }
2309
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002310 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002311}
2312
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002313#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002314
Victor Stinner15a11362012-10-06 23:48:20 +02002315/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002316 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2317 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2318#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002319
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002320static int
2321unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2322 Py_ssize_t width, Py_ssize_t precision)
2323{
2324 Py_ssize_t length, fill, arglen;
2325 Py_UCS4 maxchar;
2326
2327 if (PyUnicode_READY(str) == -1)
2328 return -1;
2329
2330 length = PyUnicode_GET_LENGTH(str);
2331 if ((precision == -1 || precision >= length)
2332 && width <= length)
2333 return _PyUnicodeWriter_WriteStr(writer, str);
2334
2335 if (precision != -1)
2336 length = Py_MIN(precision, length);
2337
2338 arglen = Py_MAX(length, width);
2339 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2340 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2341 else
2342 maxchar = writer->maxchar;
2343
2344 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2345 return -1;
2346
2347 if (width > length) {
2348 fill = width - length;
2349 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2350 return -1;
2351 writer->pos += fill;
2352 }
2353
2354 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2355 str, 0, length);
2356 writer->pos += length;
2357 return 0;
2358}
2359
2360static int
2361unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
2362 Py_ssize_t width, Py_ssize_t precision)
2363{
2364 /* UTF-8 */
2365 Py_ssize_t length;
2366 PyObject *unicode;
2367 int res;
2368
2369 length = strlen(str);
2370 if (precision != -1)
2371 length = Py_MIN(length, precision);
2372 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2373 if (unicode == NULL)
2374 return -1;
2375
2376 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2377 Py_DECREF(unicode);
2378 return res;
2379}
2380
Victor Stinner96865452011-03-01 23:44:09 +00002381static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002382unicode_fromformat_arg(_PyUnicodeWriter *writer,
2383 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002384{
Victor Stinnere215d962012-10-06 23:03:36 +02002385 const char *p;
2386 Py_ssize_t len;
2387 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002388 Py_ssize_t width;
2389 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002390 int longflag;
2391 int longlongflag;
2392 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002393 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002394
2395 p = f;
2396 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002397 zeropad = 0;
2398 if (*f == '0') {
2399 zeropad = 1;
2400 f++;
2401 }
Victor Stinner96865452011-03-01 23:44:09 +00002402
2403 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002404 width = -1;
2405 if (Py_ISDIGIT((unsigned)*f)) {
2406 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002407 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002408 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002409 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002410 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002411 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002412 return NULL;
2413 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002414 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002415 f++;
2416 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002417 }
2418 precision = -1;
2419 if (*f == '.') {
2420 f++;
2421 if (Py_ISDIGIT((unsigned)*f)) {
2422 precision = (*f - '0');
2423 f++;
2424 while (Py_ISDIGIT((unsigned)*f)) {
2425 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2426 PyErr_SetString(PyExc_ValueError,
2427 "precision too big");
2428 return NULL;
2429 }
2430 precision = (precision * 10) + (*f - '0');
2431 f++;
2432 }
2433 }
Victor Stinner96865452011-03-01 23:44:09 +00002434 if (*f == '%') {
2435 /* "%.3%s" => f points to "3" */
2436 f--;
2437 }
2438 }
2439 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002440 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002441 f--;
2442 }
Victor Stinner96865452011-03-01 23:44:09 +00002443
2444 /* Handle %ld, %lu, %lld and %llu. */
2445 longflag = 0;
2446 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002447 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002448 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002449 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002450 longflag = 1;
2451 ++f;
2452 }
2453#ifdef HAVE_LONG_LONG
2454 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002455 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002456 longlongflag = 1;
2457 f += 2;
2458 }
2459#endif
2460 }
2461 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002462 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002463 size_tflag = 1;
2464 ++f;
2465 }
Victor Stinnere215d962012-10-06 23:03:36 +02002466
2467 if (f[1] == '\0')
2468 writer->overallocate = 0;
2469
2470 switch (*f) {
2471 case 'c':
2472 {
2473 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002474 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002475 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002476 "character argument not in range(0x110000)");
2477 return NULL;
2478 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002479 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002480 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002481 break;
2482 }
2483
2484 case 'i':
2485 case 'd':
2486 case 'u':
2487 case 'x':
2488 {
2489 /* used by sprintf */
Victor Stinner15a11362012-10-06 23:48:20 +02002490 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002491 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002492
2493 if (*f == 'u') {
Victor Stinnere215d962012-10-06 23:03:36 +02002494 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002495 len = sprintf(buffer, "%lu",
Victor Stinnere215d962012-10-06 23:03:36 +02002496 va_arg(*vargs, unsigned long));
2497#ifdef HAVE_LONG_LONG
2498 else if (longlongflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002499 len = sprintf(buffer, "%" PY_FORMAT_LONG_LONG "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002500 va_arg(*vargs, unsigned PY_LONG_LONG));
2501#endif
2502 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002503 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002504 va_arg(*vargs, size_t));
2505 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002506 len = sprintf(buffer, "%u",
Victor Stinnere215d962012-10-06 23:03:36 +02002507 va_arg(*vargs, unsigned int));
2508 }
2509 else if (*f == 'x') {
Victor Stinner3aa979e2014-11-18 21:40:51 +01002510 len = sprintf(buffer, "%x", va_arg(*vargs, int));
Victor Stinnere215d962012-10-06 23:03:36 +02002511 }
2512 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002513 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002514 len = sprintf(buffer, "%li",
Victor Stinnere215d962012-10-06 23:03:36 +02002515 va_arg(*vargs, long));
2516#ifdef HAVE_LONG_LONG
2517 else if (longlongflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002518 len = sprintf(buffer, "%" PY_FORMAT_LONG_LONG "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002519 va_arg(*vargs, PY_LONG_LONG));
2520#endif
2521 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002522 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002523 va_arg(*vargs, Py_ssize_t));
2524 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002525 len = sprintf(buffer, "%i",
Victor Stinnere215d962012-10-06 23:03:36 +02002526 va_arg(*vargs, int));
2527 }
2528 assert(len >= 0);
2529
Victor Stinnere215d962012-10-06 23:03:36 +02002530 if (precision < len)
2531 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002532
2533 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002534 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2535 return NULL;
2536
Victor Stinnere215d962012-10-06 23:03:36 +02002537 if (width > precision) {
2538 Py_UCS4 fillchar;
2539 fill = width - precision;
2540 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002541 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2542 return NULL;
2543 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002544 }
Victor Stinner15a11362012-10-06 23:48:20 +02002545 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002546 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002547 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2548 return NULL;
2549 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002550 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002551
Victor Stinner4a587072013-11-19 12:54:53 +01002552 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2553 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002554 break;
2555 }
2556
2557 case 'p':
2558 {
2559 char number[MAX_LONG_LONG_CHARS];
2560
2561 len = sprintf(number, "%p", va_arg(*vargs, void*));
2562 assert(len >= 0);
2563
2564 /* %p is ill-defined: ensure leading 0x. */
2565 if (number[1] == 'X')
2566 number[1] = 'x';
2567 else if (number[1] != 'x') {
2568 memmove(number + 2, number,
2569 strlen(number) + 1);
2570 number[0] = '0';
2571 number[1] = 'x';
2572 len += 2;
2573 }
2574
Victor Stinner4a587072013-11-19 12:54:53 +01002575 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002576 return NULL;
2577 break;
2578 }
2579
2580 case 's':
2581 {
2582 /* UTF-8 */
2583 const char *s = va_arg(*vargs, const char*);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002584 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002585 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002586 break;
2587 }
2588
2589 case 'U':
2590 {
2591 PyObject *obj = va_arg(*vargs, PyObject *);
2592 assert(obj && _PyUnicode_CHECK(obj));
2593
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002594 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002595 return NULL;
2596 break;
2597 }
2598
2599 case 'V':
2600 {
2601 PyObject *obj = va_arg(*vargs, PyObject *);
2602 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002603 if (obj) {
2604 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002605 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002606 return NULL;
2607 }
2608 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002609 assert(str != NULL);
2610 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002611 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002612 }
2613 break;
2614 }
2615
2616 case 'S':
2617 {
2618 PyObject *obj = va_arg(*vargs, PyObject *);
2619 PyObject *str;
2620 assert(obj);
2621 str = PyObject_Str(obj);
2622 if (!str)
2623 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002624 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002625 Py_DECREF(str);
2626 return NULL;
2627 }
2628 Py_DECREF(str);
2629 break;
2630 }
2631
2632 case 'R':
2633 {
2634 PyObject *obj = va_arg(*vargs, PyObject *);
2635 PyObject *repr;
2636 assert(obj);
2637 repr = PyObject_Repr(obj);
2638 if (!repr)
2639 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002640 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002641 Py_DECREF(repr);
2642 return NULL;
2643 }
2644 Py_DECREF(repr);
2645 break;
2646 }
2647
2648 case 'A':
2649 {
2650 PyObject *obj = va_arg(*vargs, PyObject *);
2651 PyObject *ascii;
2652 assert(obj);
2653 ascii = PyObject_ASCII(obj);
2654 if (!ascii)
2655 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002656 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002657 Py_DECREF(ascii);
2658 return NULL;
2659 }
2660 Py_DECREF(ascii);
2661 break;
2662 }
2663
2664 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002665 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002666 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002667 break;
2668
2669 default:
2670 /* if we stumble upon an unknown formatting code, copy the rest
2671 of the format string to the output string. (we cannot just
2672 skip the code, since there's no way to know what's in the
2673 argument list) */
2674 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002675 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002676 return NULL;
2677 f = p+len;
2678 return f;
2679 }
2680
2681 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002682 return f;
2683}
2684
Walter Dörwaldd2034312007-05-18 16:29:38 +00002685PyObject *
2686PyUnicode_FromFormatV(const char *format, va_list vargs)
2687{
Victor Stinnere215d962012-10-06 23:03:36 +02002688 va_list vargs2;
2689 const char *f;
2690 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002691
Victor Stinner8f674cc2013-04-17 23:02:17 +02002692 _PyUnicodeWriter_Init(&writer);
2693 writer.min_length = strlen(format) + 100;
2694 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002695
2696 /* va_list may be an array (of 1 item) on some platforms (ex: AMD64).
2697 Copy it to be able to pass a reference to a subfunction. */
2698 Py_VA_COPY(vargs2, vargs);
2699
2700 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002701 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002702 f = unicode_fromformat_arg(&writer, f, &vargs2);
2703 if (f == NULL)
2704 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002705 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002706 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002707 const char *p;
2708 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002709
Victor Stinnere215d962012-10-06 23:03:36 +02002710 p = f;
2711 do
2712 {
2713 if ((unsigned char)*p > 127) {
2714 PyErr_Format(PyExc_ValueError,
2715 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2716 "string, got a non-ASCII byte: 0x%02x",
2717 (unsigned char)*p);
2718 return NULL;
2719 }
2720 p++;
2721 }
2722 while (*p != '\0' && *p != '%');
2723 len = p - f;
2724
2725 if (*p == '\0')
2726 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01002727
2728 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002729 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002730
2731 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002732 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002733 }
Victor Stinnere215d962012-10-06 23:03:36 +02002734 return _PyUnicodeWriter_Finish(&writer);
2735
2736 fail:
2737 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002738 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002739}
2740
Walter Dörwaldd2034312007-05-18 16:29:38 +00002741PyObject *
2742PyUnicode_FromFormat(const char *format, ...)
2743{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002744 PyObject* ret;
2745 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002746
2747#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002748 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002749#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002750 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002751#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002752 ret = PyUnicode_FromFormatV(format, vargs);
2753 va_end(vargs);
2754 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002755}
2756
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002757#ifdef HAVE_WCHAR_H
2758
Victor Stinner5593d8a2010-10-02 11:11:27 +00002759/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2760 convert a Unicode object to a wide character string.
2761
Victor Stinnerd88d9832011-09-06 02:00:05 +02002762 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002763 character) required to convert the unicode object. Ignore size argument.
2764
Victor Stinnerd88d9832011-09-06 02:00:05 +02002765 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002766 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002767 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002768static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002769unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002770 wchar_t *w,
2771 Py_ssize_t size)
2772{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002773 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002774 const wchar_t *wstr;
2775
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002776 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002777 if (wstr == NULL)
2778 return -1;
2779
Victor Stinner5593d8a2010-10-02 11:11:27 +00002780 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002781 if (size > res)
2782 size = res + 1;
2783 else
2784 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002785 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002786 return res;
2787 }
2788 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002789 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002790}
2791
2792Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002793PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002794 wchar_t *w,
2795 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002796{
2797 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002798 PyErr_BadInternalCall();
2799 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002800 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002801 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002802}
2803
Victor Stinner137c34c2010-09-29 10:25:54 +00002804wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002805PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002806 Py_ssize_t *size)
2807{
2808 wchar_t* buffer;
2809 Py_ssize_t buflen;
2810
2811 if (unicode == NULL) {
2812 PyErr_BadInternalCall();
2813 return NULL;
2814 }
2815
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002816 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002817 if (buflen == -1)
2818 return NULL;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002819 buffer = PyMem_NEW(wchar_t, buflen);
Victor Stinner137c34c2010-09-29 10:25:54 +00002820 if (buffer == NULL) {
2821 PyErr_NoMemory();
2822 return NULL;
2823 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002824 buflen = unicode_aswidechar(unicode, buffer, buflen);
Stefan Krah8528c312012-08-19 21:52:43 +02002825 if (buflen == -1) {
2826 PyMem_FREE(buffer);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002827 return NULL;
Stefan Krah8528c312012-08-19 21:52:43 +02002828 }
Victor Stinner5593d8a2010-10-02 11:11:27 +00002829 if (size != NULL)
2830 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002831 return buffer;
2832}
2833
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002834#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002835
Alexander Belopolsky40018472011-02-26 01:02:56 +00002836PyObject *
2837PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002838{
Victor Stinner8faf8212011-12-08 22:14:11 +01002839 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002840 PyErr_SetString(PyExc_ValueError,
2841 "chr() arg not in range(0x110000)");
2842 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002843 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002844
Victor Stinner985a82a2014-01-03 12:53:47 +01002845 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002846}
2847
Alexander Belopolsky40018472011-02-26 01:02:56 +00002848PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002849PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002850{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002851 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002852 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002853 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05002854 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002855 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002856 Py_INCREF(obj);
2857 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002858 }
2859 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002860 /* For a Unicode subtype that's not a Unicode object,
2861 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002862 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002863 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002864 PyErr_Format(PyExc_TypeError,
2865 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002866 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002867 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002868}
2869
Alexander Belopolsky40018472011-02-26 01:02:56 +00002870PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02002871PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002872 const char *encoding,
2873 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002874{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002875 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002876 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002877
Guido van Rossumd57fd912000-03-10 22:53:23 +00002878 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002879 PyErr_BadInternalCall();
2880 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002881 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002882
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002883 /* Decoding bytes objects is the most common case and should be fast */
2884 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002885 if (PyBytes_GET_SIZE(obj) == 0)
2886 _Py_RETURN_UNICODE_EMPTY();
2887 v = PyUnicode_Decode(
2888 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2889 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002890 return v;
2891 }
2892
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002893 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002894 PyErr_SetString(PyExc_TypeError,
2895 "decoding str is not supported");
2896 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002897 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002898
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002899 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2900 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2901 PyErr_Format(PyExc_TypeError,
Serhiy Storchakab757c832014-12-05 22:25:22 +02002902 "coercing to str: need a bytes-like object, %.80s found",
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002903 Py_TYPE(obj)->tp_name);
2904 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002905 }
Tim Petersced69f82003-09-16 20:30:58 +00002906
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002907 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02002908 PyBuffer_Release(&buffer);
2909 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00002910 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002911
Serhiy Storchaka05997252013-01-26 12:14:02 +02002912 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002913 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002914 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002915}
2916
Victor Stinner600d3be2010-06-10 12:00:55 +00002917/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002918 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2919 1 on success. */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01002920int
2921_Py_normalize_encoding(const char *encoding,
2922 char *lower,
2923 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002924{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002925 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002926 char *l;
2927 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002928
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002929 if (encoding == NULL) {
Victor Stinner66b32702013-11-07 23:12:23 +01002930 /* 6 == strlen("utf-8") + 1 */
Victor Stinnerdf23e302013-11-07 13:33:36 +01002931 if (lower_len < 6)
2932 return 0;
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002933 strcpy(lower, "utf-8");
2934 return 1;
2935 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002936 e = encoding;
2937 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002938 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002939 while (*e) {
2940 if (l == l_end)
2941 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002942 if (Py_ISUPPER(*e)) {
2943 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002944 }
2945 else if (*e == '_') {
2946 *l++ = '-';
2947 e++;
2948 }
2949 else {
2950 *l++ = *e++;
2951 }
2952 }
2953 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002954 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002955}
2956
Alexander Belopolsky40018472011-02-26 01:02:56 +00002957PyObject *
2958PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002959 Py_ssize_t size,
2960 const char *encoding,
2961 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002962{
2963 PyObject *buffer = NULL, *unicode;
2964 Py_buffer info;
2965 char lower[11]; /* Enough for any encoding shortcut */
2966
Fred Drakee4315f52000-05-09 19:53:39 +00002967 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01002968 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002969 if ((strcmp(lower, "utf-8") == 0) ||
2970 (strcmp(lower, "utf8") == 0))
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002971 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
Victor Stinner37296e82010-06-10 13:36:23 +00002972 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002973 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01002974 (strcmp(lower, "iso-8859-1") == 0) ||
2975 (strcmp(lower, "iso8859-1") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00002976 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002977#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002978 else if (strcmp(lower, "mbcs") == 0)
2979 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002980#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002981 else if (strcmp(lower, "ascii") == 0)
2982 return PyUnicode_DecodeASCII(s, size, errors);
2983 else if (strcmp(lower, "utf-16") == 0)
2984 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2985 else if (strcmp(lower, "utf-32") == 0)
2986 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2987 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002988
2989 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002990 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002991 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002992 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002993 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002994 if (buffer == NULL)
2995 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10002996 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002997 if (unicode == NULL)
2998 goto onError;
2999 if (!PyUnicode_Check(unicode)) {
3000 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003001 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3002 "use codecs.decode() to decode to arbitrary types",
3003 encoding,
3004 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003005 Py_DECREF(unicode);
3006 goto onError;
3007 }
3008 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003009 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003010
Benjamin Peterson29060642009-01-31 22:14:21 +00003011 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003012 Py_XDECREF(buffer);
3013 return NULL;
3014}
3015
Alexander Belopolsky40018472011-02-26 01:02:56 +00003016PyObject *
3017PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003018 const char *encoding,
3019 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003020{
3021 PyObject *v;
3022
3023 if (!PyUnicode_Check(unicode)) {
3024 PyErr_BadArgument();
3025 goto onError;
3026 }
3027
3028 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003029 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003030
3031 /* Decode via the codec registry */
3032 v = PyCodec_Decode(unicode, encoding, errors);
3033 if (v == NULL)
3034 goto onError;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003035 return unicode_result(v);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003036
Benjamin Peterson29060642009-01-31 22:14:21 +00003037 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003038 return NULL;
3039}
3040
Alexander Belopolsky40018472011-02-26 01:02:56 +00003041PyObject *
3042PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003043 const char *encoding,
3044 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003045{
3046 PyObject *v;
3047
3048 if (!PyUnicode_Check(unicode)) {
3049 PyErr_BadArgument();
3050 goto onError;
3051 }
3052
3053 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003054 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003055
3056 /* Decode via the codec registry */
3057 v = PyCodec_Decode(unicode, encoding, errors);
3058 if (v == NULL)
3059 goto onError;
3060 if (!PyUnicode_Check(v)) {
3061 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003062 "'%.400s' decoder returned '%.400s' instead of 'str'; "
3063 "use codecs.decode() to decode to arbitrary types",
3064 encoding,
3065 Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003066 Py_DECREF(v);
3067 goto onError;
3068 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003069 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003070
Benjamin Peterson29060642009-01-31 22:14:21 +00003071 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003072 return NULL;
3073}
3074
Alexander Belopolsky40018472011-02-26 01:02:56 +00003075PyObject *
3076PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003077 Py_ssize_t size,
3078 const char *encoding,
3079 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003080{
3081 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003082
Guido van Rossumd57fd912000-03-10 22:53:23 +00003083 unicode = PyUnicode_FromUnicode(s, size);
3084 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003085 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003086 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3087 Py_DECREF(unicode);
3088 return v;
3089}
3090
Alexander Belopolsky40018472011-02-26 01:02:56 +00003091PyObject *
3092PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003093 const char *encoding,
3094 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003095{
3096 PyObject *v;
3097
3098 if (!PyUnicode_Check(unicode)) {
3099 PyErr_BadArgument();
3100 goto onError;
3101 }
3102
3103 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003104 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003105
3106 /* Encode via the codec registry */
3107 v = PyCodec_Encode(unicode, encoding, errors);
3108 if (v == NULL)
3109 goto onError;
3110 return v;
3111
Benjamin Peterson29060642009-01-31 22:14:21 +00003112 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003113 return NULL;
3114}
3115
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003116static size_t
3117wcstombs_errorpos(const wchar_t *wstr)
3118{
3119 size_t len;
3120#if SIZEOF_WCHAR_T == 2
3121 wchar_t buf[3];
3122#else
3123 wchar_t buf[2];
3124#endif
3125 char outbuf[MB_LEN_MAX];
3126 const wchar_t *start, *previous;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003127
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003128#if SIZEOF_WCHAR_T == 2
3129 buf[2] = 0;
3130#else
3131 buf[1] = 0;
3132#endif
3133 start = wstr;
3134 while (*wstr != L'\0')
3135 {
3136 previous = wstr;
3137#if SIZEOF_WCHAR_T == 2
3138 if (Py_UNICODE_IS_HIGH_SURROGATE(wstr[0])
3139 && Py_UNICODE_IS_LOW_SURROGATE(wstr[1]))
3140 {
3141 buf[0] = wstr[0];
3142 buf[1] = wstr[1];
3143 wstr += 2;
3144 }
3145 else {
3146 buf[0] = *wstr;
3147 buf[1] = 0;
3148 wstr++;
3149 }
3150#else
3151 buf[0] = *wstr;
3152 wstr++;
3153#endif
3154 len = wcstombs(outbuf, buf, sizeof(outbuf));
Victor Stinner2f197072011-12-17 07:08:30 +01003155 if (len == (size_t)-1)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003156 return previous - start;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003157 }
3158
3159 /* failed to find the unencodable character */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003160 return 0;
3161}
3162
Victor Stinner1b579672011-12-17 05:47:23 +01003163static int
3164locale_error_handler(const char *errors, int *surrogateescape)
3165{
3166 if (errors == NULL) {
3167 *surrogateescape = 0;
3168 return 0;
3169 }
3170
3171 if (strcmp(errors, "strict") == 0) {
3172 *surrogateescape = 0;
3173 return 0;
3174 }
Victor Stinner8dbd4212012-12-04 09:30:24 +01003175 if (strcmp(errors, "surrogateescape") == 0) {
Victor Stinner1b579672011-12-17 05:47:23 +01003176 *surrogateescape = 1;
3177 return 0;
3178 }
3179 PyErr_Format(PyExc_ValueError,
3180 "only 'strict' and 'surrogateescape' error handlers "
3181 "are supported, not '%s'",
3182 errors);
3183 return -1;
3184}
3185
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003186PyObject *
Victor Stinner1b579672011-12-17 05:47:23 +01003187PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003188{
3189 Py_ssize_t wlen, wlen2;
3190 wchar_t *wstr;
3191 PyObject *bytes = NULL;
3192 char *errmsg;
Raymond Hettingere56666d2013-08-04 11:51:03 -07003193 PyObject *reason = NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003194 PyObject *exc;
3195 size_t error_pos;
Victor Stinner1b579672011-12-17 05:47:23 +01003196 int surrogateescape;
3197
3198 if (locale_error_handler(errors, &surrogateescape) < 0)
3199 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003200
3201 wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3202 if (wstr == NULL)
3203 return NULL;
3204
3205 wlen2 = wcslen(wstr);
3206 if (wlen2 != wlen) {
3207 PyMem_Free(wstr);
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003208 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003209 return NULL;
3210 }
3211
3212 if (surrogateescape) {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003213 /* "surrogateescape" error handler */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003214 char *str;
3215
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003216 str = Py_EncodeLocale(wstr, &error_pos);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003217 if (str == NULL) {
3218 if (error_pos == (size_t)-1) {
3219 PyErr_NoMemory();
3220 PyMem_Free(wstr);
3221 return NULL;
3222 }
3223 else {
3224 goto encode_error;
3225 }
3226 }
3227 PyMem_Free(wstr);
3228
3229 bytes = PyBytes_FromString(str);
3230 PyMem_Free(str);
3231 }
3232 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003233 /* strict mode */
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003234 size_t len, len2;
3235
3236 len = wcstombs(NULL, wstr, 0);
3237 if (len == (size_t)-1) {
Victor Stinner2f197072011-12-17 07:08:30 +01003238 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003239 goto encode_error;
3240 }
3241
3242 bytes = PyBytes_FromStringAndSize(NULL, len);
3243 if (bytes == NULL) {
3244 PyMem_Free(wstr);
3245 return NULL;
3246 }
3247
3248 len2 = wcstombs(PyBytes_AS_STRING(bytes), wstr, len+1);
3249 if (len2 == (size_t)-1 || len2 > len) {
Victor Stinner2f197072011-12-17 07:08:30 +01003250 error_pos = (size_t)-1;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003251 goto encode_error;
3252 }
3253 PyMem_Free(wstr);
3254 }
3255 return bytes;
3256
3257encode_error:
3258 errmsg = strerror(errno);
3259 assert(errmsg != NULL);
Victor Stinner2f197072011-12-17 07:08:30 +01003260
3261 if (error_pos == (size_t)-1)
3262 error_pos = wcstombs_errorpos(wstr);
3263
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003264 PyMem_Free(wstr);
3265 Py_XDECREF(bytes);
3266
Victor Stinner2f197072011-12-17 07:08:30 +01003267 if (errmsg != NULL) {
3268 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003269 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003270 if (wstr != NULL) {
3271 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003272 PyMem_RawFree(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003273 } else
3274 errmsg = NULL;
3275 }
3276 if (errmsg == NULL)
Victor Stinner1f33f2b2011-12-17 04:45:09 +01003277 reason = PyUnicode_FromString(
3278 "wcstombs() encountered an unencodable "
3279 "wide character");
3280 if (reason == NULL)
3281 return NULL;
3282
3283 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnnO",
3284 "locale", unicode,
3285 (Py_ssize_t)error_pos,
3286 (Py_ssize_t)(error_pos+1),
3287 reason);
3288 Py_DECREF(reason);
3289 if (exc != NULL) {
3290 PyCodec_StrictErrors(exc);
3291 Py_XDECREF(exc);
3292 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003293 return NULL;
3294}
3295
Victor Stinnerad158722010-10-27 00:25:46 +00003296PyObject *
3297PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003298{
Victor Stinner99b95382011-07-04 14:23:54 +02003299#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003300 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003301#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003302 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003303#else
Victor Stinner793b5312011-04-27 00:24:21 +02003304 PyInterpreterState *interp = PyThreadState_GET()->interp;
3305 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3306 cannot use it to encode and decode filenames before it is loaded. Load
3307 the Python codec requires to encode at least its own filename. Use the C
3308 version of the locale codec until the codec registry is initialized and
3309 the Python codec is loaded.
3310
3311 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3312 cannot only rely on it: check also interp->fscodec_initialized for
3313 subinterpreters. */
3314 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003315 return PyUnicode_AsEncodedString(unicode,
3316 Py_FileSystemDefaultEncoding,
3317 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003318 }
3319 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003320 return PyUnicode_EncodeLocale(unicode, "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003321 }
Victor Stinnerad158722010-10-27 00:25:46 +00003322#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003323}
3324
Alexander Belopolsky40018472011-02-26 01:02:56 +00003325PyObject *
3326PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003327 const char *encoding,
3328 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003329{
3330 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003331 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003332
Guido van Rossumd57fd912000-03-10 22:53:23 +00003333 if (!PyUnicode_Check(unicode)) {
3334 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003335 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003336 }
Fred Drakee4315f52000-05-09 19:53:39 +00003337
Fred Drakee4315f52000-05-09 19:53:39 +00003338 /* Shortcuts for common default encodings */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003339 if (_Py_normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003340 if ((strcmp(lower, "utf-8") == 0) ||
3341 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003342 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003343 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003344 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003345 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003346 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003347 }
Victor Stinner37296e82010-06-10 13:36:23 +00003348 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003349 (strcmp(lower, "latin1") == 0) ||
Victor Stinnerfa3ba4c2013-10-29 11:34:05 +01003350 (strcmp(lower, "iso-8859-1") == 0) ||
3351 (strcmp(lower, "iso8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003352 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003353#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003354 else if (strcmp(lower, "mbcs") == 0)
3355 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003356#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003357 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003358 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003359 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003360
3361 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003362 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003363 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003364 return NULL;
3365
3366 /* The normal path */
3367 if (PyBytes_Check(v))
3368 return v;
3369
3370 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003371 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003372 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003373 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003374
3375 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003376 "encoder %s returned bytearray instead of bytes; "
3377 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003378 encoding);
3379 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003380 Py_DECREF(v);
3381 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003382 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003383
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003384 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3385 Py_DECREF(v);
3386 return b;
3387 }
3388
3389 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003390 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
3391 "use codecs.encode() to encode to arbitrary types",
3392 encoding,
3393 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003394 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003395 return NULL;
3396}
3397
Alexander Belopolsky40018472011-02-26 01:02:56 +00003398PyObject *
3399PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003400 const char *encoding,
3401 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003402{
3403 PyObject *v;
3404
3405 if (!PyUnicode_Check(unicode)) {
3406 PyErr_BadArgument();
3407 goto onError;
3408 }
3409
3410 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003411 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003412
3413 /* Encode via the codec registry */
3414 v = PyCodec_Encode(unicode, encoding, errors);
3415 if (v == NULL)
3416 goto onError;
3417 if (!PyUnicode_Check(v)) {
3418 PyErr_Format(PyExc_TypeError,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003419 "'%.400s' encoder returned '%.400s' instead of 'str'; "
3420 "use codecs.encode() to encode to arbitrary types",
3421 encoding,
3422 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003423 Py_DECREF(v);
3424 goto onError;
3425 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003426 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003427
Benjamin Peterson29060642009-01-31 22:14:21 +00003428 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003429 return NULL;
3430}
3431
Victor Stinner2f197072011-12-17 07:08:30 +01003432static size_t
3433mbstowcs_errorpos(const char *str, size_t len)
3434{
3435#ifdef HAVE_MBRTOWC
3436 const char *start = str;
3437 mbstate_t mbs;
3438 size_t converted;
3439 wchar_t ch;
3440
3441 memset(&mbs, 0, sizeof mbs);
3442 while (len)
3443 {
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03003444 converted = mbrtowc(&ch, str, len, &mbs);
Victor Stinner2f197072011-12-17 07:08:30 +01003445 if (converted == 0)
3446 /* Reached end of string */
3447 break;
3448 if (converted == (size_t)-1 || converted == (size_t)-2) {
3449 /* Conversion error or incomplete character */
3450 return str - start;
3451 }
3452 else {
3453 str += converted;
3454 len -= converted;
3455 }
3456 }
3457 /* failed to find the undecodable byte sequence */
3458 return 0;
3459#endif
3460 return 0;
3461}
3462
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003463PyObject*
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003464PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
Victor Stinner1b579672011-12-17 05:47:23 +01003465 const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003466{
3467 wchar_t smallbuf[256];
3468 size_t smallbuf_len = Py_ARRAY_LENGTH(smallbuf);
3469 wchar_t *wstr;
3470 size_t wlen, wlen2;
3471 PyObject *unicode;
Victor Stinner1b579672011-12-17 05:47:23 +01003472 int surrogateescape;
Victor Stinner2f197072011-12-17 07:08:30 +01003473 size_t error_pos;
3474 char *errmsg;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01003475 PyObject *reason = NULL; /* initialize to prevent gcc warning */
3476 PyObject *exc;
Victor Stinner1b579672011-12-17 05:47:23 +01003477
3478 if (locale_error_handler(errors, &surrogateescape) < 0)
3479 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003480
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003481 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3482 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003483 return NULL;
3484 }
3485
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003486 if (surrogateescape) {
3487 /* "surrogateescape" error handler */
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003488 wstr = Py_DecodeLocale(str, &wlen);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003489 if (wstr == NULL) {
3490 if (wlen == (size_t)-1)
3491 PyErr_NoMemory();
3492 else
3493 PyErr_SetFromErrno(PyExc_OSError);
3494 return NULL;
3495 }
3496
3497 unicode = PyUnicode_FromWideChar(wstr, wlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003498 PyMem_RawFree(wstr);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003499 }
3500 else {
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003501 /* strict mode */
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003502#ifndef HAVE_BROKEN_MBSTOWCS
3503 wlen = mbstowcs(NULL, str, 0);
3504#else
3505 wlen = len;
3506#endif
Victor Stinner2f197072011-12-17 07:08:30 +01003507 if (wlen == (size_t)-1)
3508 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003509 if (wlen+1 <= smallbuf_len) {
3510 wstr = smallbuf;
3511 }
3512 else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003513 wstr = PyMem_New(wchar_t, wlen+1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003514 if (!wstr)
3515 return PyErr_NoMemory();
3516 }
3517
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003518 wlen2 = mbstowcs(wstr, str, wlen+1);
3519 if (wlen2 == (size_t)-1) {
3520 if (wstr != smallbuf)
3521 PyMem_Free(wstr);
Victor Stinner2f197072011-12-17 07:08:30 +01003522 goto decode_error;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003523 }
3524#ifdef HAVE_BROKEN_MBSTOWCS
3525 assert(wlen2 == wlen);
3526#endif
3527 unicode = PyUnicode_FromWideChar(wstr, wlen2);
3528 if (wstr != smallbuf)
3529 PyMem_Free(wstr);
3530 }
3531 return unicode;
Victor Stinner2f197072011-12-17 07:08:30 +01003532
3533decode_error:
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003534 reason = NULL;
Victor Stinner2f197072011-12-17 07:08:30 +01003535 errmsg = strerror(errno);
3536 assert(errmsg != NULL);
3537
3538 error_pos = mbstowcs_errorpos(str, len);
3539 if (errmsg != NULL) {
3540 size_t errlen;
Victor Stinnerf6a271a2014-08-01 12:28:48 +02003541 wstr = Py_DecodeLocale(errmsg, &errlen);
Victor Stinner2f197072011-12-17 07:08:30 +01003542 if (wstr != NULL) {
3543 reason = PyUnicode_FromWideChar(wstr, errlen);
Victor Stinner1a7425f2013-07-07 16:25:15 +02003544 PyMem_RawFree(wstr);
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003545 }
Victor Stinner2f197072011-12-17 07:08:30 +01003546 }
Antoine Pitrouf6d1f1f2015-05-19 21:04:33 +02003547 if (reason == NULL)
Victor Stinner2f197072011-12-17 07:08:30 +01003548 reason = PyUnicode_FromString(
3549 "mbstowcs() encountered an invalid multibyte sequence");
3550 if (reason == NULL)
3551 return NULL;
3552
3553 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nnO",
3554 "locale", str, len,
3555 (Py_ssize_t)error_pos,
3556 (Py_ssize_t)(error_pos+1),
3557 reason);
3558 Py_DECREF(reason);
3559 if (exc != NULL) {
3560 PyCodec_StrictErrors(exc);
3561 Py_XDECREF(exc);
3562 }
3563 return NULL;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003564}
3565
3566PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003567PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003568{
3569 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner1b579672011-12-17 05:47:23 +01003570 return PyUnicode_DecodeLocaleAndSize(str, size, errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003571}
3572
3573
3574PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003575PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003576 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003577 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3578}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003579
Christian Heimes5894ba72007-11-04 11:43:14 +00003580PyObject*
3581PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3582{
Victor Stinner99b95382011-07-04 14:23:54 +02003583#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003584 return PyUnicode_DecodeMBCS(s, size, NULL);
3585#elif defined(__APPLE__)
Victor Stinnera1d12bb2011-12-11 21:53:09 +01003586 return PyUnicode_DecodeUTF8Stateful(s, size, "surrogateescape", NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003587#else
Victor Stinner793b5312011-04-27 00:24:21 +02003588 PyInterpreterState *interp = PyThreadState_GET()->interp;
3589 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3590 cannot use it to encode and decode filenames before it is loaded. Load
3591 the Python codec requires to encode at least its own filename. Use the C
3592 version of the locale codec until the codec registry is initialized and
3593 the Python codec is loaded.
3594
3595 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3596 cannot only rely on it: check also interp->fscodec_initialized for
3597 subinterpreters. */
3598 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003599 return PyUnicode_Decode(s, size,
3600 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003601 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003602 }
3603 else {
Victor Stinner1b579672011-12-17 05:47:23 +01003604 return PyUnicode_DecodeLocaleAndSize(s, size, "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003605 }
Victor Stinnerad158722010-10-27 00:25:46 +00003606#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003607}
3608
Martin v. Löwis011e8422009-05-05 04:43:17 +00003609
3610int
3611PyUnicode_FSConverter(PyObject* arg, void* addr)
3612{
3613 PyObject *output = NULL;
3614 Py_ssize_t size;
3615 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003616 if (arg == NULL) {
3617 Py_DECREF(*(PyObject**)addr);
3618 return 1;
3619 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003620 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003621 output = arg;
3622 Py_INCREF(output);
3623 }
3624 else {
3625 arg = PyUnicode_FromObject(arg);
3626 if (!arg)
3627 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003628 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003629 Py_DECREF(arg);
3630 if (!output)
3631 return 0;
3632 if (!PyBytes_Check(output)) {
3633 Py_DECREF(output);
3634 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3635 return 0;
3636 }
3637 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003638 size = PyBytes_GET_SIZE(output);
3639 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003640 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003641 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003642 Py_DECREF(output);
3643 return 0;
3644 }
3645 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003646 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003647}
3648
3649
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003650int
3651PyUnicode_FSDecoder(PyObject* arg, void* addr)
3652{
3653 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003654 if (arg == NULL) {
3655 Py_DECREF(*(PyObject**)addr);
3656 return 1;
3657 }
3658 if (PyUnicode_Check(arg)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003659 if (PyUnicode_READY(arg) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003660 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003661 output = arg;
3662 Py_INCREF(output);
3663 }
3664 else {
3665 arg = PyBytes_FromObject(arg);
3666 if (!arg)
3667 return 0;
3668 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3669 PyBytes_GET_SIZE(arg));
3670 Py_DECREF(arg);
3671 if (!output)
3672 return 0;
3673 if (!PyUnicode_Check(output)) {
3674 Py_DECREF(output);
3675 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3676 return 0;
3677 }
3678 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003679 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003680 Py_DECREF(output);
3681 return 0;
3682 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003683 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003684 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003685 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003686 Py_DECREF(output);
3687 return 0;
3688 }
3689 *(PyObject**)addr = output;
3690 return Py_CLEANUP_SUPPORTED;
3691}
3692
3693
Martin v. Löwis5b222132007-06-10 09:51:05 +00003694char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003695PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003696{
Christian Heimesf3863112007-11-22 07:46:41 +00003697 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003698
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003699 if (!PyUnicode_Check(unicode)) {
3700 PyErr_BadArgument();
3701 return NULL;
3702 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003703 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003704 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003705
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003706 if (PyUnicode_UTF8(unicode) == NULL) {
3707 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003708 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3709 if (bytes == NULL)
3710 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003711 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3712 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003713 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003714 Py_DECREF(bytes);
3715 return NULL;
3716 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003717 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3718 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3719 PyBytes_AS_STRING(bytes),
3720 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003721 Py_DECREF(bytes);
3722 }
3723
3724 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003725 *psize = PyUnicode_UTF8_LENGTH(unicode);
3726 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003727}
3728
3729char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003730PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003731{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003732 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3733}
3734
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003735Py_UNICODE *
3736PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3737{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003738 const unsigned char *one_byte;
3739#if SIZEOF_WCHAR_T == 4
3740 const Py_UCS2 *two_bytes;
3741#else
3742 const Py_UCS4 *four_bytes;
3743 const Py_UCS4 *ucs4_end;
3744 Py_ssize_t num_surrogates;
3745#endif
3746 wchar_t *w;
3747 wchar_t *wchar_end;
3748
3749 if (!PyUnicode_Check(unicode)) {
3750 PyErr_BadArgument();
3751 return NULL;
3752 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003753 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003754 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003755 assert(_PyUnicode_KIND(unicode) != 0);
3756 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003757
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003758 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003759#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003760 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3761 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003762 num_surrogates = 0;
3763
3764 for (; four_bytes < ucs4_end; ++four_bytes) {
3765 if (*four_bytes > 0xFFFF)
3766 ++num_surrogates;
3767 }
3768
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003769 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3770 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3771 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003772 PyErr_NoMemory();
3773 return NULL;
3774 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003775 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003776
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003777 w = _PyUnicode_WSTR(unicode);
3778 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3779 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003780 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3781 if (*four_bytes > 0xFFFF) {
Victor Stinner8faf8212011-12-08 22:14:11 +01003782 assert(*four_bytes <= MAX_UNICODE);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003783 /* encode surrogate pair in this case */
Victor Stinner551ac952011-11-29 22:58:13 +01003784 *w++ = Py_UNICODE_HIGH_SURROGATE(*four_bytes);
3785 *w = Py_UNICODE_LOW_SURROGATE(*four_bytes);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003786 }
3787 else
3788 *w = *four_bytes;
3789
3790 if (w > wchar_end) {
3791 assert(0 && "Miscalculated string end");
3792 }
3793 }
3794 *w = 0;
3795#else
3796 /* sizeof(wchar_t) == 4 */
3797 Py_FatalError("Impossible unicode object state, wstr and str "
3798 "should share memory already.");
3799 return NULL;
3800#endif
3801 }
3802 else {
Serhiy Storchakae55181f2015-02-20 21:34:06 +02003803 if ((size_t)_PyUnicode_LENGTH(unicode) >
3804 PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
3805 PyErr_NoMemory();
3806 return NULL;
3807 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003808 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3809 (_PyUnicode_LENGTH(unicode) + 1));
3810 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003811 PyErr_NoMemory();
3812 return NULL;
3813 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003814 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3815 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3816 w = _PyUnicode_WSTR(unicode);
3817 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003818
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003819 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3820 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003821 for (; w < wchar_end; ++one_byte, ++w)
3822 *w = *one_byte;
3823 /* null-terminate the wstr */
3824 *w = 0;
3825 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003826 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003827#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003828 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003829 for (; w < wchar_end; ++two_bytes, ++w)
3830 *w = *two_bytes;
3831 /* null-terminate the wstr */
3832 *w = 0;
3833#else
3834 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003835 PyObject_FREE(_PyUnicode_WSTR(unicode));
3836 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003837 Py_FatalError("Impossible unicode object state, wstr "
3838 "and str should share memory already.");
3839 return NULL;
3840#endif
3841 }
3842 else {
3843 assert(0 && "This should never happen.");
3844 }
3845 }
3846 }
3847 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003848 *size = PyUnicode_WSTR_LENGTH(unicode);
3849 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003850}
3851
Alexander Belopolsky40018472011-02-26 01:02:56 +00003852Py_UNICODE *
3853PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003854{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003855 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003856}
3857
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003858
Alexander Belopolsky40018472011-02-26 01:02:56 +00003859Py_ssize_t
3860PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003861{
3862 if (!PyUnicode_Check(unicode)) {
3863 PyErr_BadArgument();
3864 goto onError;
3865 }
3866 return PyUnicode_GET_SIZE(unicode);
3867
Benjamin Peterson29060642009-01-31 22:14:21 +00003868 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003869 return -1;
3870}
3871
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003872Py_ssize_t
3873PyUnicode_GetLength(PyObject *unicode)
3874{
Victor Stinner07621332012-06-16 04:53:46 +02003875 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003876 PyErr_BadArgument();
3877 return -1;
3878 }
Victor Stinner07621332012-06-16 04:53:46 +02003879 if (PyUnicode_READY(unicode) == -1)
3880 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003881 return PyUnicode_GET_LENGTH(unicode);
3882}
3883
3884Py_UCS4
3885PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3886{
Victor Stinner69ed0f42013-04-09 21:48:24 +02003887 void *data;
3888 int kind;
3889
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003890 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3891 PyErr_BadArgument();
3892 return (Py_UCS4)-1;
3893 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003894 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003895 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003896 return (Py_UCS4)-1;
3897 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02003898 data = PyUnicode_DATA(unicode);
3899 kind = PyUnicode_KIND(unicode);
3900 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003901}
3902
3903int
3904PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3905{
3906 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003907 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003908 return -1;
3909 }
Victor Stinner488fa492011-12-12 00:01:39 +01003910 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01003911 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003912 PyErr_SetString(PyExc_IndexError, "string index out of range");
3913 return -1;
3914 }
Victor Stinner488fa492011-12-12 00:01:39 +01003915 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02003916 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01003917 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
3918 PyErr_SetString(PyExc_ValueError, "character out of range");
3919 return -1;
3920 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003921 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3922 index, ch);
3923 return 0;
3924}
3925
Alexander Belopolsky40018472011-02-26 01:02:56 +00003926const char *
3927PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003928{
Victor Stinner42cb4622010-09-01 19:39:01 +00003929 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003930}
3931
Victor Stinner554f3f02010-06-16 23:33:54 +00003932/* create or adjust a UnicodeDecodeError */
3933static void
3934make_decode_exception(PyObject **exceptionObject,
3935 const char *encoding,
3936 const char *input, Py_ssize_t length,
3937 Py_ssize_t startpos, Py_ssize_t endpos,
3938 const char *reason)
3939{
3940 if (*exceptionObject == NULL) {
3941 *exceptionObject = PyUnicodeDecodeError_Create(
3942 encoding, input, length, startpos, endpos, reason);
3943 }
3944 else {
3945 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3946 goto onError;
3947 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3948 goto onError;
3949 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3950 goto onError;
3951 }
3952 return;
3953
3954onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02003955 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00003956}
3957
Victor Stinnerfc009ef2012-11-07 00:36:38 +01003958#ifdef HAVE_MBCS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003959/* error handling callback helper:
3960 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003961 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003962 and adjust various state variables.
3963 return 0 on success, -1 on error
3964*/
3965
Alexander Belopolsky40018472011-02-26 01:02:56 +00003966static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01003967unicode_decode_call_errorhandler_wchar(
3968 const char *errors, PyObject **errorHandler,
3969 const char *encoding, const char *reason,
3970 const char **input, const char **inend, Py_ssize_t *startinpos,
3971 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
3972 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003973{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003974 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003975
3976 PyObject *restuple = NULL;
3977 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01003978 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003979 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003980 Py_ssize_t requiredsize;
3981 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003982 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01003983 wchar_t *repwstr;
3984 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003985
Victor Stinnerfc009ef2012-11-07 00:36:38 +01003986 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
3987 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01003988
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003989 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003990 *errorHandler = PyCodec_LookupError(errors);
3991 if (*errorHandler == NULL)
3992 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003993 }
3994
Victor Stinner554f3f02010-06-16 23:33:54 +00003995 make_decode_exception(exceptionObject,
3996 encoding,
3997 *input, *inend - *input,
3998 *startinpos, *endinpos,
3999 reason);
4000 if (*exceptionObject == NULL)
4001 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004002
4003 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4004 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004005 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004006 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00004007 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004008 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004009 }
4010 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004011 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004012
4013 /* Copy back the bytes variables, which might have been modified by the
4014 callback */
4015 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4016 if (!inputobj)
4017 goto onError;
4018 if (!PyBytes_Check(inputobj)) {
4019 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
4020 }
4021 *input = PyBytes_AS_STRING(inputobj);
4022 insize = PyBytes_GET_SIZE(inputobj);
4023 *inend = *input + insize;
4024 /* we can DECREF safely, as the exception has another reference,
4025 so the object won't go away. */
4026 Py_DECREF(inputobj);
4027
4028 if (newpos<0)
4029 newpos = insize+newpos;
4030 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004031 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004032 goto onError;
4033 }
4034
4035 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4036 if (repwstr == NULL)
4037 goto onError;
4038 /* need more space? (at least enough for what we
4039 have+the replacement+the rest of the string (starting
4040 at the new input position), so we won't have to check space
4041 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004042 requiredsize = *outpos;
4043 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4044 goto overflow;
4045 requiredsize += repwlen;
4046 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4047 goto overflow;
4048 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004049 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004050 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004051 requiredsize = 2*outsize;
4052 if (unicode_resize(output, requiredsize) < 0)
4053 goto onError;
4054 }
4055 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4056 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004057 *endinpos = newpos;
4058 *inptr = *input + newpos;
4059
4060 /* we made it! */
4061 Py_XDECREF(restuple);
4062 return 0;
4063
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004064 overflow:
4065 PyErr_SetString(PyExc_OverflowError,
4066 "decoded result is too long for a Python string");
4067
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004068 onError:
4069 Py_XDECREF(restuple);
4070 return -1;
4071}
4072#endif /* HAVE_MBCS */
4073
4074static int
4075unicode_decode_call_errorhandler_writer(
4076 const char *errors, PyObject **errorHandler,
4077 const char *encoding, const char *reason,
4078 const char **input, const char **inend, Py_ssize_t *startinpos,
4079 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4080 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4081{
4082 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
4083
4084 PyObject *restuple = NULL;
4085 PyObject *repunicode = NULL;
4086 Py_ssize_t insize;
4087 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004088 Py_ssize_t replen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004089 PyObject *inputobj = NULL;
4090
4091 if (*errorHandler == NULL) {
4092 *errorHandler = PyCodec_LookupError(errors);
4093 if (*errorHandler == NULL)
4094 goto onError;
4095 }
4096
4097 make_decode_exception(exceptionObject,
4098 encoding,
4099 *input, *inend - *input,
4100 *startinpos, *endinpos,
4101 reason);
4102 if (*exceptionObject == NULL)
4103 goto onError;
4104
4105 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
4106 if (restuple == NULL)
4107 goto onError;
4108 if (!PyTuple_Check(restuple)) {
4109 PyErr_SetString(PyExc_TypeError, &argparse[4]);
4110 goto onError;
4111 }
4112 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004113 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004114
4115 /* Copy back the bytes variables, which might have been modified by the
4116 callback */
4117 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4118 if (!inputobj)
4119 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00004120 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004121 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00004122 }
Christian Heimes72b710a2008-05-26 13:28:38 +00004123 *input = PyBytes_AS_STRING(inputobj);
4124 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004125 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004126 /* we can DECREF safely, as the exception has another reference,
4127 so the object won't go away. */
4128 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004129
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004130 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004131 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004132 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004133 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004134 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004135 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004136
Victor Stinner8f674cc2013-04-17 23:02:17 +02004137 if (PyUnicode_READY(repunicode) < 0)
4138 goto onError;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004139 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004140 if (replen > 1) {
4141 writer->min_length += replen - 1;
Victor Stinner8f674cc2013-04-17 23:02:17 +02004142 writer->overallocate = 1;
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004143 if (_PyUnicodeWriter_Prepare(writer, writer->min_length,
4144 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4145 goto onError;
4146 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004147 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004148 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004149
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004150 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004151 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004152
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004153 /* we made it! */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004154 Py_XDECREF(restuple);
4155 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004156
Benjamin Peterson29060642009-01-31 22:14:21 +00004157 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004158 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004159 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004160}
4161
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004162/* --- UTF-7 Codec -------------------------------------------------------- */
4163
Antoine Pitrou244651a2009-05-04 18:56:13 +00004164/* See RFC2152 for details. We encode conservatively and decode liberally. */
4165
4166/* Three simple macros defining base-64. */
4167
4168/* Is c a base-64 character? */
4169
4170#define IS_BASE64(c) \
4171 (((c) >= 'A' && (c) <= 'Z') || \
4172 ((c) >= 'a' && (c) <= 'z') || \
4173 ((c) >= '0' && (c) <= '9') || \
4174 (c) == '+' || (c) == '/')
4175
4176/* given that c is a base-64 character, what is its base-64 value? */
4177
4178#define FROM_BASE64(c) \
4179 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4180 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4181 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4182 (c) == '+' ? 62 : 63)
4183
4184/* What is the base-64 character of the bottom 6 bits of n? */
4185
4186#define TO_BASE64(n) \
4187 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4188
4189/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4190 * decoded as itself. We are permissive on decoding; the only ASCII
4191 * byte not decoding to itself is the + which begins a base64
4192 * string. */
4193
4194#define DECODE_DIRECT(c) \
4195 ((c) <= 127 && (c) != '+')
4196
4197/* The UTF-7 encoder treats ASCII characters differently according to
4198 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4199 * the above). See RFC2152. This array identifies these different
4200 * sets:
4201 * 0 : "Set D"
4202 * alphanumeric and '(),-./:?
4203 * 1 : "Set O"
4204 * !"#$%&*;<=>@[]^_`{|}
4205 * 2 : "whitespace"
4206 * ht nl cr sp
4207 * 3 : special (must be base64 encoded)
4208 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4209 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004210
Tim Petersced69f82003-09-16 20:30:58 +00004211static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004212char utf7_category[128] = {
4213/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4214 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4215/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4216 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4217/* sp ! " # $ % & ' ( ) * + , - . / */
4218 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4219/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4220 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4221/* @ A B C D E F G H I J K L M N O */
4222 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4223/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4224 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4225/* ` a b c d e f g h i j k l m n o */
4226 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4227/* p q r s t u v w x y z { | } ~ del */
4228 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004229};
4230
Antoine Pitrou244651a2009-05-04 18:56:13 +00004231/* ENCODE_DIRECT: this character should be encoded as itself. The
4232 * answer depends on whether we are encoding set O as itself, and also
4233 * on whether we are encoding whitespace as itself. RFC2152 makes it
4234 * clear that the answers to these questions vary between
4235 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004236
Antoine Pitrou244651a2009-05-04 18:56:13 +00004237#define ENCODE_DIRECT(c, directO, directWS) \
4238 ((c) < 128 && (c) > 0 && \
4239 ((utf7_category[(c)] == 0) || \
4240 (directWS && (utf7_category[(c)] == 2)) || \
4241 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004242
Alexander Belopolsky40018472011-02-26 01:02:56 +00004243PyObject *
4244PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004245 Py_ssize_t size,
4246 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004247{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004248 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4249}
4250
Antoine Pitrou244651a2009-05-04 18:56:13 +00004251/* The decoder. The only state we preserve is our read position,
4252 * i.e. how many characters we have consumed. So if we end in the
4253 * middle of a shift sequence we have to back off the read position
4254 * and the output to the beginning of the sequence, otherwise we lose
4255 * all the shift state (seen bits, number of bits seen, high
4256 * surrogate). */
4257
Alexander Belopolsky40018472011-02-26 01:02:56 +00004258PyObject *
4259PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004260 Py_ssize_t size,
4261 const char *errors,
4262 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004263{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004264 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004265 Py_ssize_t startinpos;
4266 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004267 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004268 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004269 const char *errmsg = "";
4270 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004271 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004272 unsigned int base64bits = 0;
4273 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004274 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004275 PyObject *errorHandler = NULL;
4276 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004277
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004278 if (size == 0) {
4279 if (consumed)
4280 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004281 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004282 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004283
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004284 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004285 _PyUnicodeWriter_Init(&writer);
4286 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004287
4288 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004289 e = s + size;
4290
4291 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004292 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004293 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004294 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004295
Antoine Pitrou244651a2009-05-04 18:56:13 +00004296 if (inShift) { /* in a base-64 section */
4297 if (IS_BASE64(ch)) { /* consume a base-64 character */
4298 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4299 base64bits += 6;
4300 s++;
4301 if (base64bits >= 16) {
4302 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004303 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004304 base64bits -= 16;
4305 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004306 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004307 if (surrogate) {
4308 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004309 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4310 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004311 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004312 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004313 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004314 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004315 }
4316 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004317 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004318 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004319 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004320 }
4321 }
Victor Stinner551ac952011-11-29 22:58:13 +01004322 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004323 /* first surrogate */
4324 surrogate = outCh;
4325 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004326 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004327 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004328 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004329 }
4330 }
4331 }
4332 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004333 inShift = 0;
4334 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004335 if (surrogate) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004336 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004337 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004338 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004339 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004340 if (base64bits > 0) { /* left-over bits */
4341 if (base64bits >= 6) {
4342 /* We've seen at least one base-64 character */
4343 errmsg = "partial character in shift sequence";
4344 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004345 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004346 else {
4347 /* Some bits remain; they should be zero */
4348 if (base64buffer != 0) {
4349 errmsg = "non-zero padding bits in shift sequence";
4350 goto utf7Error;
4351 }
4352 }
4353 }
4354 if (ch != '-') {
4355 /* '-' is absorbed; other terminating
4356 characters are preserved */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004357 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004358 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004359 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004360 }
4361 }
4362 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004363 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004364 s++; /* consume '+' */
4365 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004366 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004367 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004368 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004369 }
4370 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004371 inShift = 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004372 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004373 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004374 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004375 }
4376 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004377 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004378 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004379 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004380 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004381 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004382 else {
4383 startinpos = s-starts;
4384 s++;
4385 errmsg = "unexpected special character";
4386 goto utf7Error;
4387 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004388 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004389utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004390 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004391 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004392 errors, &errorHandler,
4393 "utf7", errmsg,
4394 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004395 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004396 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004397 }
4398
Antoine Pitrou244651a2009-05-04 18:56:13 +00004399 /* end of string */
4400
4401 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4402 /* if we're in an inconsistent state, that's an error */
4403 if (surrogate ||
4404 (base64bits >= 6) ||
4405 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004406 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004407 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004408 errors, &errorHandler,
4409 "utf7", "unterminated shift sequence",
4410 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004411 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004412 goto onError;
4413 if (s < e)
4414 goto restart;
4415 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004416 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004417
4418 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004419 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004420 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004421 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004422 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004423 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004424 writer.kind, writer.data, shiftOutStart);
4425 Py_XDECREF(errorHandler);
4426 Py_XDECREF(exc);
4427 _PyUnicodeWriter_Dealloc(&writer);
4428 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004429 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004430 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004431 }
4432 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004433 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004434 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004435 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004436
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004437 Py_XDECREF(errorHandler);
4438 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004439 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004440
Benjamin Peterson29060642009-01-31 22:14:21 +00004441 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004442 Py_XDECREF(errorHandler);
4443 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004444 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004445 return NULL;
4446}
4447
4448
Alexander Belopolsky40018472011-02-26 01:02:56 +00004449PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004450_PyUnicode_EncodeUTF7(PyObject *str,
4451 int base64SetO,
4452 int base64WhiteSpace,
4453 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004454{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004455 int kind;
4456 void *data;
4457 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004458 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004459 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004460 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004461 unsigned int base64bits = 0;
4462 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004463 char * out;
4464 char * start;
4465
Benjamin Petersonbac79492012-01-14 13:34:47 -05004466 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004467 return NULL;
4468 kind = PyUnicode_KIND(str);
4469 data = PyUnicode_DATA(str);
4470 len = PyUnicode_GET_LENGTH(str);
4471
4472 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004473 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004474
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004475 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004476 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004477 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004478 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004479 if (v == NULL)
4480 return NULL;
4481
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004482 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004483 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004484 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004485
Antoine Pitrou244651a2009-05-04 18:56:13 +00004486 if (inShift) {
4487 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4488 /* shifting out */
4489 if (base64bits) { /* output remaining bits */
4490 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4491 base64buffer = 0;
4492 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004493 }
4494 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004495 /* Characters not in the BASE64 set implicitly unshift the sequence
4496 so no '-' is required, except if the character is itself a '-' */
4497 if (IS_BASE64(ch) || ch == '-') {
4498 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004499 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004500 *out++ = (char) ch;
4501 }
4502 else {
4503 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004504 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004505 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004506 else { /* not in a shift sequence */
4507 if (ch == '+') {
4508 *out++ = '+';
4509 *out++ = '-';
4510 }
4511 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4512 *out++ = (char) ch;
4513 }
4514 else {
4515 *out++ = '+';
4516 inShift = 1;
4517 goto encode_char;
4518 }
4519 }
4520 continue;
4521encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004522 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004523 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004524
Antoine Pitrou244651a2009-05-04 18:56:13 +00004525 /* code first surrogate */
4526 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004527 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004528 while (base64bits >= 6) {
4529 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4530 base64bits -= 6;
4531 }
4532 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004533 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004534 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004535 base64bits += 16;
4536 base64buffer = (base64buffer << 16) | ch;
4537 while (base64bits >= 6) {
4538 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4539 base64bits -= 6;
4540 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004541 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004542 if (base64bits)
4543 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4544 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004545 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004546 if (_PyBytes_Resize(&v, out - start) < 0)
4547 return NULL;
4548 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004549}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004550PyObject *
4551PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4552 Py_ssize_t size,
4553 int base64SetO,
4554 int base64WhiteSpace,
4555 const char *errors)
4556{
4557 PyObject *result;
4558 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4559 if (tmp == NULL)
4560 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004561 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004562 base64WhiteSpace, errors);
4563 Py_DECREF(tmp);
4564 return result;
4565}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004566
Antoine Pitrou244651a2009-05-04 18:56:13 +00004567#undef IS_BASE64
4568#undef FROM_BASE64
4569#undef TO_BASE64
4570#undef DECODE_DIRECT
4571#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004572
Guido van Rossumd57fd912000-03-10 22:53:23 +00004573/* --- UTF-8 Codec -------------------------------------------------------- */
4574
Alexander Belopolsky40018472011-02-26 01:02:56 +00004575PyObject *
4576PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004577 Py_ssize_t size,
4578 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004579{
Walter Dörwald69652032004-09-07 20:24:22 +00004580 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4581}
4582
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004583#include "stringlib/asciilib.h"
4584#include "stringlib/codecs.h"
4585#include "stringlib/undef.h"
4586
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004587#include "stringlib/ucs1lib.h"
4588#include "stringlib/codecs.h"
4589#include "stringlib/undef.h"
4590
4591#include "stringlib/ucs2lib.h"
4592#include "stringlib/codecs.h"
4593#include "stringlib/undef.h"
4594
4595#include "stringlib/ucs4lib.h"
4596#include "stringlib/codecs.h"
4597#include "stringlib/undef.h"
4598
Antoine Pitrouab868312009-01-10 15:40:25 +00004599/* Mask to quickly check whether a C 'long' contains a
4600 non-ASCII, UTF8-encoded char. */
4601#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004602# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004603#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004604# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004605#else
4606# error C 'long' size should be either 4 or 8!
4607#endif
4608
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004609static Py_ssize_t
4610ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004611{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004612 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004613 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004614
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004615 /*
4616 * Issue #17237: m68k is a bit different from most architectures in
4617 * that objects do not use "natural alignment" - for example, int and
4618 * long are only aligned at 2-byte boundaries. Therefore the assert()
4619 * won't work; also, tests have shown that skipping the "optimised
4620 * version" will even speed up m68k.
4621 */
4622#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004623#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004624 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4625 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004626 /* Fast path, see in STRINGLIB(utf8_decode) for
4627 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004628 /* Help allocation */
4629 const char *_p = p;
4630 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004631 while (_p < aligned_end) {
4632 unsigned long value = *(const unsigned long *) _p;
4633 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004634 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004635 *((unsigned long *)q) = value;
4636 _p += SIZEOF_LONG;
4637 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004638 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004639 p = _p;
4640 while (p < end) {
4641 if ((unsigned char)*p & 0x80)
4642 break;
4643 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004644 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004645 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004646 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004647#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004648#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004649 while (p < end) {
4650 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4651 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004652 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004653 /* Help allocation */
4654 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004655 while (_p < aligned_end) {
4656 unsigned long value = *(unsigned long *) _p;
4657 if (value & ASCII_CHAR_MASK)
4658 break;
4659 _p += SIZEOF_LONG;
4660 }
4661 p = _p;
4662 if (_p == end)
4663 break;
4664 }
4665 if ((unsigned char)*p & 0x80)
4666 break;
4667 ++p;
4668 }
4669 memcpy(dest, start, p - start);
4670 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004671}
Antoine Pitrouab868312009-01-10 15:40:25 +00004672
Victor Stinner785938e2011-12-11 20:09:03 +01004673PyObject *
4674PyUnicode_DecodeUTF8Stateful(const char *s,
4675 Py_ssize_t size,
4676 const char *errors,
4677 Py_ssize_t *consumed)
4678{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004679 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004680 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004681 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004682
4683 Py_ssize_t startinpos;
4684 Py_ssize_t endinpos;
4685 const char *errmsg = "";
4686 PyObject *errorHandler = NULL;
4687 PyObject *exc = NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004688
4689 if (size == 0) {
4690 if (consumed)
4691 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004692 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004693 }
4694
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004695 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4696 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004697 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004698 *consumed = 1;
4699 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004700 }
4701
Victor Stinner8f674cc2013-04-17 23:02:17 +02004702 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004703 writer.min_length = size;
4704 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004705 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004706
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004707 writer.pos = ascii_decode(s, end, writer.data);
4708 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004709 while (s < end) {
4710 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004711 int kind = writer.kind;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004712 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004713 if (PyUnicode_IS_ASCII(writer.buffer))
4714 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004715 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004716 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004717 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004718 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004719 } else {
4720 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004721 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004722 }
4723
4724 switch (ch) {
4725 case 0:
4726 if (s == end || consumed)
4727 goto End;
4728 errmsg = "unexpected end of data";
4729 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004730 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004731 break;
4732 case 1:
4733 errmsg = "invalid start byte";
4734 startinpos = s - starts;
4735 endinpos = startinpos + 1;
4736 break;
4737 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004738 case 3:
4739 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004740 errmsg = "invalid continuation byte";
4741 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004742 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004743 break;
4744 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004745 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004746 goto onError;
4747 continue;
4748 }
4749
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004750 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004751 errors, &errorHandler,
4752 "utf-8", errmsg,
4753 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004754 &writer))
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004755 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004756 }
4757
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004758End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004759 if (consumed)
4760 *consumed = s - starts;
4761
4762 Py_XDECREF(errorHandler);
4763 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004764 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004765
4766onError:
4767 Py_XDECREF(errorHandler);
4768 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004769 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004770 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004771}
4772
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004773#ifdef __APPLE__
4774
4775/* Simplified UTF-8 decoder using surrogateescape error handler,
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004776 used to decode the command line arguments on Mac OS X.
4777
4778 Return a pointer to a newly allocated wide character string (use
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004779 PyMem_RawFree() to free the memory), or NULL on memory allocation error. */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004780
4781wchar_t*
4782_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4783{
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004784 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004785 wchar_t *unicode;
4786 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004787
4788 /* Note: size will always be longer than the resulting Unicode
4789 character count */
Victor Stinnerf50e1872015-03-20 11:32:24 +01004790 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1))
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004791 return NULL;
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004792 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004793 if (!unicode)
4794 return NULL;
4795
4796 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004797 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004798 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004799 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004800 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004801#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004802 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004803#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004804 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004805#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004806 if (ch > 0xFF) {
4807#if SIZEOF_WCHAR_T == 4
4808 assert(0);
4809#else
4810 assert(Py_UNICODE_IS_SURROGATE(ch));
4811 /* compute and append the two surrogates: */
4812 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4813 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4814#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004815 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004816 else {
4817 if (!ch && s == e)
4818 break;
4819 /* surrogateescape */
4820 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
4821 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004822 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004823 unicode[outpos] = L'\0';
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004824 return unicode;
4825}
4826
4827#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004828
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004829/* Primary internal function which creates utf8 encoded bytes objects.
4830
4831 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004832 and allocate exactly as much space needed at the end. Else allocate the
4833 maximum possible needed (4 result bytes per Unicode character), and return
4834 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004835*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004836PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004837_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004838{
Victor Stinner6099a032011-12-18 14:22:26 +01004839 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004840 void *data;
4841 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004842
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004843 if (!PyUnicode_Check(unicode)) {
4844 PyErr_BadArgument();
4845 return NULL;
4846 }
4847
4848 if (PyUnicode_READY(unicode) == -1)
4849 return NULL;
4850
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004851 if (PyUnicode_UTF8(unicode))
4852 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4853 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004854
4855 kind = PyUnicode_KIND(unicode);
4856 data = PyUnicode_DATA(unicode);
4857 size = PyUnicode_GET_LENGTH(unicode);
4858
Benjamin Petersonead6b532011-12-20 17:23:42 -06004859 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01004860 default:
4861 assert(0);
4862 case PyUnicode_1BYTE_KIND:
4863 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
4864 assert(!PyUnicode_IS_ASCII(unicode));
4865 return ucs1lib_utf8_encoder(unicode, data, size, errors);
4866 case PyUnicode_2BYTE_KIND:
4867 return ucs2lib_utf8_encoder(unicode, data, size, errors);
4868 case PyUnicode_4BYTE_KIND:
4869 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00004870 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004871}
4872
Alexander Belopolsky40018472011-02-26 01:02:56 +00004873PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004874PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4875 Py_ssize_t size,
4876 const char *errors)
4877{
4878 PyObject *v, *unicode;
4879
4880 unicode = PyUnicode_FromUnicode(s, size);
4881 if (unicode == NULL)
4882 return NULL;
4883 v = _PyUnicode_AsUTF8String(unicode, errors);
4884 Py_DECREF(unicode);
4885 return v;
4886}
4887
4888PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004889PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004890{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004891 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004892}
4893
Walter Dörwald41980ca2007-08-16 21:55:45 +00004894/* --- UTF-32 Codec ------------------------------------------------------- */
4895
4896PyObject *
4897PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004898 Py_ssize_t size,
4899 const char *errors,
4900 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004901{
4902 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4903}
4904
4905PyObject *
4906PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004907 Py_ssize_t size,
4908 const char *errors,
4909 int *byteorder,
4910 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004911{
4912 const char *starts = s;
4913 Py_ssize_t startinpos;
4914 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004915 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004916 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01004917 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02004918 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004919 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004920 PyObject *errorHandler = NULL;
4921 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004922
Walter Dörwald41980ca2007-08-16 21:55:45 +00004923 q = (unsigned char *)s;
4924 e = q + size;
4925
4926 if (byteorder)
4927 bo = *byteorder;
4928
4929 /* Check for BOM marks (U+FEFF) in the input and adjust current
4930 byte order setting accordingly. In native mode, the leading BOM
4931 mark is skipped, in all other modes, it is copied to the output
4932 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01004933 if (bo == 0 && size >= 4) {
4934 Py_UCS4 bom = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
4935 if (bom == 0x0000FEFF) {
4936 bo = -1;
4937 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00004938 }
Victor Stinnere64322e2012-10-30 23:12:47 +01004939 else if (bom == 0xFFFE0000) {
4940 bo = 1;
4941 q += 4;
4942 }
4943 if (byteorder)
4944 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004945 }
4946
Victor Stinnere64322e2012-10-30 23:12:47 +01004947 if (q == e) {
4948 if (consumed)
4949 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004950 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00004951 }
4952
Victor Stinnere64322e2012-10-30 23:12:47 +01004953#ifdef WORDS_BIGENDIAN
4954 le = bo < 0;
4955#else
4956 le = bo <= 0;
4957#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02004958 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01004959
Victor Stinner8f674cc2013-04-17 23:02:17 +02004960 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004961 writer.min_length = (e - q + 3) / 4;
4962 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004963 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01004964
Victor Stinnere64322e2012-10-30 23:12:47 +01004965 while (1) {
4966 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004967 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004968
Victor Stinnere64322e2012-10-30 23:12:47 +01004969 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004970 enum PyUnicode_Kind kind = writer.kind;
4971 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01004972 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004973 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01004974 if (le) {
4975 do {
4976 ch = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
4977 if (ch > maxch)
4978 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02004979 if (kind != PyUnicode_1BYTE_KIND &&
4980 Py_UNICODE_IS_SURROGATE(ch))
4981 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004982 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01004983 q += 4;
4984 } while (q <= last);
4985 }
4986 else {
4987 do {
4988 ch = (q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
4989 if (ch > maxch)
4990 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02004991 if (kind != PyUnicode_1BYTE_KIND &&
4992 Py_UNICODE_IS_SURROGATE(ch))
4993 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004994 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01004995 q += 4;
4996 } while (q <= last);
4997 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004998 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01004999 }
5000
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005001 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005002 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005003 startinpos = ((const char *)q) - starts;
5004 endinpos = startinpos + 4;
5005 }
5006 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005007 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005008 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005009 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005010 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005011 startinpos = ((const char *)q) - starts;
5012 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005013 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005014 else {
5015 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005016 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005017 goto onError;
5018 q += 4;
5019 continue;
5020 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005021 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005022 startinpos = ((const char *)q) - starts;
5023 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005024 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005025
5026 /* The remaining input chars are ignored if the callback
5027 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005028 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005029 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005030 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005031 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005032 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005033 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005034 }
5035
Walter Dörwald41980ca2007-08-16 21:55:45 +00005036 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005037 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005038
Walter Dörwald41980ca2007-08-16 21:55:45 +00005039 Py_XDECREF(errorHandler);
5040 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005041 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005042
Benjamin Peterson29060642009-01-31 22:14:21 +00005043 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005044 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005045 Py_XDECREF(errorHandler);
5046 Py_XDECREF(exc);
5047 return NULL;
5048}
5049
5050PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005051_PyUnicode_EncodeUTF32(PyObject *str,
5052 const char *errors,
5053 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005054{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005055 enum PyUnicode_Kind kind;
5056 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005057 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005058 PyObject *v;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005059 PY_UINT32_T *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005060#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005061 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005062#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005063 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005064#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005065 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005066 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005067 PyObject *errorHandler = NULL;
5068 PyObject *exc = NULL;
5069 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005070
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005071 if (!PyUnicode_Check(str)) {
5072 PyErr_BadArgument();
5073 return NULL;
5074 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005075 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005076 return NULL;
5077 kind = PyUnicode_KIND(str);
5078 data = PyUnicode_DATA(str);
5079 len = PyUnicode_GET_LENGTH(str);
5080
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005081 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005082 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005083 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005084 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005085 if (v == NULL)
5086 return NULL;
5087
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005088 /* output buffer is 4-bytes aligned */
5089 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
5090 out = (PY_UINT32_T *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005091 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005092 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005093 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005094 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005095
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005096 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005097 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005098 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005099 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005100 else
5101 encoding = "utf-32";
5102
5103 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005104 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5105 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005106 }
5107
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005108 pos = 0;
5109 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005110 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005111
5112 if (kind == PyUnicode_2BYTE_KIND) {
5113 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5114 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005115 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005116 else {
5117 assert(kind == PyUnicode_4BYTE_KIND);
5118 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5119 &out, native_ordering);
5120 }
5121 if (pos == len)
5122 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005123
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005124 rep = unicode_encode_call_errorhandler(
5125 errors, &errorHandler,
5126 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005127 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005128 if (!rep)
5129 goto error;
5130
5131 if (PyBytes_Check(rep)) {
5132 repsize = PyBytes_GET_SIZE(rep);
5133 if (repsize & 3) {
5134 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005135 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005136 "surrogates not allowed");
5137 goto error;
5138 }
5139 moreunits = repsize / 4;
5140 }
5141 else {
5142 assert(PyUnicode_Check(rep));
5143 if (PyUnicode_READY(rep) < 0)
5144 goto error;
5145 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5146 if (!PyUnicode_IS_ASCII(rep)) {
5147 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005148 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005149 "surrogates not allowed");
5150 goto error;
5151 }
5152 }
5153
5154 /* four bytes are reserved for each surrogate */
5155 if (moreunits > 1) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005156 Py_ssize_t outpos = out - (PY_UINT32_T*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005157 Py_ssize_t morebytes = 4 * (moreunits - 1);
5158 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5159 /* integer overflow */
5160 PyErr_NoMemory();
5161 goto error;
5162 }
5163 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5164 goto error;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005165 out = (PY_UINT32_T*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005166 }
5167
5168 if (PyBytes_Check(rep)) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005169 Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
5170 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005171 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005172 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005173 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5174 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005175 }
5176
5177 Py_CLEAR(rep);
5178 }
5179
5180 /* Cut back to size actually needed. This is necessary for, for example,
5181 encoding of a string containing isolated surrogates and the 'ignore'
5182 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005183 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005184 if (nsize != PyBytes_GET_SIZE(v))
5185 _PyBytes_Resize(&v, nsize);
5186 Py_XDECREF(errorHandler);
5187 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005188 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005189 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005190 error:
5191 Py_XDECREF(rep);
5192 Py_XDECREF(errorHandler);
5193 Py_XDECREF(exc);
5194 Py_XDECREF(v);
5195 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005196}
5197
Alexander Belopolsky40018472011-02-26 01:02:56 +00005198PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005199PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5200 Py_ssize_t size,
5201 const char *errors,
5202 int byteorder)
5203{
5204 PyObject *result;
5205 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5206 if (tmp == NULL)
5207 return NULL;
5208 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5209 Py_DECREF(tmp);
5210 return result;
5211}
5212
5213PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005214PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005215{
Victor Stinnerb960b342011-11-20 19:12:52 +01005216 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005217}
5218
Guido van Rossumd57fd912000-03-10 22:53:23 +00005219/* --- UTF-16 Codec ------------------------------------------------------- */
5220
Tim Peters772747b2001-08-09 22:21:55 +00005221PyObject *
5222PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005223 Py_ssize_t size,
5224 const char *errors,
5225 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005226{
Walter Dörwald69652032004-09-07 20:24:22 +00005227 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5228}
5229
5230PyObject *
5231PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005232 Py_ssize_t size,
5233 const char *errors,
5234 int *byteorder,
5235 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005236{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005237 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005238 Py_ssize_t startinpos;
5239 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005240 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005241 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005242 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005243 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005244 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005245 PyObject *errorHandler = NULL;
5246 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005247 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005248
Tim Peters772747b2001-08-09 22:21:55 +00005249 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005250 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005251
5252 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005253 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005254
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005255 /* Check for BOM marks (U+FEFF) in the input and adjust current
5256 byte order setting accordingly. In native mode, the leading BOM
5257 mark is skipped, in all other modes, it is copied to the output
5258 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005259 if (bo == 0 && size >= 2) {
5260 const Py_UCS4 bom = (q[1] << 8) | q[0];
5261 if (bom == 0xFEFF) {
5262 q += 2;
5263 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005264 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005265 else if (bom == 0xFFFE) {
5266 q += 2;
5267 bo = 1;
5268 }
5269 if (byteorder)
5270 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005271 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005272
Antoine Pitrou63065d72012-05-15 23:48:04 +02005273 if (q == e) {
5274 if (consumed)
5275 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005276 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005277 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005278
Christian Heimes743e0cd2012-10-17 23:52:17 +02005279#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005280 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005281 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005282#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005283 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005284 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005285#endif
Tim Peters772747b2001-08-09 22:21:55 +00005286
Antoine Pitrou63065d72012-05-15 23:48:04 +02005287 /* Note: size will always be longer than the resulting Unicode
5288 character count */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005289 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005290 writer.min_length = (e - q + 1) / 2;
5291 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005292 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005293
Antoine Pitrou63065d72012-05-15 23:48:04 +02005294 while (1) {
5295 Py_UCS4 ch = 0;
5296 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005297 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005298 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005299 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005300 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005301 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005302 native_ordering);
5303 else
5304 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005305 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005306 native_ordering);
5307 } else if (kind == PyUnicode_2BYTE_KIND) {
5308 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005309 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005310 native_ordering);
5311 } else {
5312 assert(kind == PyUnicode_4BYTE_KIND);
5313 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005314 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005315 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005316 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005317 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005318
Antoine Pitrou63065d72012-05-15 23:48:04 +02005319 switch (ch)
5320 {
5321 case 0:
5322 /* remaining byte at the end? (size should be even) */
5323 if (q == e || consumed)
5324 goto End;
5325 errmsg = "truncated data";
5326 startinpos = ((const char *)q) - starts;
5327 endinpos = ((const char *)e) - starts;
5328 break;
5329 /* The remaining input chars are ignored if the callback
5330 chooses to skip the input */
5331 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005332 q -= 2;
5333 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005334 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005335 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005336 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005337 endinpos = ((const char *)e) - starts;
5338 break;
5339 case 2:
5340 errmsg = "illegal encoding";
5341 startinpos = ((const char *)q) - 2 - starts;
5342 endinpos = startinpos + 2;
5343 break;
5344 case 3:
5345 errmsg = "illegal UTF-16 surrogate";
5346 startinpos = ((const char *)q) - 4 - starts;
5347 endinpos = startinpos + 2;
5348 break;
5349 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005350 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005351 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005352 continue;
5353 }
5354
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005355 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005356 errors,
5357 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005358 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005359 &starts,
5360 (const char **)&e,
5361 &startinpos,
5362 &endinpos,
5363 &exc,
5364 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005365 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005366 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005367 }
5368
Antoine Pitrou63065d72012-05-15 23:48:04 +02005369End:
Walter Dörwald69652032004-09-07 20:24:22 +00005370 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005371 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005372
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005373 Py_XDECREF(errorHandler);
5374 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005375 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005376
Benjamin Peterson29060642009-01-31 22:14:21 +00005377 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005378 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005379 Py_XDECREF(errorHandler);
5380 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005381 return NULL;
5382}
5383
Tim Peters772747b2001-08-09 22:21:55 +00005384PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005385_PyUnicode_EncodeUTF16(PyObject *str,
5386 const char *errors,
5387 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005388{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005389 enum PyUnicode_Kind kind;
5390 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005391 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005392 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005393 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005394 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005395#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005396 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005397#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005398 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005399#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005400 const char *encoding;
5401 Py_ssize_t nsize, pos;
5402 PyObject *errorHandler = NULL;
5403 PyObject *exc = NULL;
5404 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005405
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005406 if (!PyUnicode_Check(str)) {
5407 PyErr_BadArgument();
5408 return NULL;
5409 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005410 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005411 return NULL;
5412 kind = PyUnicode_KIND(str);
5413 data = PyUnicode_DATA(str);
5414 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005415
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005416 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005417 if (kind == PyUnicode_4BYTE_KIND) {
5418 const Py_UCS4 *in = (const Py_UCS4 *)data;
5419 const Py_UCS4 *end = in + len;
5420 while (in < end)
5421 if (*in++ >= 0x10000)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005422 pairs++;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005423 }
5424 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005425 return PyErr_NoMemory();
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005426 nsize = len + pairs + (byteorder == 0);
5427 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005428 if (v == NULL)
5429 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005430
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005431 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005432 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005433 out = (unsigned short *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005434 if (byteorder == 0)
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005435 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005436 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005437 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005438
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005439 if (kind == PyUnicode_1BYTE_KIND) {
5440 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5441 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005442 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005443
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005444 if (byteorder < 0)
5445 encoding = "utf-16-le";
5446 else if (byteorder > 0)
5447 encoding = "utf-16-be";
5448 else
5449 encoding = "utf-16";
5450
5451 pos = 0;
5452 while (pos < len) {
5453 Py_ssize_t repsize, moreunits;
5454
5455 if (kind == PyUnicode_2BYTE_KIND) {
5456 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5457 &out, native_ordering);
5458 }
5459 else {
5460 assert(kind == PyUnicode_4BYTE_KIND);
5461 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5462 &out, native_ordering);
5463 }
5464 if (pos == len)
5465 break;
5466
5467 rep = unicode_encode_call_errorhandler(
5468 errors, &errorHandler,
5469 encoding, "surrogates not allowed",
5470 str, &exc, pos, pos + 1, &pos);
5471 if (!rep)
5472 goto error;
5473
5474 if (PyBytes_Check(rep)) {
5475 repsize = PyBytes_GET_SIZE(rep);
5476 if (repsize & 1) {
5477 raise_encode_exception(&exc, encoding,
5478 str, pos - 1, pos,
5479 "surrogates not allowed");
5480 goto error;
5481 }
5482 moreunits = repsize / 2;
5483 }
5484 else {
5485 assert(PyUnicode_Check(rep));
5486 if (PyUnicode_READY(rep) < 0)
5487 goto error;
5488 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5489 if (!PyUnicode_IS_ASCII(rep)) {
5490 raise_encode_exception(&exc, encoding,
5491 str, pos - 1, pos,
5492 "surrogates not allowed");
5493 goto error;
5494 }
5495 }
5496
5497 /* two bytes are reserved for each surrogate */
5498 if (moreunits > 1) {
5499 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
5500 Py_ssize_t morebytes = 2 * (moreunits - 1);
5501 if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5502 /* integer overflow */
5503 PyErr_NoMemory();
5504 goto error;
5505 }
5506 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5507 goto error;
5508 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5509 }
5510
5511 if (PyBytes_Check(rep)) {
5512 Py_MEMCPY(out, PyBytes_AS_STRING(rep), repsize);
5513 out += moreunits;
5514 } else /* rep is unicode */ {
5515 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5516 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5517 &out, native_ordering);
5518 }
5519
5520 Py_CLEAR(rep);
5521 }
5522
5523 /* Cut back to size actually needed. This is necessary for, for example,
5524 encoding of a string containing isolated surrogates and the 'ignore' handler
5525 is used. */
5526 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5527 if (nsize != PyBytes_GET_SIZE(v))
5528 _PyBytes_Resize(&v, nsize);
5529 Py_XDECREF(errorHandler);
5530 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005531 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005532 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005533 error:
5534 Py_XDECREF(rep);
5535 Py_XDECREF(errorHandler);
5536 Py_XDECREF(exc);
5537 Py_XDECREF(v);
5538 return NULL;
5539#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005540}
5541
Alexander Belopolsky40018472011-02-26 01:02:56 +00005542PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005543PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5544 Py_ssize_t size,
5545 const char *errors,
5546 int byteorder)
5547{
5548 PyObject *result;
5549 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5550 if (tmp == NULL)
5551 return NULL;
5552 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5553 Py_DECREF(tmp);
5554 return result;
5555}
5556
5557PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005558PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005559{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005560 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005561}
5562
5563/* --- Unicode Escape Codec ----------------------------------------------- */
5564
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005565/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5566 if all the escapes in the string make it still a valid ASCII string.
5567 Returns -1 if any escapes were found which cause the string to
5568 pop out of ASCII range. Otherwise returns the length of the
5569 required buffer to hold the string.
5570 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005571static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005572length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5573{
5574 const unsigned char *p = (const unsigned char *)s;
5575 const unsigned char *end = p + size;
5576 Py_ssize_t length = 0;
5577
5578 if (size < 0)
5579 return -1;
5580
5581 for (; p < end; ++p) {
5582 if (*p > 127) {
5583 /* Non-ASCII */
5584 return -1;
5585 }
5586 else if (*p != '\\') {
5587 /* Normal character */
5588 ++length;
5589 }
5590 else {
5591 /* Backslash-escape, check next char */
5592 ++p;
5593 /* Escape sequence reaches till end of string or
5594 non-ASCII follow-up. */
5595 if (p >= end || *p > 127)
5596 return -1;
5597 switch (*p) {
5598 case '\n':
5599 /* backslash + \n result in zero characters */
5600 break;
5601 case '\\': case '\'': case '\"':
5602 case 'b': case 'f': case 't':
5603 case 'n': case 'r': case 'v': case 'a':
5604 ++length;
5605 break;
5606 case '0': case '1': case '2': case '3':
5607 case '4': case '5': case '6': case '7':
5608 case 'x': case 'u': case 'U': case 'N':
5609 /* these do not guarantee ASCII characters */
5610 return -1;
5611 default:
5612 /* count the backslash + the other character */
5613 length += 2;
5614 }
5615 }
5616 }
5617 return length;
5618}
5619
Fredrik Lundh06d12682001-01-24 07:59:11 +00005620static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005621
Alexander Belopolsky40018472011-02-26 01:02:56 +00005622PyObject *
5623PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005624 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005625 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005626{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005627 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005628 Py_ssize_t startinpos;
5629 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005630 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005631 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005632 char* message;
5633 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005634 PyObject *errorHandler = NULL;
5635 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005636 Py_ssize_t len;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005637
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005638 len = length_of_escaped_ascii_string(s, size);
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005639 if (len == 0)
5640 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005641
5642 /* After length_of_escaped_ascii_string() there are two alternatives,
5643 either the string is pure ASCII with named escapes like \n, etc.
5644 and we determined it's exact size (common case)
5645 or it contains \x, \u, ... escape sequences. then we create a
5646 legacy wchar string and resize it at the end of this function. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005647 _PyUnicodeWriter_Init(&writer);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005648 if (len > 0) {
Victor Stinner8f674cc2013-04-17 23:02:17 +02005649 writer.min_length = len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005650 }
5651 else {
5652 /* Escaped strings will always be longer than the resulting
5653 Unicode string, so we start with size here and then reduce the
5654 length after conversion to the true value.
5655 (but if the error callback returns a long replacement string
5656 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005657 writer.min_length = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005658 }
5659
Guido van Rossumd57fd912000-03-10 22:53:23 +00005660 if (size == 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005661 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005662 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005663
Guido van Rossumd57fd912000-03-10 22:53:23 +00005664 while (s < end) {
5665 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005666 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005667 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005668
5669 /* Non-escape characters are interpreted as Unicode ordinals */
5670 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005671 x = (unsigned char)*s;
5672 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005673 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005674 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005675 continue;
5676 }
5677
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005678 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005679 /* \ - Escapes */
5680 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005681 c = *s++;
5682 if (s > end)
5683 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005684
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005685 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005686
Benjamin Peterson29060642009-01-31 22:14:21 +00005687 /* \x escapes */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005688#define WRITECHAR(ch) \
5689 do { \
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005690 if (_PyUnicodeWriter_WriteCharInline(&writer, (ch)) < 0) \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005691 goto onError; \
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005692 } while(0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005693
Guido van Rossumd57fd912000-03-10 22:53:23 +00005694 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005695 case '\\': WRITECHAR('\\'); break;
5696 case '\'': WRITECHAR('\''); break;
5697 case '\"': WRITECHAR('\"'); break;
5698 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005699 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005700 case 'f': WRITECHAR('\014'); break;
5701 case 't': WRITECHAR('\t'); break;
5702 case 'n': WRITECHAR('\n'); break;
5703 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005704 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005705 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005706 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005707 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005708
Benjamin Peterson29060642009-01-31 22:14:21 +00005709 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005710 case '0': case '1': case '2': case '3':
5711 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005712 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005713 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005714 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005715 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005716 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005717 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005718 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005719 break;
5720
Benjamin Peterson29060642009-01-31 22:14:21 +00005721 /* hex escapes */
5722 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005723 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005724 digits = 2;
5725 message = "truncated \\xXX escape";
5726 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005727
Benjamin Peterson29060642009-01-31 22:14:21 +00005728 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005729 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005730 digits = 4;
5731 message = "truncated \\uXXXX escape";
5732 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005733
Benjamin Peterson29060642009-01-31 22:14:21 +00005734 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005735 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005736 digits = 8;
5737 message = "truncated \\UXXXXXXXX escape";
5738 hexescape:
5739 chr = 0;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005740 if (end - s < digits) {
5741 /* count only hex digits */
5742 for (; s < end; ++s) {
5743 c = (unsigned char)*s;
5744 if (!Py_ISXDIGIT(c))
5745 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005746 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005747 goto error;
5748 }
5749 for (; digits--; ++s) {
5750 c = (unsigned char)*s;
5751 if (!Py_ISXDIGIT(c))
5752 goto error;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005753 chr = (chr<<4) & ~0xF;
5754 if (c >= '0' && c <= '9')
5755 chr += c - '0';
5756 else if (c >= 'a' && c <= 'f')
5757 chr += 10 + c - 'a';
5758 else
5759 chr += 10 + c - 'A';
5760 }
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005761 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005762 /* _decoding_error will have already written into the
5763 target buffer. */
5764 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005765 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005766 /* when we get here, chr is a 32-bit unicode character */
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005767 message = "illegal Unicode character";
5768 if (chr > MAX_UNICODE)
Serhiy Storchakad6793772013-01-29 10:20:44 +02005769 goto error;
Serhiy Storchaka24193de2013-01-29 10:28:07 +02005770 WRITECHAR(chr);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005771 break;
5772
Benjamin Peterson29060642009-01-31 22:14:21 +00005773 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005774 case 'N':
5775 message = "malformed \\N character escape";
5776 if (ucnhash_CAPI == NULL) {
5777 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005778 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5779 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005780 if (ucnhash_CAPI == NULL)
5781 goto ucnhashError;
5782 }
5783 if (*s == '{') {
5784 const char *start = s+1;
5785 /* look for the closing brace */
5786 while (*s != '}' && s < end)
5787 s++;
5788 if (s > start && s < end && *s == '}') {
5789 /* found a name. look it up in the unicode database */
5790 message = "unknown Unicode character name";
5791 s++;
Serhiy Storchaka4f5f0e52013-01-21 11:38:00 +02005792 if (s - start - 1 <= INT_MAX &&
Serhiy Storchakac35f3a92013-01-21 11:42:57 +02005793 ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005794 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005795 goto store;
5796 }
5797 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005798 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005799
5800 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005801 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005802 message = "\\ at end of string";
5803 s--;
Serhiy Storchakad6793772013-01-29 10:20:44 +02005804 goto error;
Walter Dörwald8c077222002-03-25 11:16:18 +00005805 }
5806 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005807 WRITECHAR('\\');
Serhiy Storchaka73e38802013-01-25 23:52:21 +02005808 WRITECHAR((unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005809 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005810 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005811 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02005812 continue;
5813
5814 error:
5815 endinpos = s-starts;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005816 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02005817 errors, &errorHandler,
5818 "unicodeescape", message,
5819 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02005820 &writer))
Serhiy Storchakad6793772013-01-29 10:20:44 +02005821 goto onError;
5822 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005823 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005824#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005825
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005826 Py_XDECREF(errorHandler);
5827 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005828 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00005829
Benjamin Peterson29060642009-01-31 22:14:21 +00005830 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005831 PyErr_SetString(
5832 PyExc_UnicodeError,
5833 "\\N escapes not supported (can't load unicodedata module)"
5834 );
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005835 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005836 Py_XDECREF(errorHandler);
5837 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005838 return NULL;
5839
Benjamin Peterson29060642009-01-31 22:14:21 +00005840 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005841 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005842 Py_XDECREF(errorHandler);
5843 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005844 return NULL;
5845}
5846
5847/* Return a Unicode-Escape string version of the Unicode object.
5848
5849 If quotes is true, the string is enclosed in u"" or u'' quotes as
5850 appropriate.
5851
5852*/
5853
Alexander Belopolsky40018472011-02-26 01:02:56 +00005854PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005855PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005856{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005857 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005858 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005859 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005860 int kind;
5861 void *data;
5862 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005863
Ezio Melottie7f90372012-10-05 03:33:31 +03005864 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00005865 escape.
5866
Ezio Melottie7f90372012-10-05 03:33:31 +03005867 For UCS1 strings it's '\xxx', 4 bytes per source character.
5868 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
5869 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00005870 */
5871
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005872 if (!PyUnicode_Check(unicode)) {
5873 PyErr_BadArgument();
5874 return NULL;
5875 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005876 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005877 return NULL;
5878 len = PyUnicode_GET_LENGTH(unicode);
5879 kind = PyUnicode_KIND(unicode);
5880 data = PyUnicode_DATA(unicode);
Benjamin Petersonead6b532011-12-20 17:23:42 -06005881 switch (kind) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005882 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5883 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5884 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5885 }
5886
5887 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005888 return PyBytes_FromStringAndSize(NULL, 0);
5889
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005890 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005891 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005892
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005893 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005894 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005895 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005896 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005897 if (repr == NULL)
5898 return NULL;
5899
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005900 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005901
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005902 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005903 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005904
Walter Dörwald79e913e2007-05-12 11:08:06 +00005905 /* Escape backslashes */
5906 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005907 *p++ = '\\';
5908 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005909 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005910 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005911
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005912 /* Map 21-bit characters to '\U00xxxxxx' */
5913 else if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01005914 assert(ch <= MAX_UNICODE);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005915 *p++ = '\\';
5916 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005917 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5918 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5919 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5920 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5921 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5922 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5923 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5924 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005925 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005926 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005927
Guido van Rossumd57fd912000-03-10 22:53:23 +00005928 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005929 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005930 *p++ = '\\';
5931 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005932 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5933 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5934 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5935 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005936 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005937
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005938 /* Map special whitespace to '\t', \n', '\r' */
5939 else if (ch == '\t') {
5940 *p++ = '\\';
5941 *p++ = 't';
5942 }
5943 else if (ch == '\n') {
5944 *p++ = '\\';
5945 *p++ = 'n';
5946 }
5947 else if (ch == '\r') {
5948 *p++ = '\\';
5949 *p++ = 'r';
5950 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005951
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005952 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005953 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005954 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005955 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005956 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5957 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005958 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005959
Guido van Rossumd57fd912000-03-10 22:53:23 +00005960 /* Copy everything else as-is */
5961 else
5962 *p++ = (char) ch;
5963 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005964
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005965 assert(p - PyBytes_AS_STRING(repr) > 0);
5966 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
5967 return NULL;
5968 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005969}
5970
Alexander Belopolsky40018472011-02-26 01:02:56 +00005971PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005972PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
5973 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005974{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005975 PyObject *result;
5976 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5977 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005978 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005979 result = PyUnicode_AsUnicodeEscapeString(tmp);
5980 Py_DECREF(tmp);
5981 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005982}
5983
5984/* --- Raw Unicode Escape Codec ------------------------------------------- */
5985
Alexander Belopolsky40018472011-02-26 01:02:56 +00005986PyObject *
5987PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005988 Py_ssize_t size,
5989 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005990{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005991 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005992 Py_ssize_t startinpos;
5993 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005994 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005995 const char *end;
5996 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005997 PyObject *errorHandler = NULL;
5998 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00005999
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006000 if (size == 0)
6001 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006002
Guido van Rossumd57fd912000-03-10 22:53:23 +00006003 /* Escaped strings will always be longer than the resulting
6004 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006005 length after conversion to the true value. (But decoding error
6006 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006007 _PyUnicodeWriter_Init(&writer);
6008 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006009
Guido van Rossumd57fd912000-03-10 22:53:23 +00006010 end = s + size;
6011 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006012 unsigned char c;
6013 Py_UCS4 x;
6014 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006015 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006016
Benjamin Peterson29060642009-01-31 22:14:21 +00006017 /* Non-escape characters are interpreted as Unicode ordinals */
6018 if (*s != '\\') {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006019 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006020 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006021 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006022 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006023 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006024 startinpos = s-starts;
6025
6026 /* \u-escapes are only interpreted iff the number of leading
6027 backslashes if odd */
6028 bs = s;
6029 for (;s < end;) {
6030 if (*s != '\\')
6031 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006032 x = (unsigned char)*s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006033 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006034 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006035 }
6036 if (((s - bs) & 1) == 0 ||
6037 s >= end ||
6038 (*s != 'u' && *s != 'U')) {
6039 continue;
6040 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006041 writer.pos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006042 count = *s=='u' ? 4 : 8;
6043 s++;
6044
6045 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006046 for (x = 0, i = 0; i < count; ++i, ++s) {
6047 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006048 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006049 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006050 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006051 errors, &errorHandler,
6052 "rawunicodeescape", "truncated \\uXXXX",
6053 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006054 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006055 goto onError;
6056 goto nextByte;
6057 }
6058 x = (x<<4) & ~0xF;
6059 if (c >= '0' && c <= '9')
6060 x += c - '0';
6061 else if (c >= 'a' && c <= 'f')
6062 x += 10 + c - 'a';
6063 else
6064 x += 10 + c - 'A';
6065 }
Victor Stinner8faf8212011-12-08 22:14:11 +01006066 if (x <= MAX_UNICODE) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006067 if (_PyUnicodeWriter_WriteCharInline(&writer, x) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006068 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006069 }
6070 else {
Christian Heimesfe337bf2008-03-23 21:54:12 +00006071 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006072 if (unicode_decode_call_errorhandler_writer(
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006073 errors, &errorHandler,
6074 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006075 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006076 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006077 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006078 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006079 nextByte:
6080 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006081 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006082 Py_XDECREF(errorHandler);
6083 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006084 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006085
Benjamin Peterson29060642009-01-31 22:14:21 +00006086 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006087 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006088 Py_XDECREF(errorHandler);
6089 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006090 return NULL;
6091}
6092
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006093
Alexander Belopolsky40018472011-02-26 01:02:56 +00006094PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006095PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006096{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006097 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006098 char *p;
6099 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006100 Py_ssize_t expandsize, pos;
6101 int kind;
6102 void *data;
6103 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006104
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006105 if (!PyUnicode_Check(unicode)) {
6106 PyErr_BadArgument();
6107 return NULL;
6108 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006109 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006110 return NULL;
6111 kind = PyUnicode_KIND(unicode);
6112 data = PyUnicode_DATA(unicode);
6113 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson1518e872011-11-23 10:44:52 -06006114 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6115 bytes, and 1 byte characters 4. */
6116 expandsize = kind * 2 + 2;
Victor Stinner0e368262011-11-10 20:12:49 +01006117
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006118 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006119 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006120
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006121 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006122 if (repr == NULL)
6123 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006124 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006125 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006126
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006127 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006128 for (pos = 0; pos < len; pos++) {
6129 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006130 /* Map 32-bit characters to '\Uxxxxxxxx' */
6131 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01006132 assert(ch <= MAX_UNICODE);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006133 *p++ = '\\';
6134 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006135 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6136 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6137 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6138 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6139 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6140 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6141 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6142 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006143 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006144 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006145 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006146 *p++ = '\\';
6147 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006148 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6149 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6150 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6151 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006152 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006153 /* Copy everything else as-is */
6154 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006155 *p++ = (char) ch;
6156 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006157
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006158 assert(p > q);
6159 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006160 return NULL;
6161 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006162}
6163
Alexander Belopolsky40018472011-02-26 01:02:56 +00006164PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006165PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6166 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006167{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006168 PyObject *result;
6169 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6170 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006171 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006172 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6173 Py_DECREF(tmp);
6174 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006175}
6176
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006177/* --- Unicode Internal Codec ------------------------------------------- */
6178
Alexander Belopolsky40018472011-02-26 01:02:56 +00006179PyObject *
6180_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006181 Py_ssize_t size,
6182 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006183{
6184 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006185 Py_ssize_t startinpos;
6186 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006187 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006188 const char *end;
6189 const char *reason;
6190 PyObject *errorHandler = NULL;
6191 PyObject *exc = NULL;
6192
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006193 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006194 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006195 1))
6196 return NULL;
6197
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006198 if (size == 0)
6199 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006200
Victor Stinner8f674cc2013-04-17 23:02:17 +02006201 _PyUnicodeWriter_Init(&writer);
6202 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6203 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006204 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006205 }
6206 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006207
Victor Stinner8f674cc2013-04-17 23:02:17 +02006208 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006209 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006210 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006211 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006212 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006213 endinpos = end-starts;
6214 reason = "truncated input";
6215 goto error;
6216 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006217 /* We copy the raw representation one byte at a time because the
6218 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006219 ((char *) &uch)[0] = s[0];
6220 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006221#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006222 ((char *) &uch)[2] = s[2];
6223 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006224#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006225 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006226#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006227 /* We have to sanity check the raw data, otherwise doom looms for
6228 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006229 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006230 endinpos = s - starts + Py_UNICODE_SIZE;
6231 reason = "illegal code point (> 0x10FFFF)";
6232 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006233 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006234#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006235 s += Py_UNICODE_SIZE;
6236#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006237 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006238 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006239 Py_UNICODE uch2;
6240 ((char *) &uch2)[0] = s[0];
6241 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006242 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006243 {
Victor Stinner551ac952011-11-29 22:58:13 +01006244 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006245 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006246 }
6247 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006248#endif
6249
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006250 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006251 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006252 continue;
6253
6254 error:
6255 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006256 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006257 errors, &errorHandler,
6258 "unicode_internal", reason,
6259 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006260 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006261 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006262 }
6263
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006264 Py_XDECREF(errorHandler);
6265 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006266 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006267
Benjamin Peterson29060642009-01-31 22:14:21 +00006268 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006269 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006270 Py_XDECREF(errorHandler);
6271 Py_XDECREF(exc);
6272 return NULL;
6273}
6274
Guido van Rossumd57fd912000-03-10 22:53:23 +00006275/* --- Latin-1 Codec ------------------------------------------------------ */
6276
Alexander Belopolsky40018472011-02-26 01:02:56 +00006277PyObject *
6278PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006279 Py_ssize_t size,
6280 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006281{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006282 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006283 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006284}
6285
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006286/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006287static void
6288make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006289 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006290 PyObject *unicode,
6291 Py_ssize_t startpos, Py_ssize_t endpos,
6292 const char *reason)
6293{
6294 if (*exceptionObject == NULL) {
6295 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006296 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006297 encoding, unicode, startpos, endpos, reason);
6298 }
6299 else {
6300 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6301 goto onError;
6302 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6303 goto onError;
6304 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6305 goto onError;
6306 return;
6307 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006308 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006309 }
6310}
6311
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006312/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006313static void
6314raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006315 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006316 PyObject *unicode,
6317 Py_ssize_t startpos, Py_ssize_t endpos,
6318 const char *reason)
6319{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006320 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006321 encoding, unicode, startpos, endpos, reason);
6322 if (*exceptionObject != NULL)
6323 PyCodec_StrictErrors(*exceptionObject);
6324}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006325
6326/* error handling callback helper:
6327 build arguments, call the callback and check the arguments,
6328 put the result into newpos and return the replacement string, which
6329 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006330static PyObject *
6331unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006332 PyObject **errorHandler,
6333 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006334 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006335 Py_ssize_t startpos, Py_ssize_t endpos,
6336 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006337{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006338 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006339 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006340 PyObject *restuple;
6341 PyObject *resunicode;
6342
6343 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006344 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006345 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006346 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006347 }
6348
Benjamin Petersonbac79492012-01-14 13:34:47 -05006349 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006350 return NULL;
6351 len = PyUnicode_GET_LENGTH(unicode);
6352
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006353 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006354 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006355 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006356 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006357
6358 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006359 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006360 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006361 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006362 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006363 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006364 Py_DECREF(restuple);
6365 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006366 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006367 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006368 &resunicode, newpos)) {
6369 Py_DECREF(restuple);
6370 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006371 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006372 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6373 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6374 Py_DECREF(restuple);
6375 return NULL;
6376 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006377 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006378 *newpos = len + *newpos;
6379 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006380 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006381 Py_DECREF(restuple);
6382 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006383 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006384 Py_INCREF(resunicode);
6385 Py_DECREF(restuple);
6386 return resunicode;
6387}
6388
Alexander Belopolsky40018472011-02-26 01:02:56 +00006389static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006390unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006391 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006392 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006393{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006394 /* input state */
6395 Py_ssize_t pos=0, size;
6396 int kind;
6397 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006398 /* output object */
6399 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006400 /* pointer into the output */
6401 char *str;
6402 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006403 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006404 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6405 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006406 PyObject *errorHandler = NULL;
6407 PyObject *exc = NULL;
6408 /* the following variable is used for caching string comparisons
6409 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6410 int known_errorHandler = -1;
6411
Benjamin Petersonbac79492012-01-14 13:34:47 -05006412 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006413 return NULL;
6414 size = PyUnicode_GET_LENGTH(unicode);
6415 kind = PyUnicode_KIND(unicode);
6416 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006417 /* allocate enough for a simple encoding without
6418 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006419 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006420 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006421 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006422 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006423 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006424 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006425 ressize = size;
6426
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006427 while (pos < size) {
6428 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006429
Benjamin Peterson29060642009-01-31 22:14:21 +00006430 /* can we encode this? */
6431 if (c<limit) {
6432 /* no overflow check, because we know that the space is enough */
6433 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006434 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006435 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006436 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006437 Py_ssize_t requiredsize;
6438 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006439 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006440 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006441 Py_ssize_t collstart = pos;
6442 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006443 /* find all unecodable characters */
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006444 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006445 ++collend;
6446 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6447 if (known_errorHandler==-1) {
6448 if ((errors==NULL) || (!strcmp(errors, "strict")))
6449 known_errorHandler = 1;
6450 else if (!strcmp(errors, "replace"))
6451 known_errorHandler = 2;
6452 else if (!strcmp(errors, "ignore"))
6453 known_errorHandler = 3;
6454 else if (!strcmp(errors, "xmlcharrefreplace"))
6455 known_errorHandler = 4;
6456 else
6457 known_errorHandler = 0;
6458 }
6459 switch (known_errorHandler) {
6460 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006461 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006462 goto onError;
6463 case 2: /* replace */
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006464 while (collstart++ < collend)
Benjamin Peterson29060642009-01-31 22:14:21 +00006465 *str++ = '?'; /* fall through */
6466 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006467 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006468 break;
6469 case 4: /* xmlcharrefreplace */
6470 respos = str - PyBytes_AS_STRING(res);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006471 requiredsize = respos;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006472 /* determine replacement size */
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006473 for (i = collstart; i < collend; ++i) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006474 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006475 Py_ssize_t incr;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006476 if (ch < 10)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006477 incr = 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006478 else if (ch < 100)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006479 incr = 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006480 else if (ch < 1000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006481 incr = 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006482 else if (ch < 10000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006483 incr = 2+4+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006484 else if (ch < 100000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006485 incr = 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006486 else if (ch < 1000000)
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006487 incr = 2+6+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006488 else {
Victor Stinner8faf8212011-12-08 22:14:11 +01006489 assert(ch <= MAX_UNICODE);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006490 incr = 2+7+1;
Victor Stinner0d3721d2011-11-22 03:27:53 +01006491 }
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006492 if (requiredsize > PY_SSIZE_T_MAX - incr)
6493 goto overflow;
6494 requiredsize += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +00006495 }
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006496 if (requiredsize > PY_SSIZE_T_MAX - (size - collend))
6497 goto overflow;
6498 requiredsize += size - collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006499 if (requiredsize > ressize) {
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006500 if (ressize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*ressize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006501 requiredsize = 2*ressize;
6502 if (_PyBytes_Resize(&res, requiredsize))
6503 goto onError;
6504 str = PyBytes_AS_STRING(res) + respos;
6505 ressize = requiredsize;
6506 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006507 /* generate replacement */
6508 for (i = collstart; i < collend; ++i) {
6509 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006510 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006511 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006512 break;
6513 default:
6514 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006515 encoding, reason, unicode, &exc,
6516 collstart, collend, &newpos);
6517 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
Benjamin Petersonbac79492012-01-14 13:34:47 -05006518 PyUnicode_READY(repunicode) == -1))
Benjamin Peterson29060642009-01-31 22:14:21 +00006519 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006520 if (PyBytes_Check(repunicode)) {
6521 /* Directly copy bytes result to output. */
6522 repsize = PyBytes_Size(repunicode);
6523 if (repsize > 1) {
6524 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006525 respos = str - PyBytes_AS_STRING(res);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006526 if (ressize > PY_SSIZE_T_MAX - repsize - 1) {
6527 Py_DECREF(repunicode);
6528 goto overflow;
6529 }
Martin v. Löwis011e8422009-05-05 04:43:17 +00006530 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6531 Py_DECREF(repunicode);
6532 goto onError;
6533 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006534 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006535 ressize += repsize-1;
6536 }
6537 memcpy(str, PyBytes_AsString(repunicode), repsize);
6538 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006539 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006540 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006541 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006542 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006543 /* need more space? (at least enough for what we
6544 have+the replacement+the rest of the string, so
6545 we won't have to check space for encodable characters) */
6546 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006547 repsize = PyUnicode_GET_LENGTH(repunicode);
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006548 requiredsize = respos;
6549 if (requiredsize > PY_SSIZE_T_MAX - repsize)
6550 goto overflow;
6551 requiredsize += repsize;
6552 if (requiredsize > PY_SSIZE_T_MAX - (size - collend))
6553 goto overflow;
6554 requiredsize += size - collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006555 if (requiredsize > ressize) {
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006556 if (ressize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*ressize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006557 requiredsize = 2*ressize;
6558 if (_PyBytes_Resize(&res, requiredsize)) {
6559 Py_DECREF(repunicode);
6560 goto onError;
6561 }
6562 str = PyBytes_AS_STRING(res) + respos;
6563 ressize = requiredsize;
6564 }
6565 /* check if there is anything unencodable in the replacement
6566 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006567 for (i = 0; repsize-->0; ++i, ++str) {
6568 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006569 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006570 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006571 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006572 Py_DECREF(repunicode);
6573 goto onError;
6574 }
6575 *str = (char)c;
6576 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006577 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006578 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006579 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006580 }
6581 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006582 /* Resize if we allocated to much */
6583 size = str - PyBytes_AS_STRING(res);
6584 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006585 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006586 if (_PyBytes_Resize(&res, size) < 0)
6587 goto onError;
6588 }
6589
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006590 Py_XDECREF(errorHandler);
6591 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006592 return res;
6593
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006594 overflow:
6595 PyErr_SetString(PyExc_OverflowError,
6596 "encoded result is too long for a Python string");
6597
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006598 onError:
6599 Py_XDECREF(res);
6600 Py_XDECREF(errorHandler);
6601 Py_XDECREF(exc);
6602 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006603}
6604
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006605/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006606PyObject *
6607PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006608 Py_ssize_t size,
6609 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006610{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006611 PyObject *result;
6612 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6613 if (unicode == NULL)
6614 return NULL;
6615 result = unicode_encode_ucs1(unicode, errors, 256);
6616 Py_DECREF(unicode);
6617 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006618}
6619
Alexander Belopolsky40018472011-02-26 01:02:56 +00006620PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006621_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006622{
6623 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006624 PyErr_BadArgument();
6625 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006626 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006627 if (PyUnicode_READY(unicode) == -1)
6628 return NULL;
6629 /* Fast path: if it is a one-byte string, construct
6630 bytes object directly. */
6631 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6632 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6633 PyUnicode_GET_LENGTH(unicode));
6634 /* Non-Latin-1 characters present. Defer to above function to
6635 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006636 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006637}
6638
6639PyObject*
6640PyUnicode_AsLatin1String(PyObject *unicode)
6641{
6642 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006643}
6644
6645/* --- 7-bit ASCII Codec -------------------------------------------------- */
6646
Alexander Belopolsky40018472011-02-26 01:02:56 +00006647PyObject *
6648PyUnicode_DecodeASCII(const char *s,
6649 Py_ssize_t size,
6650 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006651{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006652 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006653 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006654 int kind;
6655 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006656 Py_ssize_t startinpos;
6657 Py_ssize_t endinpos;
6658 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006659 const char *e;
6660 PyObject *errorHandler = NULL;
6661 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006662
Guido van Rossumd57fd912000-03-10 22:53:23 +00006663 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006664 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006665
Guido van Rossumd57fd912000-03-10 22:53:23 +00006666 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006667 if (size == 1 && (unsigned char)s[0] < 128)
6668 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006669
Victor Stinner8f674cc2013-04-17 23:02:17 +02006670 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006671 writer.min_length = size;
6672 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006673 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006674
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006675 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006676 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006677 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006678 writer.pos = outpos;
6679 if (writer.pos == size)
6680 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006681
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006682 s += writer.pos;
6683 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006684 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006685 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006686 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006687 PyUnicode_WRITE(kind, data, writer.pos, c);
6688 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006689 ++s;
6690 }
6691 else {
6692 startinpos = s-starts;
6693 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006694 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00006695 errors, &errorHandler,
6696 "ascii", "ordinal not in range(128)",
6697 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006698 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006699 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006700 kind = writer.kind;
6701 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006702 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006703 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006704 Py_XDECREF(errorHandler);
6705 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006706 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006707
Benjamin Peterson29060642009-01-31 22:14:21 +00006708 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006709 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006710 Py_XDECREF(errorHandler);
6711 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006712 return NULL;
6713}
6714
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006715/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006716PyObject *
6717PyUnicode_EncodeASCII(const Py_UNICODE *p,
6718 Py_ssize_t size,
6719 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006720{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006721 PyObject *result;
6722 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6723 if (unicode == NULL)
6724 return NULL;
6725 result = unicode_encode_ucs1(unicode, errors, 128);
6726 Py_DECREF(unicode);
6727 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006728}
6729
Alexander Belopolsky40018472011-02-26 01:02:56 +00006730PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006731_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006732{
6733 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006734 PyErr_BadArgument();
6735 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006736 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006737 if (PyUnicode_READY(unicode) == -1)
6738 return NULL;
6739 /* Fast path: if it is an ASCII-only string, construct bytes object
6740 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02006741 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006742 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6743 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006744 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006745}
6746
6747PyObject *
6748PyUnicode_AsASCIIString(PyObject *unicode)
6749{
6750 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006751}
6752
Victor Stinner99b95382011-07-04 14:23:54 +02006753#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006754
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006755/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006756
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006757#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006758#define NEED_RETRY
6759#endif
6760
Victor Stinner3a50e702011-10-18 21:21:00 +02006761#ifndef WC_ERR_INVALID_CHARS
6762# define WC_ERR_INVALID_CHARS 0x0080
6763#endif
6764
6765static char*
6766code_page_name(UINT code_page, PyObject **obj)
6767{
6768 *obj = NULL;
6769 if (code_page == CP_ACP)
6770 return "mbcs";
6771 if (code_page == CP_UTF7)
6772 return "CP_UTF7";
6773 if (code_page == CP_UTF8)
6774 return "CP_UTF8";
6775
6776 *obj = PyBytes_FromFormat("cp%u", code_page);
6777 if (*obj == NULL)
6778 return NULL;
6779 return PyBytes_AS_STRING(*obj);
6780}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006781
Victor Stinner3a50e702011-10-18 21:21:00 +02006782static DWORD
6783decode_code_page_flags(UINT code_page)
6784{
6785 if (code_page == CP_UTF7) {
6786 /* The CP_UTF7 decoder only supports flags=0 */
6787 return 0;
6788 }
6789 else
6790 return MB_ERR_INVALID_CHARS;
6791}
6792
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006793/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006794 * Decode a byte string from a Windows code page into unicode object in strict
6795 * mode.
6796 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006797 * Returns consumed size if succeed, returns -2 on decode error, or raise an
6798 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006799 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006800static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006801decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006802 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006803 const char *in,
6804 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006805{
Victor Stinner3a50e702011-10-18 21:21:00 +02006806 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006807 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006808 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006809
6810 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006811 assert(insize > 0);
6812 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6813 if (outsize <= 0)
6814 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006815
6816 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006817 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01006818 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006819 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006820 if (*v == NULL)
6821 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006822 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006823 }
6824 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006825 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006826 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01006827 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006828 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006829 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006830 }
6831
6832 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006833 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6834 if (outsize <= 0)
6835 goto error;
6836 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006837
Victor Stinner3a50e702011-10-18 21:21:00 +02006838error:
6839 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6840 return -2;
6841 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006842 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006843}
6844
Victor Stinner3a50e702011-10-18 21:21:00 +02006845/*
6846 * Decode a byte string from a code page into unicode object with an error
6847 * handler.
6848 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006849 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02006850 * UnicodeDecodeError exception and returns -1 on error.
6851 */
6852static int
6853decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006854 PyObject **v,
6855 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01006856 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02006857{
6858 const char *startin = in;
6859 const char *endin = in + size;
6860 const DWORD flags = decode_code_page_flags(code_page);
6861 /* Ideally, we should get reason from FormatMessage. This is the Windows
6862 2000 English version of the message. */
6863 const char *reason = "No mapping for the Unicode character exists "
6864 "in the target code page.";
6865 /* each step cannot decode more than 1 character, but a character can be
6866 represented as a surrogate pair */
6867 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02006868 int insize;
6869 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02006870 PyObject *errorHandler = NULL;
6871 PyObject *exc = NULL;
6872 PyObject *encoding_obj = NULL;
6873 char *encoding;
6874 DWORD err;
6875 int ret = -1;
6876
6877 assert(size > 0);
6878
6879 encoding = code_page_name(code_page, &encoding_obj);
6880 if (encoding == NULL)
6881 return -1;
6882
Victor Stinner7d00cc12014-03-17 23:08:06 +01006883 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02006884 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6885 UnicodeDecodeError. */
6886 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6887 if (exc != NULL) {
6888 PyCodec_StrictErrors(exc);
6889 Py_CLEAR(exc);
6890 }
6891 goto error;
6892 }
6893
6894 if (*v == NULL) {
6895 /* Create unicode object */
6896 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6897 PyErr_NoMemory();
6898 goto error;
6899 }
Victor Stinnerab595942011-12-17 04:59:06 +01006900 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006901 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006902 if (*v == NULL)
6903 goto error;
6904 startout = PyUnicode_AS_UNICODE(*v);
6905 }
6906 else {
6907 /* Extend unicode object */
6908 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6909 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6910 PyErr_NoMemory();
6911 goto error;
6912 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006913 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006914 goto error;
6915 startout = PyUnicode_AS_UNICODE(*v) + n;
6916 }
6917
6918 /* Decode the byte string character per character */
6919 out = startout;
6920 while (in < endin)
6921 {
6922 /* Decode a character */
6923 insize = 1;
6924 do
6925 {
6926 outsize = MultiByteToWideChar(code_page, flags,
6927 in, insize,
6928 buffer, Py_ARRAY_LENGTH(buffer));
6929 if (outsize > 0)
6930 break;
6931 err = GetLastError();
6932 if (err != ERROR_NO_UNICODE_TRANSLATION
6933 && err != ERROR_INSUFFICIENT_BUFFER)
6934 {
6935 PyErr_SetFromWindowsErr(0);
6936 goto error;
6937 }
6938 insize++;
6939 }
6940 /* 4=maximum length of a UTF-8 sequence */
6941 while (insize <= 4 && (in + insize) <= endin);
6942
6943 if (outsize <= 0) {
6944 Py_ssize_t startinpos, endinpos, outpos;
6945
Victor Stinner7d00cc12014-03-17 23:08:06 +01006946 /* last character in partial decode? */
6947 if (in + insize >= endin && !final)
6948 break;
6949
Victor Stinner3a50e702011-10-18 21:21:00 +02006950 startinpos = in - startin;
6951 endinpos = startinpos + 1;
6952 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006953 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02006954 errors, &errorHandler,
6955 encoding, reason,
6956 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01006957 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02006958 {
6959 goto error;
6960 }
Victor Stinner596a6c42011-11-09 00:02:18 +01006961 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02006962 }
6963 else {
6964 in += insize;
6965 memcpy(out, buffer, outsize * sizeof(wchar_t));
6966 out += outsize;
6967 }
6968 }
6969
6970 /* write a NUL character at the end */
6971 *out = 0;
6972
6973 /* Extend unicode object */
6974 outsize = out - startout;
6975 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01006976 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006977 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02006978 /* (in - startin) <= size and size is an int */
6979 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02006980
6981error:
6982 Py_XDECREF(encoding_obj);
6983 Py_XDECREF(errorHandler);
6984 Py_XDECREF(exc);
6985 return ret;
6986}
6987
Victor Stinner3a50e702011-10-18 21:21:00 +02006988static PyObject *
6989decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006990 const char *s, Py_ssize_t size,
6991 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006992{
Victor Stinner76a31a62011-11-04 00:05:13 +01006993 PyObject *v = NULL;
6994 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006995
Victor Stinner3a50e702011-10-18 21:21:00 +02006996 if (code_page < 0) {
6997 PyErr_SetString(PyExc_ValueError, "invalid code page number");
6998 return NULL;
6999 }
7000
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007001 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007002 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007003
Victor Stinner76a31a62011-11-04 00:05:13 +01007004 do
7005 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007006#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007007 if (size > INT_MAX) {
7008 chunk_size = INT_MAX;
7009 final = 0;
7010 done = 0;
7011 }
7012 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007013#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007014 {
7015 chunk_size = (int)size;
7016 final = (consumed == NULL);
7017 done = 1;
7018 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007019
Victor Stinner76a31a62011-11-04 00:05:13 +01007020 if (chunk_size == 0 && done) {
7021 if (v != NULL)
7022 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007023 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007024 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007025
Victor Stinner76a31a62011-11-04 00:05:13 +01007026 converted = decode_code_page_strict(code_page, &v,
7027 s, chunk_size);
7028 if (converted == -2)
7029 converted = decode_code_page_errors(code_page, &v,
7030 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007031 errors, final);
7032 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007033
7034 if (converted < 0) {
7035 Py_XDECREF(v);
7036 return NULL;
7037 }
7038
7039 if (consumed)
7040 *consumed += converted;
7041
7042 s += converted;
7043 size -= converted;
7044 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007045
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007046 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007047}
7048
Alexander Belopolsky40018472011-02-26 01:02:56 +00007049PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007050PyUnicode_DecodeCodePageStateful(int code_page,
7051 const char *s,
7052 Py_ssize_t size,
7053 const char *errors,
7054 Py_ssize_t *consumed)
7055{
7056 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7057}
7058
7059PyObject *
7060PyUnicode_DecodeMBCSStateful(const char *s,
7061 Py_ssize_t size,
7062 const char *errors,
7063 Py_ssize_t *consumed)
7064{
7065 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7066}
7067
7068PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007069PyUnicode_DecodeMBCS(const char *s,
7070 Py_ssize_t size,
7071 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007072{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007073 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7074}
7075
Victor Stinner3a50e702011-10-18 21:21:00 +02007076static DWORD
7077encode_code_page_flags(UINT code_page, const char *errors)
7078{
7079 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007080 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007081 }
7082 else if (code_page == CP_UTF7) {
7083 /* CP_UTF7 only supports flags=0 */
7084 return 0;
7085 }
7086 else {
7087 if (errors != NULL && strcmp(errors, "replace") == 0)
7088 return 0;
7089 else
7090 return WC_NO_BEST_FIT_CHARS;
7091 }
7092}
7093
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007094/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007095 * Encode a Unicode string to a Windows code page into a byte string in strict
7096 * mode.
7097 *
7098 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007099 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007100 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007101static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007102encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007103 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007104 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007105{
Victor Stinner554f3f02010-06-16 23:33:54 +00007106 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007107 BOOL *pusedDefaultChar = &usedDefaultChar;
7108 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007109 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007110 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007111 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007112 const DWORD flags = encode_code_page_flags(code_page, NULL);
7113 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007114 /* Create a substring so that we can get the UTF-16 representation
7115 of just the slice under consideration. */
7116 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007117
Martin v. Löwis3d325192011-11-04 18:23:06 +01007118 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007119
Victor Stinner3a50e702011-10-18 21:21:00 +02007120 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007121 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007122 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007123 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007124
Victor Stinner2fc507f2011-11-04 20:06:39 +01007125 substring = PyUnicode_Substring(unicode, offset, offset+len);
7126 if (substring == NULL)
7127 return -1;
7128 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7129 if (p == NULL) {
7130 Py_DECREF(substring);
7131 return -1;
7132 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007133 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007134
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007135 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007136 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007137 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007138 NULL, 0,
7139 NULL, pusedDefaultChar);
7140 if (outsize <= 0)
7141 goto error;
7142 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007143 if (pusedDefaultChar && *pusedDefaultChar) {
7144 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007145 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007146 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007147
Victor Stinner3a50e702011-10-18 21:21:00 +02007148 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007149 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007150 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007151 if (*outbytes == NULL) {
7152 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007153 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007154 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007155 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007156 }
7157 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007158 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007159 const Py_ssize_t n = PyBytes_Size(*outbytes);
7160 if (outsize > PY_SSIZE_T_MAX - n) {
7161 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007162 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007163 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007164 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007165 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7166 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007167 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007168 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007169 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007170 }
7171
7172 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007173 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007174 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007175 out, outsize,
7176 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007177 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007178 if (outsize <= 0)
7179 goto error;
7180 if (pusedDefaultChar && *pusedDefaultChar)
7181 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007182 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007183
Victor Stinner3a50e702011-10-18 21:21:00 +02007184error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007185 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007186 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7187 return -2;
7188 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007189 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007190}
7191
Victor Stinner3a50e702011-10-18 21:21:00 +02007192/*
7193 * Encode a Unicode string to a Windows code page into a byte string using a
7194 * error handler.
7195 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007196 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007197 * -1 on other error.
7198 */
7199static int
7200encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007201 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007202 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007203{
Victor Stinner3a50e702011-10-18 21:21:00 +02007204 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007205 Py_ssize_t pos = unicode_offset;
7206 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007207 /* Ideally, we should get reason from FormatMessage. This is the Windows
7208 2000 English version of the message. */
7209 const char *reason = "invalid character";
7210 /* 4=maximum length of a UTF-8 sequence */
7211 char buffer[4];
7212 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7213 Py_ssize_t outsize;
7214 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007215 PyObject *errorHandler = NULL;
7216 PyObject *exc = NULL;
7217 PyObject *encoding_obj = NULL;
7218 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007219 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007220 PyObject *rep;
7221 int ret = -1;
7222
7223 assert(insize > 0);
7224
7225 encoding = code_page_name(code_page, &encoding_obj);
7226 if (encoding == NULL)
7227 return -1;
7228
7229 if (errors == NULL || strcmp(errors, "strict") == 0) {
7230 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7231 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007232 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007233 if (exc != NULL) {
7234 PyCodec_StrictErrors(exc);
7235 Py_DECREF(exc);
7236 }
7237 Py_XDECREF(encoding_obj);
7238 return -1;
7239 }
7240
7241 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7242 pusedDefaultChar = &usedDefaultChar;
7243 else
7244 pusedDefaultChar = NULL;
7245
7246 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7247 PyErr_NoMemory();
7248 goto error;
7249 }
7250 outsize = insize * Py_ARRAY_LENGTH(buffer);
7251
7252 if (*outbytes == NULL) {
7253 /* Create string object */
7254 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7255 if (*outbytes == NULL)
7256 goto error;
7257 out = PyBytes_AS_STRING(*outbytes);
7258 }
7259 else {
7260 /* Extend string object */
7261 Py_ssize_t n = PyBytes_Size(*outbytes);
7262 if (n > PY_SSIZE_T_MAX - outsize) {
7263 PyErr_NoMemory();
7264 goto error;
7265 }
7266 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7267 goto error;
7268 out = PyBytes_AS_STRING(*outbytes) + n;
7269 }
7270
7271 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007272 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007273 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007274 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7275 wchar_t chars[2];
7276 int charsize;
7277 if (ch < 0x10000) {
7278 chars[0] = (wchar_t)ch;
7279 charsize = 1;
7280 }
7281 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007282 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7283 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007284 charsize = 2;
7285 }
7286
Victor Stinner3a50e702011-10-18 21:21:00 +02007287 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007288 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007289 buffer, Py_ARRAY_LENGTH(buffer),
7290 NULL, pusedDefaultChar);
7291 if (outsize > 0) {
7292 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7293 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007294 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007295 memcpy(out, buffer, outsize);
7296 out += outsize;
7297 continue;
7298 }
7299 }
7300 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7301 PyErr_SetFromWindowsErr(0);
7302 goto error;
7303 }
7304
Victor Stinner3a50e702011-10-18 21:21:00 +02007305 rep = unicode_encode_call_errorhandler(
7306 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007307 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007308 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007309 if (rep == NULL)
7310 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007311 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007312
7313 if (PyBytes_Check(rep)) {
7314 outsize = PyBytes_GET_SIZE(rep);
7315 if (outsize != 1) {
7316 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7317 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7318 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7319 Py_DECREF(rep);
7320 goto error;
7321 }
7322 out = PyBytes_AS_STRING(*outbytes) + offset;
7323 }
7324 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7325 out += outsize;
7326 }
7327 else {
7328 Py_ssize_t i;
7329 enum PyUnicode_Kind kind;
7330 void *data;
7331
Benjamin Petersonbac79492012-01-14 13:34:47 -05007332 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007333 Py_DECREF(rep);
7334 goto error;
7335 }
7336
7337 outsize = PyUnicode_GET_LENGTH(rep);
7338 if (outsize != 1) {
7339 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7340 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7341 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7342 Py_DECREF(rep);
7343 goto error;
7344 }
7345 out = PyBytes_AS_STRING(*outbytes) + offset;
7346 }
7347 kind = PyUnicode_KIND(rep);
7348 data = PyUnicode_DATA(rep);
7349 for (i=0; i < outsize; i++) {
7350 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7351 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007352 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007353 encoding, unicode,
7354 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007355 "unable to encode error handler result to ASCII");
7356 Py_DECREF(rep);
7357 goto error;
7358 }
7359 *out = (unsigned char)ch;
7360 out++;
7361 }
7362 }
7363 Py_DECREF(rep);
7364 }
7365 /* write a NUL byte */
7366 *out = 0;
7367 outsize = out - PyBytes_AS_STRING(*outbytes);
7368 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7369 if (_PyBytes_Resize(outbytes, outsize) < 0)
7370 goto error;
7371 ret = 0;
7372
7373error:
7374 Py_XDECREF(encoding_obj);
7375 Py_XDECREF(errorHandler);
7376 Py_XDECREF(exc);
7377 return ret;
7378}
7379
Victor Stinner3a50e702011-10-18 21:21:00 +02007380static PyObject *
7381encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007382 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007383 const char *errors)
7384{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007385 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007386 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007387 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007388 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007389
Victor Stinner29dacf22015-01-26 16:41:32 +01007390 if (!PyUnicode_Check(unicode)) {
7391 PyErr_BadArgument();
7392 return NULL;
7393 }
7394
Benjamin Petersonbac79492012-01-14 13:34:47 -05007395 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007396 return NULL;
7397 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007398
Victor Stinner3a50e702011-10-18 21:21:00 +02007399 if (code_page < 0) {
7400 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7401 return NULL;
7402 }
7403
Martin v. Löwis3d325192011-11-04 18:23:06 +01007404 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007405 return PyBytes_FromStringAndSize(NULL, 0);
7406
Victor Stinner7581cef2011-11-03 22:32:33 +01007407 offset = 0;
7408 do
7409 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007410#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007411 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007412 chunks. */
7413 if (len > INT_MAX/2) {
7414 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007415 done = 0;
7416 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007417 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007418#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007419 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007420 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007421 done = 1;
7422 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007423
Victor Stinner76a31a62011-11-04 00:05:13 +01007424 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007425 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007426 errors);
7427 if (ret == -2)
7428 ret = encode_code_page_errors(code_page, &outbytes,
7429 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007430 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007431 if (ret < 0) {
7432 Py_XDECREF(outbytes);
7433 return NULL;
7434 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007435
Victor Stinner7581cef2011-11-03 22:32:33 +01007436 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007437 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007438 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007439
Victor Stinner3a50e702011-10-18 21:21:00 +02007440 return outbytes;
7441}
7442
7443PyObject *
7444PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7445 Py_ssize_t size,
7446 const char *errors)
7447{
Victor Stinner7581cef2011-11-03 22:32:33 +01007448 PyObject *unicode, *res;
7449 unicode = PyUnicode_FromUnicode(p, size);
7450 if (unicode == NULL)
7451 return NULL;
7452 res = encode_code_page(CP_ACP, unicode, errors);
7453 Py_DECREF(unicode);
7454 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007455}
7456
7457PyObject *
7458PyUnicode_EncodeCodePage(int code_page,
7459 PyObject *unicode,
7460 const char *errors)
7461{
Victor Stinner7581cef2011-11-03 22:32:33 +01007462 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007463}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007464
Alexander Belopolsky40018472011-02-26 01:02:56 +00007465PyObject *
7466PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007467{
Victor Stinner7581cef2011-11-03 22:32:33 +01007468 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007469}
7470
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007471#undef NEED_RETRY
7472
Victor Stinner99b95382011-07-04 14:23:54 +02007473#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007474
Guido van Rossumd57fd912000-03-10 22:53:23 +00007475/* --- Character Mapping Codec -------------------------------------------- */
7476
Victor Stinnerfb161b12013-04-18 01:44:27 +02007477static int
7478charmap_decode_string(const char *s,
7479 Py_ssize_t size,
7480 PyObject *mapping,
7481 const char *errors,
7482 _PyUnicodeWriter *writer)
7483{
7484 const char *starts = s;
7485 const char *e;
7486 Py_ssize_t startinpos, endinpos;
7487 PyObject *errorHandler = NULL, *exc = NULL;
7488 Py_ssize_t maplen;
7489 enum PyUnicode_Kind mapkind;
7490 void *mapdata;
7491 Py_UCS4 x;
7492 unsigned char ch;
7493
7494 if (PyUnicode_READY(mapping) == -1)
7495 return -1;
7496
7497 maplen = PyUnicode_GET_LENGTH(mapping);
7498 mapdata = PyUnicode_DATA(mapping);
7499 mapkind = PyUnicode_KIND(mapping);
7500
7501 e = s + size;
7502
7503 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7504 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7505 * is disabled in encoding aliases, latin1 is preferred because
7506 * its implementation is faster. */
7507 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7508 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7509 Py_UCS4 maxchar = writer->maxchar;
7510
7511 assert (writer->kind == PyUnicode_1BYTE_KIND);
7512 while (s < e) {
7513 ch = *s;
7514 x = mapdata_ucs1[ch];
7515 if (x > maxchar) {
7516 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7517 goto onError;
7518 maxchar = writer->maxchar;
7519 outdata = (Py_UCS1 *)writer->data;
7520 }
7521 outdata[writer->pos] = x;
7522 writer->pos++;
7523 ++s;
7524 }
7525 return 0;
7526 }
7527
7528 while (s < e) {
7529 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7530 enum PyUnicode_Kind outkind = writer->kind;
7531 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7532 if (outkind == PyUnicode_1BYTE_KIND) {
7533 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7534 Py_UCS4 maxchar = writer->maxchar;
7535 while (s < e) {
7536 ch = *s;
7537 x = mapdata_ucs2[ch];
7538 if (x > maxchar)
7539 goto Error;
7540 outdata[writer->pos] = x;
7541 writer->pos++;
7542 ++s;
7543 }
7544 break;
7545 }
7546 else if (outkind == PyUnicode_2BYTE_KIND) {
7547 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7548 while (s < e) {
7549 ch = *s;
7550 x = mapdata_ucs2[ch];
7551 if (x == 0xFFFE)
7552 goto Error;
7553 outdata[writer->pos] = x;
7554 writer->pos++;
7555 ++s;
7556 }
7557 break;
7558 }
7559 }
7560 ch = *s;
7561
7562 if (ch < maplen)
7563 x = PyUnicode_READ(mapkind, mapdata, ch);
7564 else
7565 x = 0xfffe; /* invalid value */
7566Error:
7567 if (x == 0xfffe)
7568 {
7569 /* undefined mapping */
7570 startinpos = s-starts;
7571 endinpos = startinpos+1;
7572 if (unicode_decode_call_errorhandler_writer(
7573 errors, &errorHandler,
7574 "charmap", "character maps to <undefined>",
7575 &starts, &e, &startinpos, &endinpos, &exc, &s,
7576 writer)) {
7577 goto onError;
7578 }
7579 continue;
7580 }
7581
7582 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7583 goto onError;
7584 ++s;
7585 }
7586 Py_XDECREF(errorHandler);
7587 Py_XDECREF(exc);
7588 return 0;
7589
7590onError:
7591 Py_XDECREF(errorHandler);
7592 Py_XDECREF(exc);
7593 return -1;
7594}
7595
7596static int
7597charmap_decode_mapping(const char *s,
7598 Py_ssize_t size,
7599 PyObject *mapping,
7600 const char *errors,
7601 _PyUnicodeWriter *writer)
7602{
7603 const char *starts = s;
7604 const char *e;
7605 Py_ssize_t startinpos, endinpos;
7606 PyObject *errorHandler = NULL, *exc = NULL;
7607 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007608 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007609
7610 e = s + size;
7611
7612 while (s < e) {
7613 ch = *s;
7614
7615 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7616 key = PyLong_FromLong((long)ch);
7617 if (key == NULL)
7618 goto onError;
7619
7620 item = PyObject_GetItem(mapping, key);
7621 Py_DECREF(key);
7622 if (item == NULL) {
7623 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7624 /* No mapping found means: mapping is undefined. */
7625 PyErr_Clear();
7626 goto Undefined;
7627 } else
7628 goto onError;
7629 }
7630
7631 /* Apply mapping */
7632 if (item == Py_None)
7633 goto Undefined;
7634 if (PyLong_Check(item)) {
7635 long value = PyLong_AS_LONG(item);
7636 if (value == 0xFFFE)
7637 goto Undefined;
7638 if (value < 0 || value > MAX_UNICODE) {
7639 PyErr_Format(PyExc_TypeError,
7640 "character mapping must be in range(0x%lx)",
7641 (unsigned long)MAX_UNICODE + 1);
7642 goto onError;
7643 }
7644
7645 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7646 goto onError;
7647 }
7648 else if (PyUnicode_Check(item)) {
7649 if (PyUnicode_READY(item) == -1)
7650 goto onError;
7651 if (PyUnicode_GET_LENGTH(item) == 1) {
7652 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7653 if (value == 0xFFFE)
7654 goto Undefined;
7655 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7656 goto onError;
7657 }
7658 else {
7659 writer->overallocate = 1;
7660 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7661 goto onError;
7662 }
7663 }
7664 else {
7665 /* wrong return value */
7666 PyErr_SetString(PyExc_TypeError,
7667 "character mapping must return integer, None or str");
7668 goto onError;
7669 }
7670 Py_CLEAR(item);
7671 ++s;
7672 continue;
7673
7674Undefined:
7675 /* undefined mapping */
7676 Py_CLEAR(item);
7677 startinpos = s-starts;
7678 endinpos = startinpos+1;
7679 if (unicode_decode_call_errorhandler_writer(
7680 errors, &errorHandler,
7681 "charmap", "character maps to <undefined>",
7682 &starts, &e, &startinpos, &endinpos, &exc, &s,
7683 writer)) {
7684 goto onError;
7685 }
7686 }
7687 Py_XDECREF(errorHandler);
7688 Py_XDECREF(exc);
7689 return 0;
7690
7691onError:
7692 Py_XDECREF(item);
7693 Py_XDECREF(errorHandler);
7694 Py_XDECREF(exc);
7695 return -1;
7696}
7697
Alexander Belopolsky40018472011-02-26 01:02:56 +00007698PyObject *
7699PyUnicode_DecodeCharmap(const char *s,
7700 Py_ssize_t size,
7701 PyObject *mapping,
7702 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007703{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007704 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007705
Guido van Rossumd57fd912000-03-10 22:53:23 +00007706 /* Default to Latin-1 */
7707 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007708 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007709
Guido van Rossumd57fd912000-03-10 22:53:23 +00007710 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007711 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007712 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007713 writer.min_length = size;
7714 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007715 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007716
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007717 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007718 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
7719 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007720 }
7721 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007722 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
7723 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007724 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007725 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007726
Benjamin Peterson29060642009-01-31 22:14:21 +00007727 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007728 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007729 return NULL;
7730}
7731
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007732/* Charmap encoding: the lookup table */
7733
Alexander Belopolsky40018472011-02-26 01:02:56 +00007734struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007735 PyObject_HEAD
7736 unsigned char level1[32];
7737 int count2, count3;
7738 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007739};
7740
7741static PyObject*
7742encoding_map_size(PyObject *obj, PyObject* args)
7743{
7744 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007745 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007746 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007747}
7748
7749static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007750 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007751 PyDoc_STR("Return the size (in bytes) of this object") },
7752 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007753};
7754
7755static void
7756encoding_map_dealloc(PyObject* o)
7757{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007758 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007759}
7760
7761static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007762 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007763 "EncodingMap", /*tp_name*/
7764 sizeof(struct encoding_map), /*tp_basicsize*/
7765 0, /*tp_itemsize*/
7766 /* methods */
7767 encoding_map_dealloc, /*tp_dealloc*/
7768 0, /*tp_print*/
7769 0, /*tp_getattr*/
7770 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007771 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007772 0, /*tp_repr*/
7773 0, /*tp_as_number*/
7774 0, /*tp_as_sequence*/
7775 0, /*tp_as_mapping*/
7776 0, /*tp_hash*/
7777 0, /*tp_call*/
7778 0, /*tp_str*/
7779 0, /*tp_getattro*/
7780 0, /*tp_setattro*/
7781 0, /*tp_as_buffer*/
7782 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7783 0, /*tp_doc*/
7784 0, /*tp_traverse*/
7785 0, /*tp_clear*/
7786 0, /*tp_richcompare*/
7787 0, /*tp_weaklistoffset*/
7788 0, /*tp_iter*/
7789 0, /*tp_iternext*/
7790 encoding_map_methods, /*tp_methods*/
7791 0, /*tp_members*/
7792 0, /*tp_getset*/
7793 0, /*tp_base*/
7794 0, /*tp_dict*/
7795 0, /*tp_descr_get*/
7796 0, /*tp_descr_set*/
7797 0, /*tp_dictoffset*/
7798 0, /*tp_init*/
7799 0, /*tp_alloc*/
7800 0, /*tp_new*/
7801 0, /*tp_free*/
7802 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007803};
7804
7805PyObject*
7806PyUnicode_BuildEncodingMap(PyObject* string)
7807{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007808 PyObject *result;
7809 struct encoding_map *mresult;
7810 int i;
7811 int need_dict = 0;
7812 unsigned char level1[32];
7813 unsigned char level2[512];
7814 unsigned char *mlevel1, *mlevel2, *mlevel3;
7815 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007816 int kind;
7817 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007818 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007819 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007820
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007821 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007822 PyErr_BadArgument();
7823 return NULL;
7824 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007825 kind = PyUnicode_KIND(string);
7826 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007827 length = PyUnicode_GET_LENGTH(string);
7828 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007829 memset(level1, 0xFF, sizeof level1);
7830 memset(level2, 0xFF, sizeof level2);
7831
7832 /* If there isn't a one-to-one mapping of NULL to \0,
7833 or if there are non-BMP characters, we need to use
7834 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007835 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007836 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007837 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007838 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007839 ch = PyUnicode_READ(kind, data, i);
7840 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007841 need_dict = 1;
7842 break;
7843 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007844 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007845 /* unmapped character */
7846 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007847 l1 = ch >> 11;
7848 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007849 if (level1[l1] == 0xFF)
7850 level1[l1] = count2++;
7851 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007852 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007853 }
7854
7855 if (count2 >= 0xFF || count3 >= 0xFF)
7856 need_dict = 1;
7857
7858 if (need_dict) {
7859 PyObject *result = PyDict_New();
7860 PyObject *key, *value;
7861 if (!result)
7862 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007863 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007864 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007865 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007866 if (!key || !value)
7867 goto failed1;
7868 if (PyDict_SetItem(result, key, value) == -1)
7869 goto failed1;
7870 Py_DECREF(key);
7871 Py_DECREF(value);
7872 }
7873 return result;
7874 failed1:
7875 Py_XDECREF(key);
7876 Py_XDECREF(value);
7877 Py_DECREF(result);
7878 return NULL;
7879 }
7880
7881 /* Create a three-level trie */
7882 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7883 16*count2 + 128*count3 - 1);
7884 if (!result)
7885 return PyErr_NoMemory();
7886 PyObject_Init(result, &EncodingMapType);
7887 mresult = (struct encoding_map*)result;
7888 mresult->count2 = count2;
7889 mresult->count3 = count3;
7890 mlevel1 = mresult->level1;
7891 mlevel2 = mresult->level23;
7892 mlevel3 = mresult->level23 + 16*count2;
7893 memcpy(mlevel1, level1, 32);
7894 memset(mlevel2, 0xFF, 16*count2);
7895 memset(mlevel3, 0, 128*count3);
7896 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007897 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007898 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007899 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7900 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007901 /* unmapped character */
7902 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007903 o1 = ch>>11;
7904 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007905 i2 = 16*mlevel1[o1] + o2;
7906 if (mlevel2[i2] == 0xFF)
7907 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007908 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007909 i3 = 128*mlevel2[i2] + o3;
7910 mlevel3[i3] = i;
7911 }
7912 return result;
7913}
7914
7915static int
Victor Stinner22168992011-11-20 17:09:18 +01007916encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007917{
7918 struct encoding_map *map = (struct encoding_map*)mapping;
7919 int l1 = c>>11;
7920 int l2 = (c>>7) & 0xF;
7921 int l3 = c & 0x7F;
7922 int i;
7923
Victor Stinner22168992011-11-20 17:09:18 +01007924 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007925 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007926 if (c == 0)
7927 return 0;
7928 /* level 1*/
7929 i = map->level1[l1];
7930 if (i == 0xFF) {
7931 return -1;
7932 }
7933 /* level 2*/
7934 i = map->level23[16*i+l2];
7935 if (i == 0xFF) {
7936 return -1;
7937 }
7938 /* level 3 */
7939 i = map->level23[16*map->count2 + 128*i + l3];
7940 if (i == 0) {
7941 return -1;
7942 }
7943 return i;
7944}
7945
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007946/* Lookup the character ch in the mapping. If the character
7947 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007948 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007949static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01007950charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007951{
Christian Heimes217cfd12007-12-02 14:31:20 +00007952 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007953 PyObject *x;
7954
7955 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007956 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007957 x = PyObject_GetItem(mapping, w);
7958 Py_DECREF(w);
7959 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007960 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7961 /* No mapping found means: mapping is undefined. */
7962 PyErr_Clear();
7963 x = Py_None;
7964 Py_INCREF(x);
7965 return x;
7966 } else
7967 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007968 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007969 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007970 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007971 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007972 long value = PyLong_AS_LONG(x);
7973 if (value < 0 || value > 255) {
7974 PyErr_SetString(PyExc_TypeError,
7975 "character mapping must be in range(256)");
7976 Py_DECREF(x);
7977 return NULL;
7978 }
7979 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007980 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007981 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007982 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007983 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007984 /* wrong return value */
7985 PyErr_Format(PyExc_TypeError,
7986 "character mapping must return integer, bytes or None, not %.400s",
7987 x->ob_type->tp_name);
7988 Py_DECREF(x);
7989 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007990 }
7991}
7992
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007993static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00007994charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007995{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007996 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
7997 /* exponentially overallocate to minimize reallocations */
7998 if (requiredsize < 2*outsize)
7999 requiredsize = 2*outsize;
8000 if (_PyBytes_Resize(outobj, requiredsize))
8001 return -1;
8002 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008003}
8004
Benjamin Peterson14339b62009-01-31 16:36:08 +00008005typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008006 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008007} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008008/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008009 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008010 space is available. Return a new reference to the object that
8011 was put in the output buffer, or Py_None, if the mapping was undefined
8012 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008013 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008014static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008015charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008016 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008017{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008018 PyObject *rep;
8019 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008020 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008021
Christian Heimes90aa7642007-12-19 02:45:37 +00008022 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008023 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008024 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008025 if (res == -1)
8026 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008027 if (outsize<requiredsize)
8028 if (charmapencode_resize(outobj, outpos, requiredsize))
8029 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008030 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008031 outstart[(*outpos)++] = (char)res;
8032 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008033 }
8034
8035 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008036 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008037 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008038 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008039 Py_DECREF(rep);
8040 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008041 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008042 if (PyLong_Check(rep)) {
8043 Py_ssize_t requiredsize = *outpos+1;
8044 if (outsize<requiredsize)
8045 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8046 Py_DECREF(rep);
8047 return enc_EXCEPTION;
8048 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008049 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008050 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008051 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008052 else {
8053 const char *repchars = PyBytes_AS_STRING(rep);
8054 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8055 Py_ssize_t requiredsize = *outpos+repsize;
8056 if (outsize<requiredsize)
8057 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8058 Py_DECREF(rep);
8059 return enc_EXCEPTION;
8060 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008061 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008062 memcpy(outstart + *outpos, repchars, repsize);
8063 *outpos += repsize;
8064 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008065 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008066 Py_DECREF(rep);
8067 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008068}
8069
8070/* handle an error in PyUnicode_EncodeCharmap
8071 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008072static int
8073charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008074 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008075 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008076 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008077 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008078{
8079 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008080 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008081 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008082 enum PyUnicode_Kind kind;
8083 void *data;
8084 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008085 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008086 Py_ssize_t collstartpos = *inpos;
8087 Py_ssize_t collendpos = *inpos+1;
8088 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008089 char *encoding = "charmap";
8090 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008091 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008092 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008093 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008094
Benjamin Petersonbac79492012-01-14 13:34:47 -05008095 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008096 return -1;
8097 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008098 /* find all unencodable characters */
8099 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008100 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008101 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008102 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008103 val = encoding_map_lookup(ch, mapping);
8104 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008105 break;
8106 ++collendpos;
8107 continue;
8108 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008109
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008110 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8111 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008112 if (rep==NULL)
8113 return -1;
8114 else if (rep!=Py_None) {
8115 Py_DECREF(rep);
8116 break;
8117 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008118 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008119 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008120 }
8121 /* cache callback name lookup
8122 * (if not done yet, i.e. it's the first error) */
8123 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008124 if ((errors==NULL) || (!strcmp(errors, "strict")))
8125 *known_errorHandler = 1;
8126 else if (!strcmp(errors, "replace"))
8127 *known_errorHandler = 2;
8128 else if (!strcmp(errors, "ignore"))
8129 *known_errorHandler = 3;
8130 else if (!strcmp(errors, "xmlcharrefreplace"))
8131 *known_errorHandler = 4;
8132 else
8133 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008134 }
8135 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008136 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008137 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008138 return -1;
8139 case 2: /* replace */
8140 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008141 x = charmapencode_output('?', mapping, res, respos);
8142 if (x==enc_EXCEPTION) {
8143 return -1;
8144 }
8145 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008146 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008147 return -1;
8148 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008149 }
8150 /* fall through */
8151 case 3: /* ignore */
8152 *inpos = collendpos;
8153 break;
8154 case 4: /* xmlcharrefreplace */
8155 /* generate replacement (temporarily (mis)uses p) */
8156 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008157 char buffer[2+29+1+1];
8158 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008159 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008160 for (cp = buffer; *cp; ++cp) {
8161 x = charmapencode_output(*cp, mapping, res, respos);
8162 if (x==enc_EXCEPTION)
8163 return -1;
8164 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008165 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008166 return -1;
8167 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008168 }
8169 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008170 *inpos = collendpos;
8171 break;
8172 default:
8173 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008174 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008175 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008176 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008177 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008178 if (PyBytes_Check(repunicode)) {
8179 /* Directly copy bytes result to output. */
8180 Py_ssize_t outsize = PyBytes_Size(*res);
8181 Py_ssize_t requiredsize;
8182 repsize = PyBytes_Size(repunicode);
8183 requiredsize = *respos + repsize;
8184 if (requiredsize > outsize)
8185 /* Make room for all additional bytes. */
8186 if (charmapencode_resize(res, respos, requiredsize)) {
8187 Py_DECREF(repunicode);
8188 return -1;
8189 }
8190 memcpy(PyBytes_AsString(*res) + *respos,
8191 PyBytes_AsString(repunicode), repsize);
8192 *respos += repsize;
8193 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008194 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008195 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008196 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008197 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008198 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008199 Py_DECREF(repunicode);
8200 return -1;
8201 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008202 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008203 data = PyUnicode_DATA(repunicode);
8204 kind = PyUnicode_KIND(repunicode);
8205 for (index = 0; index < repsize; index++) {
8206 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8207 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008208 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008209 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008210 return -1;
8211 }
8212 else if (x==enc_FAILED) {
8213 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008214 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008215 return -1;
8216 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008217 }
8218 *inpos = newpos;
8219 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008220 }
8221 return 0;
8222}
8223
Alexander Belopolsky40018472011-02-26 01:02:56 +00008224PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008225_PyUnicode_EncodeCharmap(PyObject *unicode,
8226 PyObject *mapping,
8227 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008228{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008229 /* output object */
8230 PyObject *res = NULL;
8231 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008232 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008233 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008234 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008235 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008236 PyObject *errorHandler = NULL;
8237 PyObject *exc = NULL;
8238 /* the following variable is used for caching string comparisons
8239 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8240 * 3=ignore, 4=xmlcharrefreplace */
8241 int known_errorHandler = -1;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008242 void *data;
8243 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008244
Benjamin Petersonbac79492012-01-14 13:34:47 -05008245 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008246 return NULL;
8247 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008248 data = PyUnicode_DATA(unicode);
8249 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008250
Guido van Rossumd57fd912000-03-10 22:53:23 +00008251 /* Default to Latin-1 */
8252 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008253 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008254
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008255 /* allocate enough for a simple encoding without
8256 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008257 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008258 if (res == NULL)
8259 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008260 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008261 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008262
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008263 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008264 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008265 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008266 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008267 if (x==enc_EXCEPTION) /* error */
8268 goto onError;
8269 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008270 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008271 &exc,
8272 &known_errorHandler, &errorHandler, errors,
8273 &res, &respos)) {
8274 goto onError;
8275 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008276 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008277 else
8278 /* done with this character => adjust input position */
8279 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008280 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008281
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008282 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008283 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008284 if (_PyBytes_Resize(&res, respos) < 0)
8285 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008286
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008287 Py_XDECREF(exc);
8288 Py_XDECREF(errorHandler);
8289 return res;
8290
Benjamin Peterson29060642009-01-31 22:14:21 +00008291 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008292 Py_XDECREF(res);
8293 Py_XDECREF(exc);
8294 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008295 return NULL;
8296}
8297
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008298/* Deprecated */
8299PyObject *
8300PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8301 Py_ssize_t size,
8302 PyObject *mapping,
8303 const char *errors)
8304{
8305 PyObject *result;
8306 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8307 if (unicode == NULL)
8308 return NULL;
8309 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8310 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008311 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008312}
8313
Alexander Belopolsky40018472011-02-26 01:02:56 +00008314PyObject *
8315PyUnicode_AsCharmapString(PyObject *unicode,
8316 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008317{
8318 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008319 PyErr_BadArgument();
8320 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008321 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008322 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008323}
8324
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008325/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008326static void
8327make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008328 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008329 Py_ssize_t startpos, Py_ssize_t endpos,
8330 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008331{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008332 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008333 *exceptionObject = _PyUnicodeTranslateError_Create(
8334 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008335 }
8336 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008337 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8338 goto onError;
8339 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8340 goto onError;
8341 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8342 goto onError;
8343 return;
8344 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008345 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008346 }
8347}
8348
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008349/* error handling callback helper:
8350 build arguments, call the callback and check the arguments,
8351 put the result into newpos and return the replacement string, which
8352 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008353static PyObject *
8354unicode_translate_call_errorhandler(const char *errors,
8355 PyObject **errorHandler,
8356 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008357 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008358 Py_ssize_t startpos, Py_ssize_t endpos,
8359 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008360{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008361 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008362
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008363 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008364 PyObject *restuple;
8365 PyObject *resunicode;
8366
8367 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008368 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008369 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008370 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008371 }
8372
8373 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008374 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008375 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008376 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008377
8378 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008379 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008380 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008381 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008382 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008383 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008384 Py_DECREF(restuple);
8385 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008386 }
8387 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008388 &resunicode, &i_newpos)) {
8389 Py_DECREF(restuple);
8390 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008391 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008392 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008393 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008394 else
8395 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008396 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008397 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008398 Py_DECREF(restuple);
8399 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008400 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008401 Py_INCREF(resunicode);
8402 Py_DECREF(restuple);
8403 return resunicode;
8404}
8405
8406/* Lookup the character ch in the mapping and put the result in result,
8407 which must be decrefed by the caller.
8408 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008409static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008410charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008411{
Christian Heimes217cfd12007-12-02 14:31:20 +00008412 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008413 PyObject *x;
8414
8415 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008416 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008417 x = PyObject_GetItem(mapping, w);
8418 Py_DECREF(w);
8419 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008420 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8421 /* No mapping found means: use 1:1 mapping. */
8422 PyErr_Clear();
8423 *result = NULL;
8424 return 0;
8425 } else
8426 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008427 }
8428 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008429 *result = x;
8430 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008431 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008432 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008433 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008434 if (value < 0 || value > MAX_UNICODE) {
8435 PyErr_Format(PyExc_ValueError,
8436 "character mapping must be in range(0x%x)",
8437 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008438 Py_DECREF(x);
8439 return -1;
8440 }
8441 *result = x;
8442 return 0;
8443 }
8444 else if (PyUnicode_Check(x)) {
8445 *result = x;
8446 return 0;
8447 }
8448 else {
8449 /* wrong return value */
8450 PyErr_SetString(PyExc_TypeError,
8451 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008452 Py_DECREF(x);
8453 return -1;
8454 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008455}
Victor Stinner1194ea02014-04-04 19:37:40 +02008456
8457/* lookup the character, write the result into the writer.
8458 Return 1 if the result was written into the writer, return 0 if the mapping
8459 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008460static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008461charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8462 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008463{
Victor Stinner1194ea02014-04-04 19:37:40 +02008464 PyObject *item;
8465
8466 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008467 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008468
8469 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008470 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008471 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008472 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008473 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008474 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008475 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008476
8477 if (item == Py_None) {
8478 Py_DECREF(item);
8479 return 0;
8480 }
8481
8482 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008483 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8484 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8485 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008486 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8487 Py_DECREF(item);
8488 return -1;
8489 }
8490 Py_DECREF(item);
8491 return 1;
8492 }
8493
8494 if (!PyUnicode_Check(item)) {
8495 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008496 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008497 }
8498
8499 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8500 Py_DECREF(item);
8501 return -1;
8502 }
8503
8504 Py_DECREF(item);
8505 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008506}
8507
Victor Stinner89a76ab2014-04-05 11:44:04 +02008508static int
8509unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8510 Py_UCS1 *translate)
8511{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008512 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008513 int ret = 0;
8514
Victor Stinner89a76ab2014-04-05 11:44:04 +02008515 if (charmaptranslate_lookup(ch, mapping, &item)) {
8516 return -1;
8517 }
8518
8519 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008520 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008521 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008522 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008523 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008524 /* not found => default to 1:1 mapping */
8525 translate[ch] = ch;
8526 return 1;
8527 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008528 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008529 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008530 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8531 used it */
8532 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008533 /* invalid character or character outside ASCII:
8534 skip the fast translate */
8535 goto exit;
8536 }
8537 translate[ch] = (Py_UCS1)replace;
8538 }
8539 else if (PyUnicode_Check(item)) {
8540 Py_UCS4 replace;
8541
8542 if (PyUnicode_READY(item) == -1) {
8543 Py_DECREF(item);
8544 return -1;
8545 }
8546 if (PyUnicode_GET_LENGTH(item) != 1)
8547 goto exit;
8548
8549 replace = PyUnicode_READ_CHAR(item, 0);
8550 if (replace > 127)
8551 goto exit;
8552 translate[ch] = (Py_UCS1)replace;
8553 }
8554 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008555 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008556 goto exit;
8557 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008558 ret = 1;
8559
Benjamin Peterson1365de72014-04-07 20:15:41 -04008560 exit:
8561 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008562 return ret;
8563}
8564
8565/* Fast path for ascii => ascii translation. Return 1 if the whole string
8566 was translated into writer, return 0 if the input string was partially
8567 translated into writer, raise an exception and return -1 on error. */
8568static int
8569unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner872b2912014-04-05 14:27:07 +02008570 _PyUnicodeWriter *writer, int ignore)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008571{
Victor Stinner872b2912014-04-05 14:27:07 +02008572 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008573 Py_ssize_t len;
8574 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008575 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008576
8577 if (PyUnicode_READY(input) == -1)
8578 return -1;
8579 if (!PyUnicode_IS_ASCII(input))
8580 return 0;
8581 len = PyUnicode_GET_LENGTH(input);
8582
Victor Stinner872b2912014-04-05 14:27:07 +02008583 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008584
8585 in = PyUnicode_1BYTE_DATA(input);
8586 end = in + len;
8587
8588 assert(PyUnicode_IS_ASCII(writer->buffer));
8589 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8590 out = PyUnicode_1BYTE_DATA(writer->buffer);
8591
Victor Stinner872b2912014-04-05 14:27:07 +02008592 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008593 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008594 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008595 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008596 int translate = unicode_fast_translate_lookup(mapping, ch,
8597 ascii_table);
8598 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008599 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008600 if (translate == 0)
8601 goto exit;
8602 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008603 }
Victor Stinner872b2912014-04-05 14:27:07 +02008604 if (ch2 == 0xfe) {
8605 if (ignore)
8606 continue;
8607 goto exit;
8608 }
8609 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008610 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008611 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008612 }
Victor Stinner872b2912014-04-05 14:27:07 +02008613 res = 1;
8614
8615exit:
8616 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
8617 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008618}
8619
Alexander Belopolsky40018472011-02-26 01:02:56 +00008620PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008621_PyUnicode_TranslateCharmap(PyObject *input,
8622 PyObject *mapping,
8623 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008624{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008625 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008626 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008627 Py_ssize_t size, i;
8628 int kind;
8629 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008630 _PyUnicodeWriter writer;
8631 /* error handler */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008632 char *reason = "character maps to <undefined>";
8633 PyObject *errorHandler = NULL;
8634 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008635 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008636 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008637
Guido van Rossumd57fd912000-03-10 22:53:23 +00008638 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008639 PyErr_BadArgument();
8640 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008641 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008642
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008643 if (PyUnicode_READY(input) == -1)
8644 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008645 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008646 kind = PyUnicode_KIND(input);
8647 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008648
8649 if (size == 0) {
8650 Py_INCREF(input);
8651 return input;
8652 }
8653
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008654 /* allocate enough for a simple 1:1 translation without
8655 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008656 _PyUnicodeWriter_Init(&writer);
8657 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008658 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008659
Victor Stinner872b2912014-04-05 14:27:07 +02008660 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
8661
8662 res = unicode_fast_translate(input, mapping, &writer, ignore);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008663 if (res < 0) {
8664 _PyUnicodeWriter_Dealloc(&writer);
8665 return NULL;
8666 }
8667 if (res == 1)
8668 return _PyUnicodeWriter_Finish(&writer);
8669
Victor Stinner89a76ab2014-04-05 11:44:04 +02008670 i = writer.pos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008671 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008672 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008673 int translate;
8674 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8675 Py_ssize_t newpos;
8676 /* startpos for collecting untranslatable chars */
8677 Py_ssize_t collstart;
8678 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02008679 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008680
Victor Stinner1194ea02014-04-04 19:37:40 +02008681 ch = PyUnicode_READ(kind, data, i);
8682 translate = charmaptranslate_output(ch, mapping, &writer);
8683 if (translate < 0)
8684 goto onError;
8685
8686 if (translate != 0) {
8687 /* it worked => adjust input pointer */
8688 ++i;
8689 continue;
8690 }
8691
8692 /* untranslatable character */
8693 collstart = i;
8694 collend = i+1;
8695
8696 /* find all untranslatable characters */
8697 while (collend < size) {
8698 PyObject *x;
8699 ch = PyUnicode_READ(kind, data, collend);
8700 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008701 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02008702 Py_XDECREF(x);
8703 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008704 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02008705 ++collend;
8706 }
8707
8708 if (ignore) {
8709 i = collend;
8710 }
8711 else {
8712 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
8713 reason, input, &exc,
8714 collstart, collend, &newpos);
8715 if (repunicode == NULL)
8716 goto onError;
8717 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008718 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02008719 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008720 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008721 Py_DECREF(repunicode);
8722 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008723 }
8724 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008725 Py_XDECREF(exc);
8726 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02008727 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008728
Benjamin Peterson29060642009-01-31 22:14:21 +00008729 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02008730 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008731 Py_XDECREF(exc);
8732 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008733 return NULL;
8734}
8735
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008736/* Deprecated. Use PyUnicode_Translate instead. */
8737PyObject *
8738PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8739 Py_ssize_t size,
8740 PyObject *mapping,
8741 const char *errors)
8742{
Christian Heimes5f520f42012-09-11 14:03:25 +02008743 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008744 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8745 if (!unicode)
8746 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02008747 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8748 Py_DECREF(unicode);
8749 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008750}
8751
Alexander Belopolsky40018472011-02-26 01:02:56 +00008752PyObject *
8753PyUnicode_Translate(PyObject *str,
8754 PyObject *mapping,
8755 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008756{
8757 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008758
Guido van Rossumd57fd912000-03-10 22:53:23 +00008759 str = PyUnicode_FromObject(str);
8760 if (str == NULL)
Christian Heimes5f520f42012-09-11 14:03:25 +02008761 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008762 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008763 Py_DECREF(str);
8764 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008765}
Tim Petersced69f82003-09-16 20:30:58 +00008766
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008767static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008768fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008769{
8770 /* No need to call PyUnicode_READY(self) because this function is only
8771 called as a callback from fixup() which does it already. */
8772 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8773 const int kind = PyUnicode_KIND(self);
8774 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008775 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008776 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008777 Py_ssize_t i;
8778
8779 for (i = 0; i < len; ++i) {
8780 ch = PyUnicode_READ(kind, data, i);
8781 fixed = 0;
8782 if (ch > 127) {
8783 if (Py_UNICODE_ISSPACE(ch))
8784 fixed = ' ';
8785 else {
8786 const int decimal = Py_UNICODE_TODECIMAL(ch);
8787 if (decimal >= 0)
8788 fixed = '0' + decimal;
8789 }
8790 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008791 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008792 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008793 PyUnicode_WRITE(kind, data, i, fixed);
8794 }
Victor Stinnere6abb482012-05-02 01:15:40 +02008795 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07008796 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008797 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008798 }
8799
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008800 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008801}
8802
8803PyObject *
8804_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8805{
8806 if (!PyUnicode_Check(unicode)) {
8807 PyErr_BadInternalCall();
8808 return NULL;
8809 }
8810 if (PyUnicode_READY(unicode) == -1)
8811 return NULL;
8812 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8813 /* If the string is already ASCII, just return the same string */
8814 Py_INCREF(unicode);
8815 return unicode;
8816 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008817 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008818}
8819
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008820PyObject *
8821PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8822 Py_ssize_t length)
8823{
Victor Stinnerf0124502011-11-21 23:12:56 +01008824 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008825 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008826 Py_UCS4 maxchar;
8827 enum PyUnicode_Kind kind;
8828 void *data;
8829
Victor Stinner99d7ad02012-02-22 13:37:39 +01008830 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008831 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02008832 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008833 if (ch > 127) {
8834 int decimal = Py_UNICODE_TODECIMAL(ch);
8835 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008836 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008837 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008838 }
8839 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008840
8841 /* Copy to a new string */
8842 decimal = PyUnicode_New(length, maxchar);
8843 if (decimal == NULL)
8844 return decimal;
8845 kind = PyUnicode_KIND(decimal);
8846 data = PyUnicode_DATA(decimal);
8847 /* Iterate over code points */
8848 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02008849 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01008850 if (ch > 127) {
8851 int decimal = Py_UNICODE_TODECIMAL(ch);
8852 if (decimal >= 0)
8853 ch = '0' + decimal;
8854 }
8855 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008856 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008857 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008858}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008859/* --- Decimal Encoder ---------------------------------------------------- */
8860
Alexander Belopolsky40018472011-02-26 01:02:56 +00008861int
8862PyUnicode_EncodeDecimal(Py_UNICODE *s,
8863 Py_ssize_t length,
8864 char *output,
8865 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008866{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008867 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008868 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008869 enum PyUnicode_Kind kind;
8870 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008871
8872 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008873 PyErr_BadArgument();
8874 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008875 }
8876
Victor Stinner42bf7752011-11-21 22:52:58 +01008877 unicode = PyUnicode_FromUnicode(s, length);
8878 if (unicode == NULL)
8879 return -1;
8880
Benjamin Petersonbac79492012-01-14 13:34:47 -05008881 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01008882 Py_DECREF(unicode);
8883 return -1;
8884 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008885 kind = PyUnicode_KIND(unicode);
8886 data = PyUnicode_DATA(unicode);
8887
Victor Stinnerb84d7232011-11-22 01:50:07 +01008888 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008889 PyObject *exc;
8890 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008891 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008892 Py_ssize_t startpos;
8893
8894 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008895
Benjamin Peterson29060642009-01-31 22:14:21 +00008896 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008897 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008898 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008899 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008900 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008901 decimal = Py_UNICODE_TODECIMAL(ch);
8902 if (decimal >= 0) {
8903 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008904 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008905 continue;
8906 }
8907 if (0 < ch && ch < 256) {
8908 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008909 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008910 continue;
8911 }
Victor Stinner6345be92011-11-25 20:09:01 +01008912
Victor Stinner42bf7752011-11-21 22:52:58 +01008913 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008914 exc = NULL;
8915 raise_encode_exception(&exc, "decimal", unicode,
8916 startpos, startpos+1,
8917 "invalid decimal Unicode string");
8918 Py_XDECREF(exc);
8919 Py_DECREF(unicode);
8920 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008921 }
8922 /* 0-terminate the output string */
8923 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008924 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008925 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008926}
8927
Guido van Rossumd57fd912000-03-10 22:53:23 +00008928/* --- Helpers ------------------------------------------------------------ */
8929
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02008930/* helper macro to fixup start/end slice values */
8931#define ADJUST_INDICES(start, end, len) \
8932 if (end > len) \
8933 end = len; \
8934 else if (end < 0) { \
8935 end += len; \
8936 if (end < 0) \
8937 end = 0; \
8938 } \
8939 if (start < 0) { \
8940 start += len; \
8941 if (start < 0) \
8942 start = 0; \
8943 }
8944
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008945static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008946any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008947 Py_ssize_t start,
8948 Py_ssize_t end)
8949{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02008950 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008951 void *buf1, *buf2;
8952 Py_ssize_t len1, len2, result;
8953
8954 kind1 = PyUnicode_KIND(s1);
8955 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02008956 if (kind1 < kind2)
8957 return -1;
8958
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008959 len1 = PyUnicode_GET_LENGTH(s1);
8960 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02008961 ADJUST_INDICES(start, end, len1);
8962 if (end - start < len2)
8963 return -1;
8964
8965 buf1 = PyUnicode_DATA(s1);
8966 buf2 = PyUnicode_DATA(s2);
8967 if (len2 == 1) {
8968 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
8969 result = findchar((const char *)buf1 + kind1*start,
8970 kind1, end - start, ch, direction);
8971 if (result == -1)
8972 return -1;
8973 else
8974 return start + result;
8975 }
8976
8977 if (kind2 != kind1) {
8978 buf2 = _PyUnicode_AsKind(s2, kind1);
8979 if (!buf2)
8980 return -2;
8981 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008982
Victor Stinner794d5672011-10-10 03:21:36 +02008983 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02008984 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02008985 case PyUnicode_1BYTE_KIND:
8986 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8987 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
8988 else
8989 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
8990 break;
8991 case PyUnicode_2BYTE_KIND:
8992 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
8993 break;
8994 case PyUnicode_4BYTE_KIND:
8995 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
8996 break;
8997 default:
8998 assert(0); result = -2;
8999 }
9000 }
9001 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009002 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009003 case PyUnicode_1BYTE_KIND:
9004 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9005 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9006 else
9007 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9008 break;
9009 case PyUnicode_2BYTE_KIND:
9010 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9011 break;
9012 case PyUnicode_4BYTE_KIND:
9013 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9014 break;
9015 default:
9016 assert(0); result = -2;
9017 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009018 }
9019
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009020 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009021 PyMem_Free(buf2);
9022
9023 return result;
9024}
9025
9026Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009027_PyUnicode_InsertThousandsGrouping(
9028 PyObject *unicode, Py_ssize_t index,
9029 Py_ssize_t n_buffer,
9030 void *digits, Py_ssize_t n_digits,
9031 Py_ssize_t min_width,
9032 const char *grouping, PyObject *thousands_sep,
9033 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009034{
Victor Stinner41a863c2012-02-24 00:37:51 +01009035 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009036 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009037 Py_ssize_t thousands_sep_len;
9038 Py_ssize_t len;
9039
9040 if (unicode != NULL) {
9041 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009042 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009043 }
9044 else {
9045 kind = PyUnicode_1BYTE_KIND;
9046 data = NULL;
9047 }
9048 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9049 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9050 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9051 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009052 if (thousands_sep_kind < kind) {
9053 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9054 if (!thousands_sep_data)
9055 return -1;
9056 }
9057 else {
9058 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9059 if (!data)
9060 return -1;
9061 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009062 }
9063
Benjamin Petersonead6b532011-12-20 17:23:42 -06009064 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009065 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009066 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009067 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009068 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009069 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009070 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009071 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009072 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009073 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009074 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009075 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009076 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009077 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009078 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009079 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009080 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009081 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009082 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009083 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009084 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009085 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009086 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009087 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009088 break;
9089 default:
9090 assert(0);
9091 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009092 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009093 if (unicode != NULL && thousands_sep_kind != kind) {
9094 if (thousands_sep_kind < kind)
9095 PyMem_Free(thousands_sep_data);
9096 else
9097 PyMem_Free(data);
9098 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009099 if (unicode == NULL) {
9100 *maxchar = 127;
9101 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009102 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009103 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009104 }
9105 }
9106 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009107}
9108
9109
Alexander Belopolsky40018472011-02-26 01:02:56 +00009110Py_ssize_t
9111PyUnicode_Count(PyObject *str,
9112 PyObject *substr,
9113 Py_ssize_t start,
9114 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009115{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009116 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009117 PyObject* str_obj;
9118 PyObject* sub_obj;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009119 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009120 void *buf1 = NULL, *buf2 = NULL;
9121 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009122
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009123 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009124 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00009125 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009126 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009127 if (!sub_obj) {
9128 Py_DECREF(str_obj);
9129 return -1;
9130 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06009131 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06009132 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00009133 Py_DECREF(str_obj);
9134 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009135 }
Tim Petersced69f82003-09-16 20:30:58 +00009136
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009137 kind1 = PyUnicode_KIND(str_obj);
9138 kind2 = PyUnicode_KIND(sub_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009139 if (kind1 < kind2) {
9140 Py_DECREF(sub_obj);
9141 Py_DECREF(str_obj);
9142 return 0;
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05009143 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009144
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009145 len1 = PyUnicode_GET_LENGTH(str_obj);
9146 len2 = PyUnicode_GET_LENGTH(sub_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009147 ADJUST_INDICES(start, end, len1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009148 if (end - start < len2) {
9149 Py_DECREF(sub_obj);
9150 Py_DECREF(str_obj);
9151 return 0;
9152 }
9153
9154 buf1 = PyUnicode_DATA(str_obj);
9155 buf2 = PyUnicode_DATA(sub_obj);
9156 if (kind2 != kind1) {
9157 buf2 = _PyUnicode_AsKind(sub_obj, kind1);
9158 if (!buf2)
9159 goto onError;
9160 }
9161
9162 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009163 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009164 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9165 result = asciilib_count(
9166 ((Py_UCS1*)buf1) + start, end - start,
9167 buf2, len2, PY_SSIZE_T_MAX
9168 );
9169 else
9170 result = ucs1lib_count(
9171 ((Py_UCS1*)buf1) + start, end - start,
9172 buf2, len2, PY_SSIZE_T_MAX
9173 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009174 break;
9175 case PyUnicode_2BYTE_KIND:
9176 result = ucs2lib_count(
9177 ((Py_UCS2*)buf1) + start, end - start,
9178 buf2, len2, PY_SSIZE_T_MAX
9179 );
9180 break;
9181 case PyUnicode_4BYTE_KIND:
9182 result = ucs4lib_count(
9183 ((Py_UCS4*)buf1) + start, end - start,
9184 buf2, len2, PY_SSIZE_T_MAX
9185 );
9186 break;
9187 default:
9188 assert(0); result = 0;
9189 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009190
9191 Py_DECREF(sub_obj);
9192 Py_DECREF(str_obj);
9193
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009194 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009195 PyMem_Free(buf2);
9196
Guido van Rossumd57fd912000-03-10 22:53:23 +00009197 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009198 onError:
9199 Py_DECREF(sub_obj);
9200 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009201 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009202 PyMem_Free(buf2);
9203 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009204}
9205
Alexander Belopolsky40018472011-02-26 01:02:56 +00009206Py_ssize_t
9207PyUnicode_Find(PyObject *str,
9208 PyObject *sub,
9209 Py_ssize_t start,
9210 Py_ssize_t end,
9211 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009212{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009213 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009214
Guido van Rossumd57fd912000-03-10 22:53:23 +00009215 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009216 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009217 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009218 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009219 if (!sub) {
9220 Py_DECREF(str);
9221 return -2;
9222 }
9223 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9224 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009225 Py_DECREF(str);
9226 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009227 }
Tim Petersced69f82003-09-16 20:30:58 +00009228
Victor Stinner794d5672011-10-10 03:21:36 +02009229 result = any_find_slice(direction,
9230 str, sub, start, end
9231 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009232
Guido van Rossumd57fd912000-03-10 22:53:23 +00009233 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009234 Py_DECREF(sub);
9235
Guido van Rossumd57fd912000-03-10 22:53:23 +00009236 return result;
9237}
9238
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009239Py_ssize_t
9240PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9241 Py_ssize_t start, Py_ssize_t end,
9242 int direction)
9243{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009244 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009245 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009246 if (PyUnicode_READY(str) == -1)
9247 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009248 if (start < 0 || end < 0) {
9249 PyErr_SetString(PyExc_IndexError, "string index out of range");
9250 return -2;
9251 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009252 if (end > PyUnicode_GET_LENGTH(str))
9253 end = PyUnicode_GET_LENGTH(str);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009254 if (start >= end)
9255 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009256 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009257 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9258 kind, end-start, ch, direction);
9259 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009260 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009261 else
9262 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009263}
9264
Alexander Belopolsky40018472011-02-26 01:02:56 +00009265static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009266tailmatch(PyObject *self,
9267 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009268 Py_ssize_t start,
9269 Py_ssize_t end,
9270 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009271{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009272 int kind_self;
9273 int kind_sub;
9274 void *data_self;
9275 void *data_sub;
9276 Py_ssize_t offset;
9277 Py_ssize_t i;
9278 Py_ssize_t end_sub;
9279
9280 if (PyUnicode_READY(self) == -1 ||
9281 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009282 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009283
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009284 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9285 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009286 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009287 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009288
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009289 if (PyUnicode_GET_LENGTH(substring) == 0)
9290 return 1;
9291
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009292 kind_self = PyUnicode_KIND(self);
9293 data_self = PyUnicode_DATA(self);
9294 kind_sub = PyUnicode_KIND(substring);
9295 data_sub = PyUnicode_DATA(substring);
9296 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9297
9298 if (direction > 0)
9299 offset = end;
9300 else
9301 offset = start;
9302
9303 if (PyUnicode_READ(kind_self, data_self, offset) ==
9304 PyUnicode_READ(kind_sub, data_sub, 0) &&
9305 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9306 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9307 /* If both are of the same kind, memcmp is sufficient */
9308 if (kind_self == kind_sub) {
9309 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009310 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009311 data_sub,
9312 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009313 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009314 }
9315 /* otherwise we have to compare each character by first accesing it */
9316 else {
9317 /* We do not need to compare 0 and len(substring)-1 because
9318 the if statement above ensured already that they are equal
9319 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009320 for (i = 1; i < end_sub; ++i) {
9321 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9322 PyUnicode_READ(kind_sub, data_sub, i))
9323 return 0;
9324 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009325 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009326 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009327 }
9328
9329 return 0;
9330}
9331
Alexander Belopolsky40018472011-02-26 01:02:56 +00009332Py_ssize_t
9333PyUnicode_Tailmatch(PyObject *str,
9334 PyObject *substr,
9335 Py_ssize_t start,
9336 Py_ssize_t end,
9337 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009338{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009339 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009340
Guido van Rossumd57fd912000-03-10 22:53:23 +00009341 str = PyUnicode_FromObject(str);
9342 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009343 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009344 substr = PyUnicode_FromObject(substr);
9345 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009346 Py_DECREF(str);
9347 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009348 }
Tim Petersced69f82003-09-16 20:30:58 +00009349
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009350 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009351 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009352 Py_DECREF(str);
9353 Py_DECREF(substr);
9354 return result;
9355}
9356
Guido van Rossumd57fd912000-03-10 22:53:23 +00009357/* Apply fixfct filter to the Unicode object self and return a
9358 reference to the modified object */
9359
Alexander Belopolsky40018472011-02-26 01:02:56 +00009360static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009361fixup(PyObject *self,
9362 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009363{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009364 PyObject *u;
9365 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009366 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009367
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009368 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009369 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009370 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009371 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009372
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009373 /* fix functions return the new maximum character in a string,
9374 if the kind of the resulting unicode object does not change,
9375 everything is fine. Otherwise we need to change the string kind
9376 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009377 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009378
9379 if (maxchar_new == 0) {
9380 /* no changes */;
9381 if (PyUnicode_CheckExact(self)) {
9382 Py_DECREF(u);
9383 Py_INCREF(self);
9384 return self;
9385 }
9386 else
9387 return u;
9388 }
9389
Victor Stinnere6abb482012-05-02 01:15:40 +02009390 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009391
Victor Stinnereaab6042011-12-11 22:22:39 +01009392 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009393 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009394
9395 /* In case the maximum character changed, we need to
9396 convert the string to the new category. */
9397 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9398 if (v == NULL) {
9399 Py_DECREF(u);
9400 return NULL;
9401 }
9402 if (maxchar_new > maxchar_old) {
9403 /* If the maxchar increased so that the kind changed, not all
9404 characters are representable anymore and we need to fix the
9405 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009406 _PyUnicode_FastCopyCharacters(v, 0,
9407 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009408 maxchar_old = fixfct(v);
9409 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009410 }
9411 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009412 _PyUnicode_FastCopyCharacters(v, 0,
9413 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009414 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009415 Py_DECREF(u);
9416 assert(_PyUnicode_CheckConsistency(v, 1));
9417 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009418}
9419
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009420static PyObject *
9421ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009422{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009423 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9424 char *resdata, *data = PyUnicode_DATA(self);
9425 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009426
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009427 res = PyUnicode_New(len, 127);
9428 if (res == NULL)
9429 return NULL;
9430 resdata = PyUnicode_DATA(res);
9431 if (lower)
9432 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009433 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009434 _Py_bytes_upper(resdata, data, len);
9435 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009436}
9437
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009438static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009439handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009440{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009441 Py_ssize_t j;
9442 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009443 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009444 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009445
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009446 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9447
9448 where ! is a negation and \p{xxx} is a character with property xxx.
9449 */
9450 for (j = i - 1; j >= 0; j--) {
9451 c = PyUnicode_READ(kind, data, j);
9452 if (!_PyUnicode_IsCaseIgnorable(c))
9453 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009454 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009455 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9456 if (final_sigma) {
9457 for (j = i + 1; j < length; j++) {
9458 c = PyUnicode_READ(kind, data, j);
9459 if (!_PyUnicode_IsCaseIgnorable(c))
9460 break;
9461 }
9462 final_sigma = j == length || !_PyUnicode_IsCased(c);
9463 }
9464 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009465}
9466
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009467static int
9468lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9469 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009470{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009471 /* Obscure special case. */
9472 if (c == 0x3A3) {
9473 mapped[0] = handle_capital_sigma(kind, data, length, i);
9474 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009475 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009476 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009477}
9478
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009479static Py_ssize_t
9480do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009481{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009482 Py_ssize_t i, k = 0;
9483 int n_res, j;
9484 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009485
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009486 c = PyUnicode_READ(kind, data, 0);
9487 n_res = _PyUnicode_ToUpperFull(c, mapped);
9488 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009489 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009490 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009491 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009492 for (i = 1; i < length; i++) {
9493 c = PyUnicode_READ(kind, data, i);
9494 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9495 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009496 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009497 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009498 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009499 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009500 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009501}
9502
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009503static Py_ssize_t
9504do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9505 Py_ssize_t i, k = 0;
9506
9507 for (i = 0; i < length; i++) {
9508 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9509 int n_res, j;
9510 if (Py_UNICODE_ISUPPER(c)) {
9511 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9512 }
9513 else if (Py_UNICODE_ISLOWER(c)) {
9514 n_res = _PyUnicode_ToUpperFull(c, mapped);
9515 }
9516 else {
9517 n_res = 1;
9518 mapped[0] = c;
9519 }
9520 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009521 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009522 res[k++] = mapped[j];
9523 }
9524 }
9525 return k;
9526}
9527
9528static Py_ssize_t
9529do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9530 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009531{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009532 Py_ssize_t i, k = 0;
9533
9534 for (i = 0; i < length; i++) {
9535 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9536 int n_res, j;
9537 if (lower)
9538 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9539 else
9540 n_res = _PyUnicode_ToUpperFull(c, mapped);
9541 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009542 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009543 res[k++] = mapped[j];
9544 }
9545 }
9546 return k;
9547}
9548
9549static Py_ssize_t
9550do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9551{
9552 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9553}
9554
9555static Py_ssize_t
9556do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9557{
9558 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9559}
9560
Benjamin Petersone51757f2012-01-12 21:10:29 -05009561static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009562do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9563{
9564 Py_ssize_t i, k = 0;
9565
9566 for (i = 0; i < length; i++) {
9567 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9568 Py_UCS4 mapped[3];
9569 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9570 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009571 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009572 res[k++] = mapped[j];
9573 }
9574 }
9575 return k;
9576}
9577
9578static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009579do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9580{
9581 Py_ssize_t i, k = 0;
9582 int previous_is_cased;
9583
9584 previous_is_cased = 0;
9585 for (i = 0; i < length; i++) {
9586 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9587 Py_UCS4 mapped[3];
9588 int n_res, j;
9589
9590 if (previous_is_cased)
9591 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9592 else
9593 n_res = _PyUnicode_ToTitleFull(c, mapped);
9594
9595 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009596 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009597 res[k++] = mapped[j];
9598 }
9599
9600 previous_is_cased = _PyUnicode_IsCased(c);
9601 }
9602 return k;
9603}
9604
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009605static PyObject *
9606case_operation(PyObject *self,
9607 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9608{
9609 PyObject *res = NULL;
9610 Py_ssize_t length, newlength = 0;
9611 int kind, outkind;
9612 void *data, *outdata;
9613 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9614
Benjamin Petersoneea48462012-01-16 14:28:50 -05009615 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009616
9617 kind = PyUnicode_KIND(self);
9618 data = PyUnicode_DATA(self);
9619 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009620 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009621 PyErr_SetString(PyExc_OverflowError, "string is too long");
9622 return NULL;
9623 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009624 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009625 if (tmp == NULL)
9626 return PyErr_NoMemory();
9627 newlength = perform(kind, data, length, tmp, &maxchar);
9628 res = PyUnicode_New(newlength, maxchar);
9629 if (res == NULL)
9630 goto leave;
9631 tmpend = tmp + newlength;
9632 outdata = PyUnicode_DATA(res);
9633 outkind = PyUnicode_KIND(res);
9634 switch (outkind) {
9635 case PyUnicode_1BYTE_KIND:
9636 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9637 break;
9638 case PyUnicode_2BYTE_KIND:
9639 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9640 break;
9641 case PyUnicode_4BYTE_KIND:
9642 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9643 break;
9644 default:
9645 assert(0);
9646 break;
9647 }
9648 leave:
9649 PyMem_FREE(tmp);
9650 return res;
9651}
9652
Tim Peters8ce9f162004-08-27 01:49:32 +00009653PyObject *
9654PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009655{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009656 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009657 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009658 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009659 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009660 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9661 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009662 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009663 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009664 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009665 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009666 int use_memcpy;
9667 unsigned char *res_data = NULL, *sep_data = NULL;
9668 PyObject *last_obj;
9669 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009670
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009671 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009672 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009673 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009674 }
9675
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009676 /* NOTE: the following code can't call back into Python code,
9677 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009678 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009679
Tim Peters05eba1f2004-08-27 21:32:02 +00009680 seqlen = PySequence_Fast_GET_SIZE(fseq);
9681 /* If empty sequence, return u"". */
9682 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009683 Py_DECREF(fseq);
Serhiy Storchaka678db842013-01-26 12:16:36 +02009684 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009685 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009686
Tim Peters05eba1f2004-08-27 21:32:02 +00009687 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009688 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009689 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009690 if (seqlen == 1) {
9691 if (PyUnicode_CheckExact(items[0])) {
9692 res = items[0];
9693 Py_INCREF(res);
9694 Py_DECREF(fseq);
9695 return res;
9696 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009697 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009698 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009699 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009700 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009701 /* Set up sep and seplen */
9702 if (separator == NULL) {
9703 /* fall back to a blank space separator */
9704 sep = PyUnicode_FromOrdinal(' ');
9705 if (!sep)
9706 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009707 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009708 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009709 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009710 else {
9711 if (!PyUnicode_Check(separator)) {
9712 PyErr_Format(PyExc_TypeError,
9713 "separator: expected str instance,"
9714 " %.80s found",
9715 Py_TYPE(separator)->tp_name);
9716 goto onError;
9717 }
9718 if (PyUnicode_READY(separator))
9719 goto onError;
9720 sep = separator;
9721 seplen = PyUnicode_GET_LENGTH(separator);
9722 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9723 /* inc refcount to keep this code path symmetric with the
9724 above case of a blank separator */
9725 Py_INCREF(sep);
9726 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009727 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009728 }
9729
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009730 /* There are at least two things to join, or else we have a subclass
9731 * of str in the sequence.
9732 * Do a pre-pass to figure out the total amount of space we'll
9733 * need (sz), and see whether all argument are strings.
9734 */
9735 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009736#ifdef Py_DEBUG
9737 use_memcpy = 0;
9738#else
9739 use_memcpy = 1;
9740#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009741 for (i = 0; i < seqlen; i++) {
9742 const Py_ssize_t old_sz = sz;
9743 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009744 if (!PyUnicode_Check(item)) {
9745 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +02009746 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +00009747 " %.80s found",
9748 i, Py_TYPE(item)->tp_name);
9749 goto onError;
9750 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009751 if (PyUnicode_READY(item) == -1)
9752 goto onError;
9753 sz += PyUnicode_GET_LENGTH(item);
9754 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009755 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009756 if (i != 0)
9757 sz += seplen;
9758 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9759 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009760 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009761 goto onError;
9762 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009763 if (use_memcpy && last_obj != NULL) {
9764 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9765 use_memcpy = 0;
9766 }
9767 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009768 }
Tim Petersced69f82003-09-16 20:30:58 +00009769
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009770 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009771 if (res == NULL)
9772 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009773
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009774 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009775#ifdef Py_DEBUG
9776 use_memcpy = 0;
9777#else
9778 if (use_memcpy) {
9779 res_data = PyUnicode_1BYTE_DATA(res);
9780 kind = PyUnicode_KIND(res);
9781 if (seplen != 0)
9782 sep_data = PyUnicode_1BYTE_DATA(sep);
9783 }
9784#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009785 if (use_memcpy) {
9786 for (i = 0; i < seqlen; ++i) {
9787 Py_ssize_t itemlen;
9788 item = items[i];
9789
9790 /* Copy item, and maybe the separator. */
9791 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009792 Py_MEMCPY(res_data,
9793 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009794 kind * seplen);
9795 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009796 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009797
9798 itemlen = PyUnicode_GET_LENGTH(item);
9799 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009800 Py_MEMCPY(res_data,
9801 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009802 kind * itemlen);
9803 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009804 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009805 }
9806 assert(res_data == PyUnicode_1BYTE_DATA(res)
9807 + kind * PyUnicode_GET_LENGTH(res));
9808 }
9809 else {
9810 for (i = 0, res_offset = 0; i < seqlen; ++i) {
9811 Py_ssize_t itemlen;
9812 item = items[i];
9813
9814 /* Copy item, and maybe the separator. */
9815 if (i && seplen != 0) {
9816 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
9817 res_offset += seplen;
9818 }
9819
9820 itemlen = PyUnicode_GET_LENGTH(item);
9821 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009822 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009823 res_offset += itemlen;
9824 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009825 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009826 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +02009827 }
Tim Peters8ce9f162004-08-27 01:49:32 +00009828
Tim Peters05eba1f2004-08-27 21:32:02 +00009829 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009830 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009831 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009832 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009833
Benjamin Peterson29060642009-01-31 22:14:21 +00009834 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009835 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009836 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009837 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009838 return NULL;
9839}
9840
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009841#define FILL(kind, data, value, start, length) \
9842 do { \
9843 Py_ssize_t i_ = 0; \
9844 assert(kind != PyUnicode_WCHAR_KIND); \
9845 switch ((kind)) { \
9846 case PyUnicode_1BYTE_KIND: { \
9847 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009848 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009849 break; \
9850 } \
9851 case PyUnicode_2BYTE_KIND: { \
9852 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9853 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9854 break; \
9855 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009856 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009857 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9858 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9859 break; \
9860 } \
Serhiy Storchaka133b11b2014-12-01 18:56:28 +02009861 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009862 } \
9863 } while (0)
9864
Victor Stinnerd3f08822012-05-29 12:57:52 +02009865void
9866_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9867 Py_UCS4 fill_char)
9868{
9869 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
9870 const void *data = PyUnicode_DATA(unicode);
9871 assert(PyUnicode_IS_READY(unicode));
9872 assert(unicode_modifiable(unicode));
9873 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
9874 assert(start >= 0);
9875 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
9876 FILL(kind, data, fill_char, start, length);
9877}
9878
Victor Stinner3fe55312012-01-04 00:33:50 +01009879Py_ssize_t
9880PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9881 Py_UCS4 fill_char)
9882{
9883 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +01009884
9885 if (!PyUnicode_Check(unicode)) {
9886 PyErr_BadInternalCall();
9887 return -1;
9888 }
9889 if (PyUnicode_READY(unicode) == -1)
9890 return -1;
9891 if (unicode_check_modifiable(unicode))
9892 return -1;
9893
Victor Stinnerd3f08822012-05-29 12:57:52 +02009894 if (start < 0) {
9895 PyErr_SetString(PyExc_IndexError, "string index out of range");
9896 return -1;
9897 }
Victor Stinner3fe55312012-01-04 00:33:50 +01009898 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9899 PyErr_SetString(PyExc_ValueError,
9900 "fill character is bigger than "
9901 "the string maximum character");
9902 return -1;
9903 }
9904
9905 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9906 length = Py_MIN(maxlen, length);
9907 if (length <= 0)
9908 return 0;
9909
Victor Stinnerd3f08822012-05-29 12:57:52 +02009910 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +01009911 return length;
9912}
9913
Victor Stinner9310abb2011-10-05 00:59:23 +02009914static PyObject *
9915pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009916 Py_ssize_t left,
9917 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009918 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009919{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009920 PyObject *u;
9921 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009922 int kind;
9923 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009924
9925 if (left < 0)
9926 left = 0;
9927 if (right < 0)
9928 right = 0;
9929
Victor Stinnerc4b49542011-12-11 22:44:26 +01009930 if (left == 0 && right == 0)
9931 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009932
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009933 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9934 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009935 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9936 return NULL;
9937 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009938 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009939 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009940 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009941 if (!u)
9942 return NULL;
9943
9944 kind = PyUnicode_KIND(u);
9945 data = PyUnicode_DATA(u);
9946 if (left)
9947 FILL(kind, data, fill, 0, left);
9948 if (right)
9949 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +02009950 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009951 assert(_PyUnicode_CheckConsistency(u, 1));
9952 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009953}
9954
Alexander Belopolsky40018472011-02-26 01:02:56 +00009955PyObject *
9956PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009957{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009958 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009959
9960 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009961 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009962 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -06009963 if (PyUnicode_READY(string) == -1) {
9964 Py_DECREF(string);
9965 return NULL;
9966 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009967
Benjamin Petersonead6b532011-12-20 17:23:42 -06009968 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009969 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009970 if (PyUnicode_IS_ASCII(string))
9971 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009972 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009973 PyUnicode_GET_LENGTH(string), keepends);
9974 else
9975 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009976 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009977 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009978 break;
9979 case PyUnicode_2BYTE_KIND:
9980 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009981 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009982 PyUnicode_GET_LENGTH(string), keepends);
9983 break;
9984 case PyUnicode_4BYTE_KIND:
9985 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009986 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009987 PyUnicode_GET_LENGTH(string), keepends);
9988 break;
9989 default:
9990 assert(0);
9991 list = 0;
9992 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009993 Py_DECREF(string);
9994 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009995}
9996
Alexander Belopolsky40018472011-02-26 01:02:56 +00009997static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009998split(PyObject *self,
9999 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010000 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010001{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010002 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010003 void *buf1, *buf2;
10004 Py_ssize_t len1, len2;
10005 PyObject* out;
10006
Guido van Rossumd57fd912000-03-10 22:53:23 +000010007 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010008 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010009
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010010 if (PyUnicode_READY(self) == -1)
10011 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010012
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010013 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010014 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010015 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010016 if (PyUnicode_IS_ASCII(self))
10017 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010018 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010019 PyUnicode_GET_LENGTH(self), maxcount
10020 );
10021 else
10022 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010023 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010024 PyUnicode_GET_LENGTH(self), maxcount
10025 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010026 case PyUnicode_2BYTE_KIND:
10027 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010028 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010029 PyUnicode_GET_LENGTH(self), maxcount
10030 );
10031 case PyUnicode_4BYTE_KIND:
10032 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010033 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010034 PyUnicode_GET_LENGTH(self), maxcount
10035 );
10036 default:
10037 assert(0);
10038 return NULL;
10039 }
10040
10041 if (PyUnicode_READY(substring) == -1)
10042 return NULL;
10043
10044 kind1 = PyUnicode_KIND(self);
10045 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010046 len1 = PyUnicode_GET_LENGTH(self);
10047 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010048 if (kind1 < kind2 || len1 < len2) {
10049 out = PyList_New(1);
10050 if (out == NULL)
10051 return NULL;
10052 Py_INCREF(self);
10053 PyList_SET_ITEM(out, 0, self);
10054 return out;
10055 }
10056 buf1 = PyUnicode_DATA(self);
10057 buf2 = PyUnicode_DATA(substring);
10058 if (kind2 != kind1) {
10059 buf2 = _PyUnicode_AsKind(substring, kind1);
10060 if (!buf2)
10061 return NULL;
10062 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010063
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010064 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010065 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010066 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10067 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010068 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010069 else
10070 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010071 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010072 break;
10073 case PyUnicode_2BYTE_KIND:
10074 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010075 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010076 break;
10077 case PyUnicode_4BYTE_KIND:
10078 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010079 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010080 break;
10081 default:
10082 out = NULL;
10083 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010084 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010085 PyMem_Free(buf2);
10086 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010087}
10088
Alexander Belopolsky40018472011-02-26 01:02:56 +000010089static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010090rsplit(PyObject *self,
10091 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010092 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010093{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010094 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010095 void *buf1, *buf2;
10096 Py_ssize_t len1, len2;
10097 PyObject* out;
10098
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010099 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010100 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010101
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010102 if (PyUnicode_READY(self) == -1)
10103 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010104
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010105 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010106 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010107 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010108 if (PyUnicode_IS_ASCII(self))
10109 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010110 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010111 PyUnicode_GET_LENGTH(self), maxcount
10112 );
10113 else
10114 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010115 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010116 PyUnicode_GET_LENGTH(self), maxcount
10117 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010118 case PyUnicode_2BYTE_KIND:
10119 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010120 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010121 PyUnicode_GET_LENGTH(self), maxcount
10122 );
10123 case PyUnicode_4BYTE_KIND:
10124 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010125 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010126 PyUnicode_GET_LENGTH(self), maxcount
10127 );
10128 default:
10129 assert(0);
10130 return NULL;
10131 }
10132
10133 if (PyUnicode_READY(substring) == -1)
10134 return NULL;
10135
10136 kind1 = PyUnicode_KIND(self);
10137 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010138 len1 = PyUnicode_GET_LENGTH(self);
10139 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010140 if (kind1 < kind2 || len1 < len2) {
10141 out = PyList_New(1);
10142 if (out == NULL)
10143 return NULL;
10144 Py_INCREF(self);
10145 PyList_SET_ITEM(out, 0, self);
10146 return out;
10147 }
10148 buf1 = PyUnicode_DATA(self);
10149 buf2 = PyUnicode_DATA(substring);
10150 if (kind2 != kind1) {
10151 buf2 = _PyUnicode_AsKind(substring, kind1);
10152 if (!buf2)
10153 return NULL;
10154 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010155
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010156 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010157 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010158 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10159 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010160 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010161 else
10162 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010163 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010164 break;
10165 case PyUnicode_2BYTE_KIND:
10166 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010167 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010168 break;
10169 case PyUnicode_4BYTE_KIND:
10170 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010171 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010172 break;
10173 default:
10174 out = NULL;
10175 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010176 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010177 PyMem_Free(buf2);
10178 return out;
10179}
10180
10181static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010182anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10183 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010184{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010185 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010186 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010187 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10188 return asciilib_find(buf1, len1, buf2, len2, offset);
10189 else
10190 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010191 case PyUnicode_2BYTE_KIND:
10192 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10193 case PyUnicode_4BYTE_KIND:
10194 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10195 }
10196 assert(0);
10197 return -1;
10198}
10199
10200static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010201anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10202 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010203{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010204 switch (kind) {
10205 case PyUnicode_1BYTE_KIND:
10206 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10207 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10208 else
10209 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10210 case PyUnicode_2BYTE_KIND:
10211 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10212 case PyUnicode_4BYTE_KIND:
10213 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10214 }
10215 assert(0);
10216 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010217}
10218
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010219static void
10220replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10221 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10222{
10223 int kind = PyUnicode_KIND(u);
10224 void *data = PyUnicode_DATA(u);
10225 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10226 if (kind == PyUnicode_1BYTE_KIND) {
10227 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10228 (Py_UCS1 *)data + len,
10229 u1, u2, maxcount);
10230 }
10231 else if (kind == PyUnicode_2BYTE_KIND) {
10232 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10233 (Py_UCS2 *)data + len,
10234 u1, u2, maxcount);
10235 }
10236 else {
10237 assert(kind == PyUnicode_4BYTE_KIND);
10238 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10239 (Py_UCS4 *)data + len,
10240 u1, u2, maxcount);
10241 }
10242}
10243
Alexander Belopolsky40018472011-02-26 01:02:56 +000010244static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010245replace(PyObject *self, PyObject *str1,
10246 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010247{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010248 PyObject *u;
10249 char *sbuf = PyUnicode_DATA(self);
10250 char *buf1 = PyUnicode_DATA(str1);
10251 char *buf2 = PyUnicode_DATA(str2);
10252 int srelease = 0, release1 = 0, release2 = 0;
10253 int skind = PyUnicode_KIND(self);
10254 int kind1 = PyUnicode_KIND(str1);
10255 int kind2 = PyUnicode_KIND(str2);
10256 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10257 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10258 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010259 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010260 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010261
10262 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010263 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010264 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010265 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010266
Victor Stinner59de0ee2011-10-07 10:01:28 +020010267 if (str1 == str2)
10268 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010269
Victor Stinner49a0a212011-10-12 23:46:10 +020010270 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010271 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10272 if (maxchar < maxchar_str1)
10273 /* substring too wide to be present */
10274 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010275 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10276 /* Replacing str1 with str2 may cause a maxchar reduction in the
10277 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010278 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010279 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010280
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010281 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010282 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010283 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010284 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010285 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010286 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010287 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010288 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010289
Victor Stinner69ed0f42013-04-09 21:48:24 +020010290 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010291 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010292 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010293 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010294 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010295 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010296 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010297 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010298
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010299 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10300 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010301 }
10302 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010303 int rkind = skind;
10304 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010305 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010306
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010307 if (kind1 < rkind) {
10308 /* widen substring */
10309 buf1 = _PyUnicode_AsKind(str1, rkind);
10310 if (!buf1) goto error;
10311 release1 = 1;
10312 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010313 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010314 if (i < 0)
10315 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010316 if (rkind > kind2) {
10317 /* widen replacement */
10318 buf2 = _PyUnicode_AsKind(str2, rkind);
10319 if (!buf2) goto error;
10320 release2 = 1;
10321 }
10322 else if (rkind < kind2) {
10323 /* widen self and buf1 */
10324 rkind = kind2;
10325 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010326 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010327 sbuf = _PyUnicode_AsKind(self, rkind);
10328 if (!sbuf) goto error;
10329 srelease = 1;
10330 buf1 = _PyUnicode_AsKind(str1, rkind);
10331 if (!buf1) goto error;
10332 release1 = 1;
10333 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010334 u = PyUnicode_New(slen, maxchar);
10335 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010336 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010337 assert(PyUnicode_KIND(u) == rkind);
10338 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010339
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010340 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010341 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010342 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010343 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010344 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010345 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010346
10347 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010348 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010349 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010350 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010351 if (i == -1)
10352 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010353 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010354 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010355 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010356 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010357 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010358 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010359 }
10360 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010361 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010362 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010363 int rkind = skind;
10364 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010365
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010366 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010367 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010368 buf1 = _PyUnicode_AsKind(str1, rkind);
10369 if (!buf1) goto error;
10370 release1 = 1;
10371 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010372 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010373 if (n == 0)
10374 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010375 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010376 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010377 buf2 = _PyUnicode_AsKind(str2, rkind);
10378 if (!buf2) goto error;
10379 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010380 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010381 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010382 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010383 rkind = kind2;
10384 sbuf = _PyUnicode_AsKind(self, rkind);
10385 if (!sbuf) goto error;
10386 srelease = 1;
10387 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010388 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010389 buf1 = _PyUnicode_AsKind(str1, rkind);
10390 if (!buf1) goto error;
10391 release1 = 1;
10392 }
10393 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10394 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010395 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010396 PyErr_SetString(PyExc_OverflowError,
10397 "replace string is too long");
10398 goto error;
10399 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010400 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010401 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010402 _Py_INCREF_UNICODE_EMPTY();
10403 if (!unicode_empty)
10404 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010405 u = unicode_empty;
10406 goto done;
10407 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010408 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010409 PyErr_SetString(PyExc_OverflowError,
10410 "replace string is too long");
10411 goto error;
10412 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010413 u = PyUnicode_New(new_size, maxchar);
10414 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010415 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010416 assert(PyUnicode_KIND(u) == rkind);
10417 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010418 ires = i = 0;
10419 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010420 while (n-- > 0) {
10421 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010422 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010423 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010424 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010425 if (j == -1)
10426 break;
10427 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010428 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010429 memcpy(res + rkind * ires,
10430 sbuf + rkind * i,
10431 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010432 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010433 }
10434 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010435 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010436 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010437 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010438 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010439 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010440 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010441 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010442 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010443 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010444 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010445 memcpy(res + rkind * ires,
10446 sbuf + rkind * i,
10447 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010448 }
10449 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010450 /* interleave */
10451 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010452 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010453 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010454 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010455 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010456 if (--n <= 0)
10457 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010458 memcpy(res + rkind * ires,
10459 sbuf + rkind * i,
10460 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010461 ires++;
10462 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010463 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010464 memcpy(res + rkind * ires,
10465 sbuf + rkind * i,
10466 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010467 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010468 }
10469
10470 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010471 unicode_adjust_maxchar(&u);
10472 if (u == NULL)
10473 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010474 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010475
10476 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010477 if (srelease)
10478 PyMem_FREE(sbuf);
10479 if (release1)
10480 PyMem_FREE(buf1);
10481 if (release2)
10482 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010483 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010484 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010485
Benjamin Peterson29060642009-01-31 22:14:21 +000010486 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010487 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010488 if (srelease)
10489 PyMem_FREE(sbuf);
10490 if (release1)
10491 PyMem_FREE(buf1);
10492 if (release2)
10493 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010494 return unicode_result_unchanged(self);
10495
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010496 error:
10497 if (srelease && sbuf)
10498 PyMem_FREE(sbuf);
10499 if (release1 && buf1)
10500 PyMem_FREE(buf1);
10501 if (release2 && buf2)
10502 PyMem_FREE(buf2);
10503 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010504}
10505
10506/* --- Unicode Object Methods --------------------------------------------- */
10507
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010508PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010509 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010510\n\
10511Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010512characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010513
10514static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010515unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010516{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010517 if (PyUnicode_READY(self) == -1)
10518 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010519 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010520}
10521
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010522PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010523 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010524\n\
10525Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010526have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010527
10528static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010529unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010530{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010531 if (PyUnicode_READY(self) == -1)
10532 return NULL;
10533 if (PyUnicode_GET_LENGTH(self) == 0)
10534 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010535 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010536}
10537
Benjamin Petersond5890c82012-01-14 13:23:30 -050010538PyDoc_STRVAR(casefold__doc__,
10539 "S.casefold() -> str\n\
10540\n\
10541Return a version of S suitable for caseless comparisons.");
10542
10543static PyObject *
10544unicode_casefold(PyObject *self)
10545{
10546 if (PyUnicode_READY(self) == -1)
10547 return NULL;
10548 if (PyUnicode_IS_ASCII(self))
10549 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010550 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010551}
10552
10553
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010554/* Argument converter. Coerces to a single unicode character */
10555
10556static int
10557convert_uc(PyObject *obj, void *addr)
10558{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010559 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010560 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010561
Benjamin Peterson14339b62009-01-31 16:36:08 +000010562 uniobj = PyUnicode_FromObject(obj);
10563 if (uniobj == NULL) {
10564 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010565 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010566 return 0;
10567 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010568 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010569 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010570 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010571 Py_DECREF(uniobj);
10572 return 0;
10573 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010574 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010575 Py_DECREF(uniobj);
10576 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010577}
10578
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010579PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010580 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010581\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010582Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010583done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010584
10585static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010586unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010587{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010588 Py_ssize_t marg, left;
10589 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010590 Py_UCS4 fillchar = ' ';
10591
Victor Stinnere9a29352011-10-01 02:14:59 +020010592 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010593 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010594
Benjamin Petersonbac79492012-01-14 13:34:47 -050010595 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010596 return NULL;
10597
Victor Stinnerc4b49542011-12-11 22:44:26 +010010598 if (PyUnicode_GET_LENGTH(self) >= width)
10599 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010600
Victor Stinnerc4b49542011-12-11 22:44:26 +010010601 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010602 left = marg / 2 + (marg & width & 1);
10603
Victor Stinner9310abb2011-10-05 00:59:23 +020010604 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010605}
10606
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010607/* This function assumes that str1 and str2 are readied by the caller. */
10608
Marc-André Lemburge5034372000-08-08 08:04:29 +000010609static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010610unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010611{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010612#define COMPARE(TYPE1, TYPE2) \
10613 do { \
10614 TYPE1* p1 = (TYPE1 *)data1; \
10615 TYPE2* p2 = (TYPE2 *)data2; \
10616 TYPE1* end = p1 + len; \
10617 Py_UCS4 c1, c2; \
10618 for (; p1 != end; p1++, p2++) { \
10619 c1 = *p1; \
10620 c2 = *p2; \
10621 if (c1 != c2) \
10622 return (c1 < c2) ? -1 : 1; \
10623 } \
10624 } \
10625 while (0)
10626
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010627 int kind1, kind2;
10628 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010629 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010630
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010631 kind1 = PyUnicode_KIND(str1);
10632 kind2 = PyUnicode_KIND(str2);
10633 data1 = PyUnicode_DATA(str1);
10634 data2 = PyUnicode_DATA(str2);
10635 len1 = PyUnicode_GET_LENGTH(str1);
10636 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010637 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010638
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010639 switch(kind1) {
10640 case PyUnicode_1BYTE_KIND:
10641 {
10642 switch(kind2) {
10643 case PyUnicode_1BYTE_KIND:
10644 {
10645 int cmp = memcmp(data1, data2, len);
10646 /* normalize result of memcmp() into the range [-1; 1] */
10647 if (cmp < 0)
10648 return -1;
10649 if (cmp > 0)
10650 return 1;
10651 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010652 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010653 case PyUnicode_2BYTE_KIND:
10654 COMPARE(Py_UCS1, Py_UCS2);
10655 break;
10656 case PyUnicode_4BYTE_KIND:
10657 COMPARE(Py_UCS1, Py_UCS4);
10658 break;
10659 default:
10660 assert(0);
10661 }
10662 break;
10663 }
10664 case PyUnicode_2BYTE_KIND:
10665 {
10666 switch(kind2) {
10667 case PyUnicode_1BYTE_KIND:
10668 COMPARE(Py_UCS2, Py_UCS1);
10669 break;
10670 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010671 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010672 COMPARE(Py_UCS2, Py_UCS2);
10673 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010674 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010675 case PyUnicode_4BYTE_KIND:
10676 COMPARE(Py_UCS2, Py_UCS4);
10677 break;
10678 default:
10679 assert(0);
10680 }
10681 break;
10682 }
10683 case PyUnicode_4BYTE_KIND:
10684 {
10685 switch(kind2) {
10686 case PyUnicode_1BYTE_KIND:
10687 COMPARE(Py_UCS4, Py_UCS1);
10688 break;
10689 case PyUnicode_2BYTE_KIND:
10690 COMPARE(Py_UCS4, Py_UCS2);
10691 break;
10692 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010693 {
10694#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10695 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10696 /* normalize result of wmemcmp() into the range [-1; 1] */
10697 if (cmp < 0)
10698 return -1;
10699 if (cmp > 0)
10700 return 1;
10701#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010702 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010703#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010704 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010705 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010706 default:
10707 assert(0);
10708 }
10709 break;
10710 }
10711 default:
10712 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010713 }
10714
Victor Stinner770e19e2012-10-04 22:59:45 +020010715 if (len1 == len2)
10716 return 0;
10717 if (len1 < len2)
10718 return -1;
10719 else
10720 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010721
10722#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010723}
10724
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010725Py_LOCAL(int)
Victor Stinnere5567ad2012-10-23 02:48:49 +020010726unicode_compare_eq(PyObject *str1, PyObject *str2)
10727{
10728 int kind;
10729 void *data1, *data2;
10730 Py_ssize_t len;
10731 int cmp;
10732
Victor Stinnere5567ad2012-10-23 02:48:49 +020010733 len = PyUnicode_GET_LENGTH(str1);
10734 if (PyUnicode_GET_LENGTH(str2) != len)
10735 return 0;
10736 kind = PyUnicode_KIND(str1);
10737 if (PyUnicode_KIND(str2) != kind)
10738 return 0;
10739 data1 = PyUnicode_DATA(str1);
10740 data2 = PyUnicode_DATA(str2);
10741
10742 cmp = memcmp(data1, data2, len * kind);
10743 return (cmp == 0);
10744}
10745
10746
Alexander Belopolsky40018472011-02-26 01:02:56 +000010747int
10748PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010749{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010750 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10751 if (PyUnicode_READY(left) == -1 ||
10752 PyUnicode_READY(right) == -1)
10753 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010754
10755 /* a string is equal to itself */
10756 if (left == right)
10757 return 0;
10758
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010759 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010760 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010761 PyErr_Format(PyExc_TypeError,
10762 "Can't compare %.100s and %.100s",
10763 left->ob_type->tp_name,
10764 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010765 return -1;
10766}
10767
Martin v. Löwis5b222132007-06-10 09:51:05 +000010768int
Victor Stinnerad14ccd2013-11-07 00:46:04 +010010769_PyUnicode_CompareWithId(PyObject *left, _Py_Identifier *right)
10770{
10771 PyObject *right_str = _PyUnicode_FromId(right); /* borrowed */
10772 if (right_str == NULL)
10773 return -1;
10774 return PyUnicode_Compare(left, right_str);
10775}
10776
10777int
Martin v. Löwis5b222132007-06-10 09:51:05 +000010778PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10779{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010780 Py_ssize_t i;
10781 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010782 Py_UCS4 chr;
10783
Victor Stinner910337b2011-10-03 03:20:16 +020010784 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010785 if (PyUnicode_READY(uni) == -1)
10786 return -1;
10787 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010788 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010010789 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010010790 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010791 size_t len, len2 = strlen(str);
10792 int cmp;
10793
10794 len = Py_MIN(len1, len2);
10795 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010010796 if (cmp != 0) {
10797 if (cmp < 0)
10798 return -1;
10799 else
10800 return 1;
10801 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010010802 if (len1 > len2)
10803 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010804 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010010805 return -1; /* str is longer */
10806 return 0;
10807 }
10808 else {
10809 void *data = PyUnicode_DATA(uni);
10810 /* Compare Unicode string and source character set string */
10811 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020010812 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010010813 return (chr < (unsigned char)(str[i])) ? -1 : 1;
10814 /* This check keeps Python strings that end in '\0' from comparing equal
10815 to C strings identical up to that point. */
10816 if (PyUnicode_GET_LENGTH(uni) != i || chr)
10817 return 1; /* uni is longer */
10818 if (str[i])
10819 return -1; /* str is longer */
10820 return 0;
10821 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000010822}
10823
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010824
Benjamin Peterson29060642009-01-31 22:14:21 +000010825#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010826 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010827
Alexander Belopolsky40018472011-02-26 01:02:56 +000010828PyObject *
10829PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010830{
10831 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020010832 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010833
Victor Stinnere5567ad2012-10-23 02:48:49 +020010834 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
10835 Py_RETURN_NOTIMPLEMENTED;
10836
10837 if (PyUnicode_READY(left) == -1 ||
10838 PyUnicode_READY(right) == -1)
10839 return NULL;
10840
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010010841 if (left == right) {
10842 switch (op) {
10843 case Py_EQ:
10844 case Py_LE:
10845 case Py_GE:
10846 /* a string is equal to itself */
10847 v = Py_True;
10848 break;
10849 case Py_NE:
10850 case Py_LT:
10851 case Py_GT:
10852 v = Py_False;
10853 break;
10854 default:
10855 PyErr_BadArgument();
10856 return NULL;
10857 }
10858 }
10859 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020010860 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010861 result ^= (op == Py_NE);
10862 v = TEST_COND(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020010863 }
10864 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020010865 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010866
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010867 /* Convert the return value to a Boolean */
10868 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010869 case Py_LE:
10870 v = TEST_COND(result <= 0);
10871 break;
10872 case Py_GE:
10873 v = TEST_COND(result >= 0);
10874 break;
10875 case Py_LT:
10876 v = TEST_COND(result == -1);
10877 break;
10878 case Py_GT:
10879 v = TEST_COND(result == 1);
10880 break;
10881 default:
10882 PyErr_BadArgument();
10883 return NULL;
10884 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010885 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020010886 Py_INCREF(v);
10887 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010888}
10889
Alexander Belopolsky40018472011-02-26 01:02:56 +000010890int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070010891_PyUnicode_EQ(PyObject *aa, PyObject *bb)
10892{
10893 return unicode_eq(aa, bb);
10894}
10895
10896int
Alexander Belopolsky40018472011-02-26 01:02:56 +000010897PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010898{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010899 PyObject *str, *sub;
Victor Stinner77282cb2013-04-14 19:22:47 +020010900 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010901 void *buf1, *buf2;
10902 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010903 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010904
10905 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010906 sub = PyUnicode_FromObject(element);
10907 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010908 PyErr_Format(PyExc_TypeError,
10909 "'in <string>' requires string as left operand, not %s",
10910 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010911 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010912 }
10913
Thomas Wouters477c8d52006-05-27 19:21:47 +000010914 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010915 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010916 Py_DECREF(sub);
10917 return -1;
10918 }
10919
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010920 kind1 = PyUnicode_KIND(str);
10921 kind2 = PyUnicode_KIND(sub);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010922 if (kind1 < kind2) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010923 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010924 Py_DECREF(str);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010925 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010926 }
10927 len1 = PyUnicode_GET_LENGTH(str);
10928 len2 = PyUnicode_GET_LENGTH(sub);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010929 if (len1 < len2) {
10930 Py_DECREF(sub);
10931 Py_DECREF(str);
10932 return 0;
10933 }
10934 buf1 = PyUnicode_DATA(str);
10935 buf2 = PyUnicode_DATA(sub);
10936 if (len2 == 1) {
10937 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
10938 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
10939 Py_DECREF(sub);
10940 Py_DECREF(str);
10941 return result;
10942 }
10943 if (kind2 != kind1) {
10944 buf2 = _PyUnicode_AsKind(sub, kind1);
10945 if (!buf2) {
10946 Py_DECREF(sub);
10947 Py_DECREF(str);
10948 return -1;
10949 }
10950 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010951
Victor Stinner77282cb2013-04-14 19:22:47 +020010952 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010953 case PyUnicode_1BYTE_KIND:
10954 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10955 break;
10956 case PyUnicode_2BYTE_KIND:
10957 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10958 break;
10959 case PyUnicode_4BYTE_KIND:
10960 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10961 break;
10962 default:
10963 result = -1;
10964 assert(0);
10965 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010966
10967 Py_DECREF(str);
10968 Py_DECREF(sub);
10969
Victor Stinner77282cb2013-04-14 19:22:47 +020010970 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010971 PyMem_Free(buf2);
10972
Guido van Rossum403d68b2000-03-13 15:55:09 +000010973 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010974}
10975
Guido van Rossumd57fd912000-03-10 22:53:23 +000010976/* Concat to string or Unicode object giving a new Unicode object. */
10977
Alexander Belopolsky40018472011-02-26 01:02:56 +000010978PyObject *
10979PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010980{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010981 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010982 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010010983 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010984
10985 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010986 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010987 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010988 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010989 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010990 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010991 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010992
10993 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010994 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010995 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010996 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010997 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010998 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010999 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011000 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011001 }
11002
Victor Stinner488fa492011-12-12 00:01:39 +010011003 u_len = PyUnicode_GET_LENGTH(u);
11004 v_len = PyUnicode_GET_LENGTH(v);
11005 if (u_len > PY_SSIZE_T_MAX - v_len) {
11006 PyErr_SetString(PyExc_OverflowError,
11007 "strings are too large to concat");
11008 goto onError;
11009 }
11010 new_len = u_len + v_len;
11011
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011012 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020011013 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011014 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011015
Guido van Rossumd57fd912000-03-10 22:53:23 +000011016 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010011017 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011018 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011019 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011020 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
11021 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011022 Py_DECREF(u);
11023 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011024 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011025 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011026
Benjamin Peterson29060642009-01-31 22:14:21 +000011027 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000011028 Py_XDECREF(u);
11029 Py_XDECREF(v);
11030 return NULL;
11031}
11032
Walter Dörwald1ab83302007-05-18 17:15:44 +000011033void
Victor Stinner23e56682011-10-03 03:54:37 +020011034PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011035{
Victor Stinner23e56682011-10-03 03:54:37 +020011036 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011037 Py_UCS4 maxchar, maxchar2;
11038 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011039
11040 if (p_left == NULL) {
11041 if (!PyErr_Occurred())
11042 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011043 return;
11044 }
Victor Stinner23e56682011-10-03 03:54:37 +020011045 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011046 if (right == NULL || left == NULL
11047 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011048 if (!PyErr_Occurred())
11049 PyErr_BadInternalCall();
11050 goto error;
11051 }
11052
Benjamin Petersonbac79492012-01-14 13:34:47 -050011053 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011054 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011055 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011056 goto error;
11057
Victor Stinner488fa492011-12-12 00:01:39 +010011058 /* Shortcuts */
11059 if (left == unicode_empty) {
11060 Py_DECREF(left);
11061 Py_INCREF(right);
11062 *p_left = right;
11063 return;
11064 }
11065 if (right == unicode_empty)
11066 return;
11067
11068 left_len = PyUnicode_GET_LENGTH(left);
11069 right_len = PyUnicode_GET_LENGTH(right);
11070 if (left_len > PY_SSIZE_T_MAX - right_len) {
11071 PyErr_SetString(PyExc_OverflowError,
11072 "strings are too large to concat");
11073 goto error;
11074 }
11075 new_len = left_len + right_len;
11076
11077 if (unicode_modifiable(left)
11078 && PyUnicode_CheckExact(right)
11079 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011080 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11081 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011082 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011083 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011084 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11085 {
11086 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011087 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011088 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011089
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011090 /* copy 'right' into the newly allocated area of 'left' */
11091 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011092 }
Victor Stinner488fa492011-12-12 00:01:39 +010011093 else {
11094 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11095 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011096 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011097
Victor Stinner488fa492011-12-12 00:01:39 +010011098 /* Concat the two Unicode strings */
11099 res = PyUnicode_New(new_len, maxchar);
11100 if (res == NULL)
11101 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011102 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11103 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011104 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011105 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011106 }
11107 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011108 return;
11109
11110error:
Victor Stinner488fa492011-12-12 00:01:39 +010011111 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011112}
11113
11114void
11115PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11116{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011117 PyUnicode_Append(pleft, right);
11118 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011119}
11120
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011121PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011122 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011123\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011124Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011125string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011126interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011127
11128static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011129unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011130{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011131 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011132 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011133 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011134 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011135 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011136 void *buf1, *buf2;
11137 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011138
Jesus Ceaac451502011-04-20 17:09:23 +020011139 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
11140 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011141 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011142
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011143 kind1 = PyUnicode_KIND(self);
11144 kind2 = PyUnicode_KIND(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011145 if (kind1 < kind2) {
Christian Heimesd47802e2013-06-29 21:33:36 +020011146 Py_DECREF(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011147 return PyLong_FromLong(0);
Christian Heimesd47802e2013-06-29 21:33:36 +020011148 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011149 len1 = PyUnicode_GET_LENGTH(self);
11150 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011151 ADJUST_INDICES(start, end, len1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011152 if (end - start < len2) {
11153 Py_DECREF(substring);
11154 return PyLong_FromLong(0);
11155 }
11156 buf1 = PyUnicode_DATA(self);
11157 buf2 = PyUnicode_DATA(substring);
11158 if (kind2 != kind1) {
11159 buf2 = _PyUnicode_AsKind(substring, kind1);
11160 if (!buf2) {
11161 Py_DECREF(substring);
11162 return NULL;
11163 }
11164 }
11165 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011166 case PyUnicode_1BYTE_KIND:
11167 iresult = ucs1lib_count(
11168 ((Py_UCS1*)buf1) + start, end - start,
11169 buf2, len2, PY_SSIZE_T_MAX
11170 );
11171 break;
11172 case PyUnicode_2BYTE_KIND:
11173 iresult = ucs2lib_count(
11174 ((Py_UCS2*)buf1) + start, end - start,
11175 buf2, len2, PY_SSIZE_T_MAX
11176 );
11177 break;
11178 case PyUnicode_4BYTE_KIND:
11179 iresult = ucs4lib_count(
11180 ((Py_UCS4*)buf1) + start, end - start,
11181 buf2, len2, PY_SSIZE_T_MAX
11182 );
11183 break;
11184 default:
11185 assert(0); iresult = 0;
11186 }
11187
11188 result = PyLong_FromSsize_t(iresult);
11189
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011190 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011191 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011192
11193 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011194
Guido van Rossumd57fd912000-03-10 22:53:23 +000011195 return result;
11196}
11197
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011198PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011199 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011200\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011201Encode S using the codec registered for encoding. Default encoding\n\
11202is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011203handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011204a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11205'xmlcharrefreplace' as well as any other name registered with\n\
11206codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011207
11208static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011209unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011210{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011211 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011212 char *encoding = NULL;
11213 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011214
Benjamin Peterson308d6372009-09-18 21:42:35 +000011215 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11216 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011217 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011218 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011219}
11220
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011221PyDoc_STRVAR(expandtabs__doc__,
Ezio Melotti745d54d2013-11-16 19:10:57 +020011222 "S.expandtabs(tabsize=8) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011223\n\
11224Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011225If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011226
11227static PyObject*
Ezio Melotti745d54d2013-11-16 19:10:57 +020011228unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011229{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011230 Py_ssize_t i, j, line_pos, src_len, incr;
11231 Py_UCS4 ch;
11232 PyObject *u;
11233 void *src_data, *dest_data;
Ezio Melotti745d54d2013-11-16 19:10:57 +020011234 static char *kwlist[] = {"tabsize", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011235 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011236 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011237 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011238
Ezio Melotti745d54d2013-11-16 19:10:57 +020011239 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs",
11240 kwlist, &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011241 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011242
Antoine Pitrou22425222011-10-04 19:10:51 +020011243 if (PyUnicode_READY(self) == -1)
11244 return NULL;
11245
Thomas Wouters7e474022000-07-16 12:04:32 +000011246 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011247 src_len = PyUnicode_GET_LENGTH(self);
11248 i = j = line_pos = 0;
11249 kind = PyUnicode_KIND(self);
11250 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011251 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011252 for (; i < src_len; i++) {
11253 ch = PyUnicode_READ(kind, src_data, i);
11254 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011255 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011256 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011257 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011258 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011259 goto overflow;
11260 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011261 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011262 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011263 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011264 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011265 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011266 goto overflow;
11267 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011268 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011269 if (ch == '\n' || ch == '\r')
11270 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011271 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011272 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011273 if (!found)
11274 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011275
Guido van Rossumd57fd912000-03-10 22:53:23 +000011276 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011277 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011278 if (!u)
11279 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011280 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011281
Antoine Pitroue71d5742011-10-04 15:55:09 +020011282 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011283
Antoine Pitroue71d5742011-10-04 15:55:09 +020011284 for (; i < src_len; i++) {
11285 ch = PyUnicode_READ(kind, src_data, i);
11286 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011287 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011288 incr = tabsize - (line_pos % tabsize);
11289 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011290 FILL(kind, dest_data, ' ', j, incr);
11291 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011292 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011293 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011294 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011295 line_pos++;
11296 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011297 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011298 if (ch == '\n' || ch == '\r')
11299 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011300 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011301 }
11302 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011303 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011304
Antoine Pitroue71d5742011-10-04 15:55:09 +020011305 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011306 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11307 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011308}
11309
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011310PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011311 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011312\n\
11313Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011314such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011315arguments start and end are interpreted as in slice notation.\n\
11316\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011317Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011318
11319static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011320unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011321{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011322 /* initialize variables to prevent gcc warning */
11323 PyObject *substring = NULL;
11324 Py_ssize_t start = 0;
11325 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011326 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011327
Jesus Ceaac451502011-04-20 17:09:23 +020011328 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11329 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011330 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011331
Christian Heimesd47802e2013-06-29 21:33:36 +020011332 if (PyUnicode_READY(self) == -1) {
11333 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011334 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011335 }
11336 if (PyUnicode_READY(substring) == -1) {
11337 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011338 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011339 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011340
Victor Stinner7931d9a2011-11-04 00:22:48 +010011341 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011342
11343 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011344
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011345 if (result == -2)
11346 return NULL;
11347
Christian Heimes217cfd12007-12-02 14:31:20 +000011348 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011349}
11350
11351static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011352unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011353{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011354 void *data;
11355 enum PyUnicode_Kind kind;
11356 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011357
11358 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11359 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011360 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011361 }
11362 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11363 PyErr_SetString(PyExc_IndexError, "string index out of range");
11364 return NULL;
11365 }
11366 kind = PyUnicode_KIND(self);
11367 data = PyUnicode_DATA(self);
11368 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011369 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011370}
11371
Guido van Rossumc2504932007-09-18 19:42:40 +000011372/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011373 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011374static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011375unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011376{
Guido van Rossumc2504932007-09-18 19:42:40 +000011377 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011378 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011379
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011380#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011381 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011382#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011383 if (_PyUnicode_HASH(self) != -1)
11384 return _PyUnicode_HASH(self);
11385 if (PyUnicode_READY(self) == -1)
11386 return -1;
11387 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011388 /*
11389 We make the hash of the empty string be 0, rather than using
11390 (prefix ^ suffix), since this slightly obfuscates the hash secret
11391 */
11392 if (len == 0) {
11393 _PyUnicode_HASH(self) = 0;
11394 return 0;
11395 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011396 x = _Py_HashBytes(PyUnicode_DATA(self),
11397 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011398 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011399 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011400}
11401
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011402PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011403 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011404\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011405Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011406
11407static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011408unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011409{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011410 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011411 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011412 PyObject *substring = NULL;
11413 Py_ssize_t start = 0;
11414 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011415
Jesus Ceaac451502011-04-20 17:09:23 +020011416 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11417 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011418 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011419
Christian Heimesd47a0452013-06-29 21:21:37 +020011420 if (PyUnicode_READY(self) == -1) {
11421 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011422 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011423 }
11424 if (PyUnicode_READY(substring) == -1) {
11425 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011426 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011427 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011428
Victor Stinner7931d9a2011-11-04 00:22:48 +010011429 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011430
11431 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011432
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011433 if (result == -2)
11434 return NULL;
11435
Guido van Rossumd57fd912000-03-10 22:53:23 +000011436 if (result < 0) {
11437 PyErr_SetString(PyExc_ValueError, "substring not found");
11438 return NULL;
11439 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011440
Christian Heimes217cfd12007-12-02 14:31:20 +000011441 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011442}
11443
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011444PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011445 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011446\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011447Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011448at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011449
11450static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011451unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011452{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011453 Py_ssize_t i, length;
11454 int kind;
11455 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011456 int cased;
11457
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011458 if (PyUnicode_READY(self) == -1)
11459 return NULL;
11460 length = PyUnicode_GET_LENGTH(self);
11461 kind = PyUnicode_KIND(self);
11462 data = PyUnicode_DATA(self);
11463
Guido van Rossumd57fd912000-03-10 22:53:23 +000011464 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011465 if (length == 1)
11466 return PyBool_FromLong(
11467 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011468
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011469 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011470 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011471 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011472
Guido van Rossumd57fd912000-03-10 22:53:23 +000011473 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011474 for (i = 0; i < length; i++) {
11475 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011476
Benjamin Peterson29060642009-01-31 22:14:21 +000011477 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11478 return PyBool_FromLong(0);
11479 else if (!cased && Py_UNICODE_ISLOWER(ch))
11480 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011481 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011482 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011483}
11484
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011485PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011486 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011487\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011488Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011489at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011490
11491static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011492unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011493{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011494 Py_ssize_t i, length;
11495 int kind;
11496 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011497 int cased;
11498
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011499 if (PyUnicode_READY(self) == -1)
11500 return NULL;
11501 length = PyUnicode_GET_LENGTH(self);
11502 kind = PyUnicode_KIND(self);
11503 data = PyUnicode_DATA(self);
11504
Guido van Rossumd57fd912000-03-10 22:53:23 +000011505 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011506 if (length == 1)
11507 return PyBool_FromLong(
11508 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011509
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011510 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011511 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011512 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011513
Guido van Rossumd57fd912000-03-10 22:53:23 +000011514 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011515 for (i = 0; i < length; i++) {
11516 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011517
Benjamin Peterson29060642009-01-31 22:14:21 +000011518 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11519 return PyBool_FromLong(0);
11520 else if (!cased && Py_UNICODE_ISUPPER(ch))
11521 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011522 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011523 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011524}
11525
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011526PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011527 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011528\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011529Return True if S is a titlecased string and there is at least one\n\
11530character in S, i.e. upper- and titlecase characters may only\n\
11531follow uncased characters and lowercase characters only cased ones.\n\
11532Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011533
11534static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011535unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011536{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011537 Py_ssize_t i, length;
11538 int kind;
11539 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011540 int cased, previous_is_cased;
11541
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011542 if (PyUnicode_READY(self) == -1)
11543 return NULL;
11544 length = PyUnicode_GET_LENGTH(self);
11545 kind = PyUnicode_KIND(self);
11546 data = PyUnicode_DATA(self);
11547
Guido van Rossumd57fd912000-03-10 22:53:23 +000011548 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011549 if (length == 1) {
11550 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11551 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11552 (Py_UNICODE_ISUPPER(ch) != 0));
11553 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011554
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011555 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011556 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011557 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011558
Guido van Rossumd57fd912000-03-10 22:53:23 +000011559 cased = 0;
11560 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011561 for (i = 0; i < length; i++) {
11562 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011563
Benjamin Peterson29060642009-01-31 22:14:21 +000011564 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11565 if (previous_is_cased)
11566 return PyBool_FromLong(0);
11567 previous_is_cased = 1;
11568 cased = 1;
11569 }
11570 else if (Py_UNICODE_ISLOWER(ch)) {
11571 if (!previous_is_cased)
11572 return PyBool_FromLong(0);
11573 previous_is_cased = 1;
11574 cased = 1;
11575 }
11576 else
11577 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011578 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011579 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011580}
11581
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011582PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011583 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011584\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011585Return True if all characters in S are whitespace\n\
11586and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011587
11588static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011589unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011590{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011591 Py_ssize_t i, length;
11592 int kind;
11593 void *data;
11594
11595 if (PyUnicode_READY(self) == -1)
11596 return NULL;
11597 length = PyUnicode_GET_LENGTH(self);
11598 kind = PyUnicode_KIND(self);
11599 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011600
Guido van Rossumd57fd912000-03-10 22:53:23 +000011601 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011602 if (length == 1)
11603 return PyBool_FromLong(
11604 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011605
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011606 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011607 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011608 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011609
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011610 for (i = 0; i < length; i++) {
11611 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011612 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011613 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011614 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011615 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011616}
11617
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011618PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011619 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011620\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011621Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011622and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011623
11624static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011625unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011626{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011627 Py_ssize_t i, length;
11628 int kind;
11629 void *data;
11630
11631 if (PyUnicode_READY(self) == -1)
11632 return NULL;
11633 length = PyUnicode_GET_LENGTH(self);
11634 kind = PyUnicode_KIND(self);
11635 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011636
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011637 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011638 if (length == 1)
11639 return PyBool_FromLong(
11640 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011641
11642 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011643 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011644 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011645
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011646 for (i = 0; i < length; i++) {
11647 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011648 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011649 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011650 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011651}
11652
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011653PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011654 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011655\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011656Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011657and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011658
11659static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011660unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011661{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011662 int kind;
11663 void *data;
11664 Py_ssize_t len, i;
11665
11666 if (PyUnicode_READY(self) == -1)
11667 return NULL;
11668
11669 kind = PyUnicode_KIND(self);
11670 data = PyUnicode_DATA(self);
11671 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011672
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011673 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011674 if (len == 1) {
11675 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11676 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11677 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011678
11679 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011680 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011681 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011682
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011683 for (i = 0; i < len; i++) {
11684 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011685 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011686 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011687 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011688 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011689}
11690
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011691PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011692 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011693\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011694Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011695False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011696
11697static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011698unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011699{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011700 Py_ssize_t i, length;
11701 int kind;
11702 void *data;
11703
11704 if (PyUnicode_READY(self) == -1)
11705 return NULL;
11706 length = PyUnicode_GET_LENGTH(self);
11707 kind = PyUnicode_KIND(self);
11708 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011709
Guido van Rossumd57fd912000-03-10 22:53:23 +000011710 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011711 if (length == 1)
11712 return PyBool_FromLong(
11713 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011714
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011715 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011716 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011717 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011718
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011719 for (i = 0; i < length; i++) {
11720 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011721 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011722 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011723 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011724}
11725
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011726PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011727 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011728\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011729Return True if all characters in S are digits\n\
11730and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011731
11732static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011733unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011734{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011735 Py_ssize_t i, length;
11736 int kind;
11737 void *data;
11738
11739 if (PyUnicode_READY(self) == -1)
11740 return NULL;
11741 length = PyUnicode_GET_LENGTH(self);
11742 kind = PyUnicode_KIND(self);
11743 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011744
Guido van Rossumd57fd912000-03-10 22:53:23 +000011745 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011746 if (length == 1) {
11747 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11748 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11749 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011750
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011751 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011752 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011753 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011754
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011755 for (i = 0; i < length; i++) {
11756 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011757 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011758 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011759 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011760}
11761
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011762PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011763 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011764\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011765Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011766False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011767
11768static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011769unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011770{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011771 Py_ssize_t i, length;
11772 int kind;
11773 void *data;
11774
11775 if (PyUnicode_READY(self) == -1)
11776 return NULL;
11777 length = PyUnicode_GET_LENGTH(self);
11778 kind = PyUnicode_KIND(self);
11779 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011780
Guido van Rossumd57fd912000-03-10 22:53:23 +000011781 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011782 if (length == 1)
11783 return PyBool_FromLong(
11784 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011785
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011786 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011787 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011788 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011789
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011790 for (i = 0; i < length; i++) {
11791 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011792 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011793 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011794 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011795}
11796
Martin v. Löwis47383402007-08-15 07:32:56 +000011797int
11798PyUnicode_IsIdentifier(PyObject *self)
11799{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011800 int kind;
11801 void *data;
11802 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011803 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011804
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011805 if (PyUnicode_READY(self) == -1) {
11806 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011807 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011808 }
11809
11810 /* Special case for empty strings */
11811 if (PyUnicode_GET_LENGTH(self) == 0)
11812 return 0;
11813 kind = PyUnicode_KIND(self);
11814 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011815
11816 /* PEP 3131 says that the first character must be in
11817 XID_Start and subsequent characters in XID_Continue,
11818 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011819 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011820 letters, digits, underscore). However, given the current
11821 definition of XID_Start and XID_Continue, it is sufficient
11822 to check just for these, except that _ must be allowed
11823 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011824 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011825 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011826 return 0;
11827
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011828 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011829 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011830 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011831 return 1;
11832}
11833
11834PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011835 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011836\n\
11837Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070011838to the language definition.\n\
11839\n\
11840Use keyword.iskeyword() to test for reserved identifiers\n\
11841such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000011842
11843static PyObject*
11844unicode_isidentifier(PyObject *self)
11845{
11846 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11847}
11848
Georg Brandl559e5d72008-06-11 18:37:52 +000011849PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011850 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011851\n\
11852Return True if all characters in S are considered\n\
11853printable in repr() or S is empty, False otherwise.");
11854
11855static PyObject*
11856unicode_isprintable(PyObject *self)
11857{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011858 Py_ssize_t i, length;
11859 int kind;
11860 void *data;
11861
11862 if (PyUnicode_READY(self) == -1)
11863 return NULL;
11864 length = PyUnicode_GET_LENGTH(self);
11865 kind = PyUnicode_KIND(self);
11866 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011867
11868 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011869 if (length == 1)
11870 return PyBool_FromLong(
11871 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011872
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011873 for (i = 0; i < length; i++) {
11874 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011875 Py_RETURN_FALSE;
11876 }
11877 }
11878 Py_RETURN_TRUE;
11879}
11880
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011881PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011882 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011883\n\
11884Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011885iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011886
11887static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011888unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011889{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011890 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011891}
11892
Martin v. Löwis18e16552006-02-15 17:27:45 +000011893static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011894unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011895{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011896 if (PyUnicode_READY(self) == -1)
11897 return -1;
11898 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011899}
11900
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011901PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011902 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011903\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011904Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011905done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011906
11907static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011908unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011909{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011910 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011911 Py_UCS4 fillchar = ' ';
11912
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011913 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011914 return NULL;
11915
Benjamin Petersonbac79492012-01-14 13:34:47 -050011916 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011917 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011918
Victor Stinnerc4b49542011-12-11 22:44:26 +010011919 if (PyUnicode_GET_LENGTH(self) >= width)
11920 return unicode_result_unchanged(self);
11921
11922 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011923}
11924
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011925PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011926 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011927\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011928Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011929
11930static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011931unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011932{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011933 if (PyUnicode_READY(self) == -1)
11934 return NULL;
11935 if (PyUnicode_IS_ASCII(self))
11936 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011937 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011938}
11939
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011940#define LEFTSTRIP 0
11941#define RIGHTSTRIP 1
11942#define BOTHSTRIP 2
11943
11944/* Arrays indexed by above */
11945static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11946
11947#define STRIPNAME(i) (stripformat[i]+3)
11948
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011949/* externally visible for str.strip(unicode) */
11950PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011951_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011952{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011953 void *data;
11954 int kind;
11955 Py_ssize_t i, j, len;
11956 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020011957 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011958
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011959 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11960 return NULL;
11961
11962 kind = PyUnicode_KIND(self);
11963 data = PyUnicode_DATA(self);
11964 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020011965 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011966 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11967 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020011968 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011969
Benjamin Peterson14339b62009-01-31 16:36:08 +000011970 i = 0;
11971 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011972 while (i < len) {
11973 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
11974 if (!BLOOM(sepmask, ch))
11975 break;
11976 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
11977 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000011978 i++;
11979 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011980 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011981
Benjamin Peterson14339b62009-01-31 16:36:08 +000011982 j = len;
11983 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020011984 j--;
11985 while (j >= i) {
11986 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
11987 if (!BLOOM(sepmask, ch))
11988 break;
11989 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
11990 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000011991 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020011992 }
11993
Benjamin Peterson29060642009-01-31 22:14:21 +000011994 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011995 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011996
Victor Stinner7931d9a2011-11-04 00:22:48 +010011997 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011998}
11999
12000PyObject*
12001PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12002{
12003 unsigned char *data;
12004 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012005 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012006
Victor Stinnerde636f32011-10-01 03:55:54 +020012007 if (PyUnicode_READY(self) == -1)
12008 return NULL;
12009
Victor Stinner684d5fd2012-05-03 02:32:34 +020012010 length = PyUnicode_GET_LENGTH(self);
12011 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012012
Victor Stinner684d5fd2012-05-03 02:32:34 +020012013 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012014 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012015
Victor Stinnerde636f32011-10-01 03:55:54 +020012016 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012017 PyErr_SetString(PyExc_IndexError, "string index out of range");
12018 return NULL;
12019 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012020 if (start >= length || end < start)
12021 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012022
Victor Stinner684d5fd2012-05-03 02:32:34 +020012023 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012024 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012025 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012026 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012027 }
12028 else {
12029 kind = PyUnicode_KIND(self);
12030 data = PyUnicode_1BYTE_DATA(self);
12031 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012032 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012033 length);
12034 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012035}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012036
12037static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012038do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012039{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012040 Py_ssize_t len, i, j;
12041
12042 if (PyUnicode_READY(self) == -1)
12043 return NULL;
12044
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012045 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012046
Victor Stinnercc7af722013-04-09 22:39:24 +020012047 if (PyUnicode_IS_ASCII(self)) {
12048 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12049
12050 i = 0;
12051 if (striptype != RIGHTSTRIP) {
12052 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012053 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012054 if (!_Py_ascii_whitespace[ch])
12055 break;
12056 i++;
12057 }
12058 }
12059
12060 j = len;
12061 if (striptype != LEFTSTRIP) {
12062 j--;
12063 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012064 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012065 if (!_Py_ascii_whitespace[ch])
12066 break;
12067 j--;
12068 }
12069 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012070 }
12071 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012072 else {
12073 int kind = PyUnicode_KIND(self);
12074 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012075
Victor Stinnercc7af722013-04-09 22:39:24 +020012076 i = 0;
12077 if (striptype != RIGHTSTRIP) {
12078 while (i < len) {
12079 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12080 if (!Py_UNICODE_ISSPACE(ch))
12081 break;
12082 i++;
12083 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012084 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012085
12086 j = len;
12087 if (striptype != LEFTSTRIP) {
12088 j--;
12089 while (j >= i) {
12090 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12091 if (!Py_UNICODE_ISSPACE(ch))
12092 break;
12093 j--;
12094 }
12095 j++;
12096 }
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);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012100}
12101
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012102
12103static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012104do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012105{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012106 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012107
Serhiy Storchakac6792272013-10-19 21:03:34 +030012108 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012109 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012110
Benjamin Peterson14339b62009-01-31 16:36:08 +000012111 if (sep != NULL && sep != Py_None) {
12112 if (PyUnicode_Check(sep))
12113 return _PyUnicode_XStrip(self, striptype, sep);
12114 else {
12115 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012116 "%s arg must be None or str",
12117 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012118 return NULL;
12119 }
12120 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012121
Benjamin Peterson14339b62009-01-31 16:36:08 +000012122 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012123}
12124
12125
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012126PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012127 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012128\n\
12129Return a copy of the string S with leading and trailing\n\
12130whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012131If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012132
12133static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012134unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012135{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012136 if (PyTuple_GET_SIZE(args) == 0)
12137 return do_strip(self, BOTHSTRIP); /* Common case */
12138 else
12139 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012140}
12141
12142
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012143PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012144 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012145\n\
12146Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012147If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012148
12149static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012150unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012151{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012152 if (PyTuple_GET_SIZE(args) == 0)
12153 return do_strip(self, LEFTSTRIP); /* Common case */
12154 else
12155 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012156}
12157
12158
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012159PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012160 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012161\n\
12162Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012163If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012164
12165static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012166unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012167{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012168 if (PyTuple_GET_SIZE(args) == 0)
12169 return do_strip(self, RIGHTSTRIP); /* Common case */
12170 else
12171 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012172}
12173
12174
Guido van Rossumd57fd912000-03-10 22:53:23 +000012175static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012176unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012177{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012178 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012179 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012180
Serhiy Storchaka05997252013-01-26 12:14:02 +020012181 if (len < 1)
12182 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012183
Victor Stinnerc4b49542011-12-11 22:44:26 +010012184 /* no repeat, return original string */
12185 if (len == 1)
12186 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012187
Benjamin Petersonbac79492012-01-14 13:34:47 -050012188 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012189 return NULL;
12190
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012191 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012192 PyErr_SetString(PyExc_OverflowError,
12193 "repeated string is too long");
12194 return NULL;
12195 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012196 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012197
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012198 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012199 if (!u)
12200 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012201 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012202
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012203 if (PyUnicode_GET_LENGTH(str) == 1) {
12204 const int kind = PyUnicode_KIND(str);
12205 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012206 if (kind == PyUnicode_1BYTE_KIND) {
12207 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012208 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012209 }
12210 else if (kind == PyUnicode_2BYTE_KIND) {
12211 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012212 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012213 ucs2[n] = fill_char;
12214 } else {
12215 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12216 assert(kind == PyUnicode_4BYTE_KIND);
12217 for (n = 0; n < len; ++n)
12218 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012219 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012220 }
12221 else {
12222 /* number of characters copied this far */
12223 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012224 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012225 char *to = (char *) PyUnicode_DATA(u);
12226 Py_MEMCPY(to, PyUnicode_DATA(str),
12227 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012228 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012229 n = (done <= nchars-done) ? done : nchars-done;
12230 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012231 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012232 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012233 }
12234
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012235 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012236 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012237}
12238
Alexander Belopolsky40018472011-02-26 01:02:56 +000012239PyObject *
12240PyUnicode_Replace(PyObject *obj,
12241 PyObject *subobj,
12242 PyObject *replobj,
12243 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012244{
12245 PyObject *self;
12246 PyObject *str1;
12247 PyObject *str2;
12248 PyObject *result;
12249
12250 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012251 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012252 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012253 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012254 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012255 Py_DECREF(self);
12256 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012257 }
12258 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012259 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012260 Py_DECREF(self);
12261 Py_DECREF(str1);
12262 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012263 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012264 if (PyUnicode_READY(self) == -1 ||
12265 PyUnicode_READY(str1) == -1 ||
12266 PyUnicode_READY(str2) == -1)
12267 result = NULL;
12268 else
12269 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012270 Py_DECREF(self);
12271 Py_DECREF(str1);
12272 Py_DECREF(str2);
12273 return result;
12274}
12275
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012276PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012277 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012278\n\
12279Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012280old replaced by new. If the optional argument count is\n\
12281given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012282
12283static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012284unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012285{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012286 PyObject *str1;
12287 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012288 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012289 PyObject *result;
12290
Martin v. Löwis18e16552006-02-15 17:27:45 +000012291 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012292 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012293 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012294 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012295 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012296 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012297 return NULL;
12298 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012299 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012300 Py_DECREF(str1);
12301 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012302 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012303 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
12304 result = NULL;
12305 else
12306 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012307
12308 Py_DECREF(str1);
12309 Py_DECREF(str2);
12310 return result;
12311}
12312
Alexander Belopolsky40018472011-02-26 01:02:56 +000012313static PyObject *
12314unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012315{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012316 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012317 Py_ssize_t isize;
12318 Py_ssize_t osize, squote, dquote, i, o;
12319 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012320 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012321 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012322
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012323 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012324 return NULL;
12325
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012326 isize = PyUnicode_GET_LENGTH(unicode);
12327 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012328
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012329 /* Compute length of output, quote characters, and
12330 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012331 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012332 max = 127;
12333 squote = dquote = 0;
12334 ikind = PyUnicode_KIND(unicode);
12335 for (i = 0; i < isize; i++) {
12336 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012337 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012338 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012339 case '\'': squote++; break;
12340 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012341 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012342 incr = 2;
12343 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012344 default:
12345 /* Fast-path ASCII */
12346 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012347 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012348 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012349 ;
12350 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012351 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012352 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012353 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012354 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012355 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012356 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012357 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012358 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012359 if (osize > PY_SSIZE_T_MAX - incr) {
12360 PyErr_SetString(PyExc_OverflowError,
12361 "string is too long to generate repr");
12362 return NULL;
12363 }
12364 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012365 }
12366
12367 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012368 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012369 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012370 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012371 if (dquote)
12372 /* Both squote and dquote present. Use squote,
12373 and escape them */
12374 osize += squote;
12375 else
12376 quote = '"';
12377 }
Victor Stinner55c08782013-04-14 18:45:39 +020012378 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012379
12380 repr = PyUnicode_New(osize, max);
12381 if (repr == NULL)
12382 return NULL;
12383 okind = PyUnicode_KIND(repr);
12384 odata = PyUnicode_DATA(repr);
12385
12386 PyUnicode_WRITE(okind, odata, 0, quote);
12387 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012388 if (unchanged) {
12389 _PyUnicode_FastCopyCharacters(repr, 1,
12390 unicode, 0,
12391 isize);
12392 }
12393 else {
12394 for (i = 0, o = 1; i < isize; i++) {
12395 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012396
Victor Stinner55c08782013-04-14 18:45:39 +020012397 /* Escape quotes and backslashes */
12398 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012399 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012400 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012401 continue;
12402 }
12403
12404 /* Map special whitespace to '\t', \n', '\r' */
12405 if (ch == '\t') {
12406 PyUnicode_WRITE(okind, odata, o++, '\\');
12407 PyUnicode_WRITE(okind, odata, o++, 't');
12408 }
12409 else if (ch == '\n') {
12410 PyUnicode_WRITE(okind, odata, o++, '\\');
12411 PyUnicode_WRITE(okind, odata, o++, 'n');
12412 }
12413 else if (ch == '\r') {
12414 PyUnicode_WRITE(okind, odata, o++, '\\');
12415 PyUnicode_WRITE(okind, odata, o++, 'r');
12416 }
12417
12418 /* Map non-printable US ASCII to '\xhh' */
12419 else if (ch < ' ' || ch == 0x7F) {
12420 PyUnicode_WRITE(okind, odata, o++, '\\');
12421 PyUnicode_WRITE(okind, odata, o++, 'x');
12422 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12423 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12424 }
12425
12426 /* Copy ASCII characters as-is */
12427 else if (ch < 0x7F) {
12428 PyUnicode_WRITE(okind, odata, o++, ch);
12429 }
12430
12431 /* Non-ASCII characters */
12432 else {
12433 /* Map Unicode whitespace and control characters
12434 (categories Z* and C* except ASCII space)
12435 */
12436 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12437 PyUnicode_WRITE(okind, odata, o++, '\\');
12438 /* Map 8-bit characters to '\xhh' */
12439 if (ch <= 0xff) {
12440 PyUnicode_WRITE(okind, odata, o++, 'x');
12441 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12442 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12443 }
12444 /* Map 16-bit characters to '\uxxxx' */
12445 else if (ch <= 0xffff) {
12446 PyUnicode_WRITE(okind, odata, o++, 'u');
12447 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12448 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12449 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12450 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12451 }
12452 /* Map 21-bit characters to '\U00xxxxxx' */
12453 else {
12454 PyUnicode_WRITE(okind, odata, o++, 'U');
12455 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12456 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12457 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12458 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12459 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12460 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12461 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12462 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12463 }
12464 }
12465 /* Copy characters as-is */
12466 else {
12467 PyUnicode_WRITE(okind, odata, o++, ch);
12468 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012469 }
12470 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012471 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012472 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012473 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012474 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012475}
12476
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012477PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012478 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012479\n\
12480Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012481such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012482arguments start and end are interpreted as in slice notation.\n\
12483\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012484Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012485
12486static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012487unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012488{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012489 /* initialize variables to prevent gcc warning */
12490 PyObject *substring = NULL;
12491 Py_ssize_t start = 0;
12492 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012493 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012494
Jesus Ceaac451502011-04-20 17:09:23 +020012495 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12496 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012497 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012498
Christian Heimesea71a522013-06-29 21:17:34 +020012499 if (PyUnicode_READY(self) == -1) {
12500 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012501 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012502 }
12503 if (PyUnicode_READY(substring) == -1) {
12504 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012505 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012506 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012507
Victor Stinner7931d9a2011-11-04 00:22:48 +010012508 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012509
12510 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012511
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012512 if (result == -2)
12513 return NULL;
12514
Christian Heimes217cfd12007-12-02 14:31:20 +000012515 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012516}
12517
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012518PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012519 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012520\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012521Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012522
12523static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012524unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012525{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012526 /* initialize variables to prevent gcc warning */
12527 PyObject *substring = NULL;
12528 Py_ssize_t start = 0;
12529 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012530 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012531
Jesus Ceaac451502011-04-20 17:09:23 +020012532 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12533 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012534 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012535
Christian Heimesea71a522013-06-29 21:17:34 +020012536 if (PyUnicode_READY(self) == -1) {
12537 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012538 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012539 }
12540 if (PyUnicode_READY(substring) == -1) {
12541 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012542 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012543 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012544
Victor Stinner7931d9a2011-11-04 00:22:48 +010012545 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012546
12547 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012548
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012549 if (result == -2)
12550 return NULL;
12551
Guido van Rossumd57fd912000-03-10 22:53:23 +000012552 if (result < 0) {
12553 PyErr_SetString(PyExc_ValueError, "substring not found");
12554 return NULL;
12555 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012556
Christian Heimes217cfd12007-12-02 14:31:20 +000012557 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012558}
12559
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012560PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012561 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012562\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012563Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012564done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012565
12566static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012567unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012568{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012569 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012570 Py_UCS4 fillchar = ' ';
12571
Victor Stinnere9a29352011-10-01 02:14:59 +020012572 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012573 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012574
Benjamin Petersonbac79492012-01-14 13:34:47 -050012575 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012576 return NULL;
12577
Victor Stinnerc4b49542011-12-11 22:44:26 +010012578 if (PyUnicode_GET_LENGTH(self) >= width)
12579 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012580
Victor Stinnerc4b49542011-12-11 22:44:26 +010012581 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012582}
12583
Alexander Belopolsky40018472011-02-26 01:02:56 +000012584PyObject *
12585PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012586{
12587 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012588
Guido van Rossumd57fd912000-03-10 22:53:23 +000012589 s = PyUnicode_FromObject(s);
12590 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012591 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012592 if (sep != NULL) {
12593 sep = PyUnicode_FromObject(sep);
12594 if (sep == NULL) {
12595 Py_DECREF(s);
12596 return NULL;
12597 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012598 }
12599
Victor Stinner9310abb2011-10-05 00:59:23 +020012600 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012601
12602 Py_DECREF(s);
12603 Py_XDECREF(sep);
12604 return result;
12605}
12606
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012607PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012608 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012609\n\
12610Return a list of the words in S, using sep as the\n\
12611delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012612splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012613whitespace string is a separator and empty strings are\n\
12614removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012615
12616static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012617unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012618{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012619 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012620 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012621 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012622
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012623 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12624 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012625 return NULL;
12626
12627 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012628 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012629 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012630 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012631 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012632 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012633}
12634
Thomas Wouters477c8d52006-05-27 19:21:47 +000012635PyObject *
12636PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12637{
12638 PyObject* str_obj;
12639 PyObject* sep_obj;
12640 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012641 int kind1, kind2;
12642 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012643 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012644
12645 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012646 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012647 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012648 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012649 if (!sep_obj) {
12650 Py_DECREF(str_obj);
12651 return NULL;
12652 }
12653 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12654 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012655 Py_DECREF(str_obj);
12656 return NULL;
12657 }
12658
Victor Stinner14f8f022011-10-05 20:58:25 +020012659 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012660 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012661 len1 = PyUnicode_GET_LENGTH(str_obj);
12662 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012663 if (kind1 < kind2 || len1 < len2) {
12664 _Py_INCREF_UNICODE_EMPTY();
12665 if (!unicode_empty)
12666 out = NULL;
12667 else {
12668 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12669 Py_DECREF(unicode_empty);
12670 }
12671 Py_DECREF(sep_obj);
12672 Py_DECREF(str_obj);
12673 return out;
12674 }
12675 buf1 = PyUnicode_DATA(str_obj);
12676 buf2 = PyUnicode_DATA(sep_obj);
12677 if (kind2 != kind1) {
12678 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12679 if (!buf2)
12680 goto onError;
12681 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012682
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012683 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012684 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012685 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12686 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12687 else
12688 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012689 break;
12690 case PyUnicode_2BYTE_KIND:
12691 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12692 break;
12693 case PyUnicode_4BYTE_KIND:
12694 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12695 break;
12696 default:
12697 assert(0);
12698 out = 0;
12699 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012700
12701 Py_DECREF(sep_obj);
12702 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012703 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012704 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012705
12706 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012707 onError:
12708 Py_DECREF(sep_obj);
12709 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012710 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012711 PyMem_Free(buf2);
12712 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012713}
12714
12715
12716PyObject *
12717PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12718{
12719 PyObject* str_obj;
12720 PyObject* sep_obj;
12721 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012722 int kind1, kind2;
12723 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012724 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012725
12726 str_obj = PyUnicode_FromObject(str_in);
12727 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012728 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012729 sep_obj = PyUnicode_FromObject(sep_in);
12730 if (!sep_obj) {
12731 Py_DECREF(str_obj);
12732 return NULL;
12733 }
12734
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012735 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012736 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012737 len1 = PyUnicode_GET_LENGTH(str_obj);
12738 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012739 if (kind1 < kind2 || len1 < len2) {
12740 _Py_INCREF_UNICODE_EMPTY();
12741 if (!unicode_empty)
12742 out = NULL;
12743 else {
12744 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
12745 Py_DECREF(unicode_empty);
12746 }
12747 Py_DECREF(sep_obj);
12748 Py_DECREF(str_obj);
12749 return out;
12750 }
12751 buf1 = PyUnicode_DATA(str_obj);
12752 buf2 = PyUnicode_DATA(sep_obj);
12753 if (kind2 != kind1) {
12754 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12755 if (!buf2)
12756 goto onError;
12757 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012758
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012759 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012760 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012761 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12762 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12763 else
12764 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012765 break;
12766 case PyUnicode_2BYTE_KIND:
12767 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12768 break;
12769 case PyUnicode_4BYTE_KIND:
12770 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12771 break;
12772 default:
12773 assert(0);
12774 out = 0;
12775 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012776
12777 Py_DECREF(sep_obj);
12778 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012779 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012780 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012781
12782 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012783 onError:
12784 Py_DECREF(sep_obj);
12785 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012786 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012787 PyMem_Free(buf2);
12788 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012789}
12790
12791PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012792 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012793\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012794Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012795the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012796found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012797
12798static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012799unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012800{
Victor Stinner9310abb2011-10-05 00:59:23 +020012801 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012802}
12803
12804PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012805 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012806\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012807Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012808the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012809separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012810
12811static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012812unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012813{
Victor Stinner9310abb2011-10-05 00:59:23 +020012814 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012815}
12816
Alexander Belopolsky40018472011-02-26 01:02:56 +000012817PyObject *
12818PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012819{
12820 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012821
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012822 s = PyUnicode_FromObject(s);
12823 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012824 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012825 if (sep != NULL) {
12826 sep = PyUnicode_FromObject(sep);
12827 if (sep == NULL) {
12828 Py_DECREF(s);
12829 return NULL;
12830 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012831 }
12832
Victor Stinner9310abb2011-10-05 00:59:23 +020012833 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012834
12835 Py_DECREF(s);
12836 Py_XDECREF(sep);
12837 return result;
12838}
12839
12840PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012841 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012842\n\
12843Return a list of the words in S, using sep as the\n\
12844delimiter string, starting at the end of the string and\n\
12845working to the front. If maxsplit is given, at most maxsplit\n\
12846splits are done. If sep is not specified, any whitespace string\n\
12847is a separator.");
12848
12849static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012850unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012851{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012852 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012853 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012854 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012855
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012856 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12857 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012858 return NULL;
12859
12860 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012861 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012862 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012863 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012864 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012865 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012866}
12867
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012868PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012869 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012870\n\
12871Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012872Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012873is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012874
12875static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012876unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012877{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012878 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012879 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012880
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012881 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12882 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012883 return NULL;
12884
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012885 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012886}
12887
12888static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012889PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012890{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012891 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012892}
12893
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012894PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012895 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012896\n\
12897Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012898and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012899
12900static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012901unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012902{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012903 if (PyUnicode_READY(self) == -1)
12904 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012905 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012906}
12907
Larry Hastings61272b72014-01-07 12:41:53 -080012908/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000012909
Larry Hastings31826802013-10-19 00:09:25 -070012910@staticmethod
12911str.maketrans as unicode_maketrans
12912
12913 x: object
12914
12915 y: unicode=NULL
12916
12917 z: unicode=NULL
12918
12919 /
12920
12921Return a translation table usable for str.translate().
12922
12923If there is only one argument, it must be a dictionary mapping Unicode
12924ordinals (integers) or characters to Unicode ordinals, strings or None.
12925Character keys will be then converted to ordinals.
12926If there are two arguments, they must be strings of equal length, and
12927in the resulting dictionary, each character in x will be mapped to the
12928character at the same position in y. If there is a third argument, it
12929must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080012930[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070012931
Larry Hastings31826802013-10-19 00:09:25 -070012932static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080012933unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030012934/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070012935{
Georg Brandlceee0772007-11-27 23:48:05 +000012936 PyObject *new = NULL, *key, *value;
12937 Py_ssize_t i = 0;
12938 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012939
Georg Brandlceee0772007-11-27 23:48:05 +000012940 new = PyDict_New();
12941 if (!new)
12942 return NULL;
12943 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012944 int x_kind, y_kind, z_kind;
12945 void *x_data, *y_data, *z_data;
12946
Georg Brandlceee0772007-11-27 23:48:05 +000012947 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012948 if (!PyUnicode_Check(x)) {
12949 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12950 "be a string if there is a second argument");
12951 goto err;
12952 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012953 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012954 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12955 "arguments must have equal length");
12956 goto err;
12957 }
12958 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012959 x_kind = PyUnicode_KIND(x);
12960 y_kind = PyUnicode_KIND(y);
12961 x_data = PyUnicode_DATA(x);
12962 y_data = PyUnicode_DATA(y);
12963 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12964 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012965 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000012966 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060012967 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060012968 if (!value) {
12969 Py_DECREF(key);
12970 goto err;
12971 }
Georg Brandlceee0772007-11-27 23:48:05 +000012972 res = PyDict_SetItem(new, key, value);
12973 Py_DECREF(key);
12974 Py_DECREF(value);
12975 if (res < 0)
12976 goto err;
12977 }
12978 /* create entries for deleting chars in z */
12979 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012980 z_kind = PyUnicode_KIND(z);
12981 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012982 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012983 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012984 if (!key)
12985 goto err;
12986 res = PyDict_SetItem(new, key, Py_None);
12987 Py_DECREF(key);
12988 if (res < 0)
12989 goto err;
12990 }
12991 }
12992 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012993 int kind;
12994 void *data;
12995
Georg Brandlceee0772007-11-27 23:48:05 +000012996 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012997 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012998 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12999 "to maketrans it must be a dict");
13000 goto err;
13001 }
13002 /* copy entries into the new dict, converting string keys to int keys */
13003 while (PyDict_Next(x, &i, &key, &value)) {
13004 if (PyUnicode_Check(key)) {
13005 /* convert string keys to integer keys */
13006 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013007 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013008 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13009 "table must be of length 1");
13010 goto err;
13011 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013012 kind = PyUnicode_KIND(key);
13013 data = PyUnicode_DATA(key);
13014 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013015 if (!newkey)
13016 goto err;
13017 res = PyDict_SetItem(new, newkey, value);
13018 Py_DECREF(newkey);
13019 if (res < 0)
13020 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013021 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013022 /* just keep integer keys */
13023 if (PyDict_SetItem(new, key, value) < 0)
13024 goto err;
13025 } else {
13026 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13027 "be strings or integers");
13028 goto err;
13029 }
13030 }
13031 }
13032 return new;
13033 err:
13034 Py_DECREF(new);
13035 return NULL;
13036}
13037
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013038PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013039 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013040\n\
Zachary Ware79b98df2015-08-05 23:54:15 -050013041Return a copy of the string S in which each character has been mapped\n\
13042through the given translation table. The table must implement\n\
13043lookup/indexing via __getitem__, for instance a dictionary or list,\n\
13044mapping Unicode ordinals to Unicode ordinals, strings, or None. If\n\
13045this operation raises LookupError, the character is left untouched.\n\
13046Characters mapped to None are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013047
13048static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013049unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013050{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013051 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013052}
13053
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013054PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013055 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013056\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013057Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013058
13059static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013060unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013061{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013062 if (PyUnicode_READY(self) == -1)
13063 return NULL;
13064 if (PyUnicode_IS_ASCII(self))
13065 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013066 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013067}
13068
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013069PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013070 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013071\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000013072Pad a numeric string S with zeros on the left, to fill a field\n\
13073of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013074
13075static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020013076unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013077{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013078 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013079 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013080 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013081 int kind;
13082 void *data;
13083 Py_UCS4 chr;
13084
Martin v. Löwis18e16552006-02-15 17:27:45 +000013085 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013086 return NULL;
13087
Benjamin Petersonbac79492012-01-14 13:34:47 -050013088 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013089 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013090
Victor Stinnerc4b49542011-12-11 22:44:26 +010013091 if (PyUnicode_GET_LENGTH(self) >= width)
13092 return unicode_result_unchanged(self);
13093
13094 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013095
13096 u = pad(self, fill, 0, '0');
13097
Walter Dörwald068325e2002-04-15 13:36:47 +000013098 if (u == NULL)
13099 return NULL;
13100
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013101 kind = PyUnicode_KIND(u);
13102 data = PyUnicode_DATA(u);
13103 chr = PyUnicode_READ(kind, data, fill);
13104
13105 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013106 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013107 PyUnicode_WRITE(kind, data, 0, chr);
13108 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013109 }
13110
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013111 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013112 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013113}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013114
13115#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013116static PyObject *
13117unicode__decimal2ascii(PyObject *self)
13118{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013119 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013120}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013121#endif
13122
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013123PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013124 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013125\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013126Return True if S starts with the specified prefix, False otherwise.\n\
13127With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013128With optional end, stop comparing S at that position.\n\
13129prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013130
13131static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013132unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013133 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013134{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013135 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013136 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013137 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013138 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013139 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013140
Jesus Ceaac451502011-04-20 17:09:23 +020013141 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013142 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013143 if (PyTuple_Check(subobj)) {
13144 Py_ssize_t i;
13145 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013146 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013147 if (substring == NULL)
13148 return NULL;
13149 result = tailmatch(self, substring, start, end, -1);
13150 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013151 if (result == -1)
13152 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013153 if (result) {
13154 Py_RETURN_TRUE;
13155 }
13156 }
13157 /* nothing matched */
13158 Py_RETURN_FALSE;
13159 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013160 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013161 if (substring == NULL) {
13162 if (PyErr_ExceptionMatches(PyExc_TypeError))
13163 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
13164 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013165 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013166 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013167 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013168 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013169 if (result == -1)
13170 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013171 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013172}
13173
13174
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013175PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013176 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013177\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013178Return True if S ends with the specified suffix, False otherwise.\n\
13179With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013180With optional end, stop comparing S at that position.\n\
13181suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013182
13183static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013184unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013185 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013186{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013187 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013188 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013189 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013190 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013191 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013192
Jesus Ceaac451502011-04-20 17:09:23 +020013193 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013194 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013195 if (PyTuple_Check(subobj)) {
13196 Py_ssize_t i;
13197 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013198 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000013199 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013200 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013201 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013202 result = tailmatch(self, substring, start, end, +1);
13203 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013204 if (result == -1)
13205 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013206 if (result) {
13207 Py_RETURN_TRUE;
13208 }
13209 }
13210 Py_RETURN_FALSE;
13211 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013212 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013213 if (substring == NULL) {
13214 if (PyErr_ExceptionMatches(PyExc_TypeError))
13215 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
13216 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013217 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013218 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013219 result = tailmatch(self, substring, start, end, +1);
Christian Heimes305e49e2013-06-29 20:41:06 +020013220 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013221 if (result == -1)
13222 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013223 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013224}
13225
Victor Stinner202fdca2012-05-07 12:47:02 +020013226Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013227_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013228{
Victor Stinner8f674cc2013-04-17 23:02:17 +020013229 if (!writer->readonly)
13230 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
13231 else {
13232 /* Copy-on-write mode: set buffer size to 0 so
13233 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13234 * next write. */
13235 writer->size = 0;
13236 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013237 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13238 writer->data = PyUnicode_DATA(writer->buffer);
13239 writer->kind = PyUnicode_KIND(writer->buffer);
13240}
13241
Victor Stinnerd3f08822012-05-29 12:57:52 +020013242void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013243_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013244{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013245 memset(writer, 0, sizeof(*writer));
13246#ifdef Py_DEBUG
13247 writer->kind = 5; /* invalid kind */
13248#endif
Victor Stinner8f674cc2013-04-17 23:02:17 +020013249 writer->min_char = 127;
Victor Stinner202fdca2012-05-07 12:47:02 +020013250}
13251
Victor Stinnerd3f08822012-05-29 12:57:52 +020013252int
13253_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13254 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013255{
Victor Stinner6989ba02013-11-18 21:08:39 +010013256#ifdef MS_WINDOWS
13257 /* On Windows, overallocate by 50% is the best factor */
13258# define OVERALLOCATE_FACTOR 2
13259#else
13260 /* On Linux, overallocate by 25% is the best factor */
13261# define OVERALLOCATE_FACTOR 4
13262#endif
Victor Stinner202fdca2012-05-07 12:47:02 +020013263 Py_ssize_t newlen;
13264 PyObject *newbuffer;
13265
Victor Stinnerd3f08822012-05-29 12:57:52 +020013266 assert(length > 0);
13267
Victor Stinner202fdca2012-05-07 12:47:02 +020013268 if (length > PY_SSIZE_T_MAX - writer->pos) {
13269 PyErr_NoMemory();
13270 return -1;
13271 }
13272 newlen = writer->pos + length;
13273
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013274 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013275
Victor Stinnerd3f08822012-05-29 12:57:52 +020013276 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013277 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013278 if (writer->overallocate
13279 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13280 /* overallocate to limit the number of realloc() */
13281 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013282 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013283 if (newlen < writer->min_length)
13284 newlen = writer->min_length;
13285
Victor Stinnerd3f08822012-05-29 12:57:52 +020013286 writer->buffer = PyUnicode_New(newlen, maxchar);
13287 if (writer->buffer == NULL)
13288 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013289 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013290 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013291 if (writer->overallocate
13292 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13293 /* overallocate to limit the number of realloc() */
13294 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013295 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013296 if (newlen < writer->min_length)
13297 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013298
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013299 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013300 /* resize + widen */
13301 newbuffer = PyUnicode_New(newlen, maxchar);
13302 if (newbuffer == NULL)
13303 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013304 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13305 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013306 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013307 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013308 }
13309 else {
13310 newbuffer = resize_compact(writer->buffer, newlen);
13311 if (newbuffer == NULL)
13312 return -1;
13313 }
13314 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013315 }
13316 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013317 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013318 newbuffer = PyUnicode_New(writer->size, maxchar);
13319 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013320 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013321 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13322 writer->buffer, 0, writer->pos);
13323 Py_DECREF(writer->buffer);
13324 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013325 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013326 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013327 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013328
13329#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013330}
13331
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013332Py_LOCAL_INLINE(int)
13333_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013334{
13335 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13336 return -1;
13337 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13338 writer->pos++;
13339 return 0;
13340}
13341
13342int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013343_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13344{
13345 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13346}
13347
13348int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013349_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13350{
13351 Py_UCS4 maxchar;
13352 Py_ssize_t len;
13353
13354 if (PyUnicode_READY(str) == -1)
13355 return -1;
13356 len = PyUnicode_GET_LENGTH(str);
13357 if (len == 0)
13358 return 0;
13359 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13360 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013361 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013362 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013363 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013364 Py_INCREF(str);
13365 writer->buffer = str;
13366 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013367 writer->pos += len;
13368 return 0;
13369 }
13370 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13371 return -1;
13372 }
13373 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13374 str, 0, len);
13375 writer->pos += len;
13376 return 0;
13377}
13378
Victor Stinnere215d962012-10-06 23:03:36 +020013379int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013380_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13381 Py_ssize_t start, Py_ssize_t end)
13382{
13383 Py_UCS4 maxchar;
13384 Py_ssize_t len;
13385
13386 if (PyUnicode_READY(str) == -1)
13387 return -1;
13388
13389 assert(0 <= start);
13390 assert(end <= PyUnicode_GET_LENGTH(str));
13391 assert(start <= end);
13392
13393 if (end == 0)
13394 return 0;
13395
13396 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13397 return _PyUnicodeWriter_WriteStr(writer, str);
13398
13399 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13400 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13401 else
13402 maxchar = writer->maxchar;
13403 len = end - start;
13404
13405 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13406 return -1;
13407
13408 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13409 str, start, len);
13410 writer->pos += len;
13411 return 0;
13412}
13413
13414int
Victor Stinner4a587072013-11-19 12:54:53 +010013415_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13416 const char *ascii, Py_ssize_t len)
13417{
13418 if (len == -1)
13419 len = strlen(ascii);
13420
13421 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13422
13423 if (writer->buffer == NULL && !writer->overallocate) {
13424 PyObject *str;
13425
13426 str = _PyUnicode_FromASCII(ascii, len);
13427 if (str == NULL)
13428 return -1;
13429
13430 writer->readonly = 1;
13431 writer->buffer = str;
13432 _PyUnicodeWriter_Update(writer);
13433 writer->pos += len;
13434 return 0;
13435 }
13436
13437 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13438 return -1;
13439
13440 switch (writer->kind)
13441 {
13442 case PyUnicode_1BYTE_KIND:
13443 {
13444 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13445 Py_UCS1 *data = writer->data;
13446
13447 Py_MEMCPY(data + writer->pos, str, len);
13448 break;
13449 }
13450 case PyUnicode_2BYTE_KIND:
13451 {
13452 _PyUnicode_CONVERT_BYTES(
13453 Py_UCS1, Py_UCS2,
13454 ascii, ascii + len,
13455 (Py_UCS2 *)writer->data + writer->pos);
13456 break;
13457 }
13458 case PyUnicode_4BYTE_KIND:
13459 {
13460 _PyUnicode_CONVERT_BYTES(
13461 Py_UCS1, Py_UCS4,
13462 ascii, ascii + len,
13463 (Py_UCS4 *)writer->data + writer->pos);
13464 break;
13465 }
13466 default:
13467 assert(0);
13468 }
13469
13470 writer->pos += len;
13471 return 0;
13472}
13473
13474int
13475_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13476 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013477{
13478 Py_UCS4 maxchar;
13479
13480 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13481 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13482 return -1;
13483 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13484 writer->pos += len;
13485 return 0;
13486}
13487
Victor Stinnerd3f08822012-05-29 12:57:52 +020013488PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013489_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013490{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013491 PyObject *str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013492 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013493 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013494 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013495 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013496 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013497 str = writer->buffer;
13498 writer->buffer = NULL;
13499 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13500 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013501 }
13502 if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
13503 PyObject *newbuffer;
13504 newbuffer = resize_compact(writer->buffer, writer->pos);
13505 if (newbuffer == NULL) {
Serhiy Storchakadfe98a12014-02-09 13:46:20 +020013506 Py_CLEAR(writer->buffer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013507 return NULL;
13508 }
13509 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013510 }
Victor Stinner15a0bd32013-07-08 22:29:55 +020013511 str = writer->buffer;
13512 writer->buffer = NULL;
13513 assert(_PyUnicode_CheckConsistency(str, 1));
13514 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013515}
13516
Victor Stinnerd3f08822012-05-29 12:57:52 +020013517void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013518_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013519{
13520 Py_CLEAR(writer->buffer);
13521}
13522
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013523#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013524
13525PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013526 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013527\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013528Return a formatted version of S, using substitutions from args and kwargs.\n\
13529The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013530
Eric Smith27bbca62010-11-04 17:06:58 +000013531PyDoc_STRVAR(format_map__doc__,
13532 "S.format_map(mapping) -> str\n\
13533\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013534Return a formatted version of S, using substitutions from mapping.\n\
13535The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013536
Eric Smith4a7d76d2008-05-30 18:10:19 +000013537static PyObject *
13538unicode__format__(PyObject* self, PyObject* args)
13539{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013540 PyObject *format_spec;
13541 _PyUnicodeWriter writer;
13542 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013543
13544 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13545 return NULL;
13546
Victor Stinnerd3f08822012-05-29 12:57:52 +020013547 if (PyUnicode_READY(self) == -1)
13548 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013549 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013550 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13551 self, format_spec, 0,
13552 PyUnicode_GET_LENGTH(format_spec));
13553 if (ret == -1) {
13554 _PyUnicodeWriter_Dealloc(&writer);
13555 return NULL;
13556 }
13557 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013558}
13559
Eric Smith8c663262007-08-25 02:26:07 +000013560PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013561 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013562\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013563Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013564
13565static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013566unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013567{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013568 Py_ssize_t size;
13569
13570 /* If it's a compact object, account for base structure +
13571 character data. */
13572 if (PyUnicode_IS_COMPACT_ASCII(v))
13573 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13574 else if (PyUnicode_IS_COMPACT(v))
13575 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013576 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013577 else {
13578 /* If it is a two-block object, account for base object, and
13579 for character block if present. */
13580 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013581 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013582 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013583 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013584 }
13585 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013586 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013587 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013588 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013589 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013590 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013591
13592 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013593}
13594
13595PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013596 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013597
13598static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013599unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013600{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013601 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013602 if (!copy)
13603 return NULL;
13604 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013605}
13606
Guido van Rossumd57fd912000-03-10 22:53:23 +000013607static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013608 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013609 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013610 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13611 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013612 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13613 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013614 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013615 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13616 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13617 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013618 {"expandtabs", (PyCFunction) unicode_expandtabs,
13619 METH_VARARGS | METH_KEYWORDS, expandtabs__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013620 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013621 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013622 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13623 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13624 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013625 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013626 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13627 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13628 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013629 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013630 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013631 {"splitlines", (PyCFunction) unicode_splitlines,
13632 METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013633 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013634 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13635 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13636 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13637 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13638 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13639 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13640 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13641 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13642 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13643 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13644 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13645 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13646 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13647 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013648 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013649 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013650 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013651 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013652 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013653 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013654 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013655 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013656#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013657 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013658 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013659#endif
13660
Benjamin Peterson14339b62009-01-31 16:36:08 +000013661 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013662 {NULL, NULL}
13663};
13664
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013665static PyObject *
13666unicode_mod(PyObject *v, PyObject *w)
13667{
Brian Curtindfc80e32011-08-10 20:28:54 -050013668 if (!PyUnicode_Check(v))
13669 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013670 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013671}
13672
13673static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013674 0, /*nb_add*/
13675 0, /*nb_subtract*/
13676 0, /*nb_multiply*/
13677 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013678};
13679
Guido van Rossumd57fd912000-03-10 22:53:23 +000013680static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013681 (lenfunc) unicode_length, /* sq_length */
13682 PyUnicode_Concat, /* sq_concat */
13683 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13684 (ssizeargfunc) unicode_getitem, /* sq_item */
13685 0, /* sq_slice */
13686 0, /* sq_ass_item */
13687 0, /* sq_ass_slice */
13688 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013689};
13690
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013691static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013692unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013693{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013694 if (PyUnicode_READY(self) == -1)
13695 return NULL;
13696
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013697 if (PyIndex_Check(item)) {
13698 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013699 if (i == -1 && PyErr_Occurred())
13700 return NULL;
13701 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013702 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013703 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013704 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013705 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013706 PyObject *result;
13707 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013708 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013709 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013710
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013711 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013712 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013713 return NULL;
13714 }
13715
13716 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013717 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013718 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013719 slicelength == PyUnicode_GET_LENGTH(self)) {
13720 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013721 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013722 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013723 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013724 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013725 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013726 src_kind = PyUnicode_KIND(self);
13727 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013728 if (!PyUnicode_IS_ASCII(self)) {
13729 kind_limit = kind_maxchar_limit(src_kind);
13730 max_char = 0;
13731 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13732 ch = PyUnicode_READ(src_kind, src_data, cur);
13733 if (ch > max_char) {
13734 max_char = ch;
13735 if (max_char >= kind_limit)
13736 break;
13737 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013738 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013739 }
Victor Stinner55c99112011-10-13 01:17:06 +020013740 else
13741 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013742 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013743 if (result == NULL)
13744 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013745 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013746 dest_data = PyUnicode_DATA(result);
13747
13748 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013749 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13750 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013751 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013752 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013753 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013754 } else {
13755 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13756 return NULL;
13757 }
13758}
13759
13760static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013761 (lenfunc)unicode_length, /* mp_length */
13762 (binaryfunc)unicode_subscript, /* mp_subscript */
13763 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013764};
13765
Guido van Rossumd57fd912000-03-10 22:53:23 +000013766
Guido van Rossumd57fd912000-03-10 22:53:23 +000013767/* Helpers for PyUnicode_Format() */
13768
Victor Stinnera47082312012-10-04 02:19:54 +020013769struct unicode_formatter_t {
13770 PyObject *args;
13771 int args_owned;
13772 Py_ssize_t arglen, argidx;
13773 PyObject *dict;
13774
13775 enum PyUnicode_Kind fmtkind;
13776 Py_ssize_t fmtcnt, fmtpos;
13777 void *fmtdata;
13778 PyObject *fmtstr;
13779
13780 _PyUnicodeWriter writer;
13781};
13782
13783struct unicode_format_arg_t {
13784 Py_UCS4 ch;
13785 int flags;
13786 Py_ssize_t width;
13787 int prec;
13788 int sign;
13789};
13790
Guido van Rossumd57fd912000-03-10 22:53:23 +000013791static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013792unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013793{
Victor Stinnera47082312012-10-04 02:19:54 +020013794 Py_ssize_t argidx = ctx->argidx;
13795
13796 if (argidx < ctx->arglen) {
13797 ctx->argidx++;
13798 if (ctx->arglen < 0)
13799 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013800 else
Victor Stinnera47082312012-10-04 02:19:54 +020013801 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013802 }
13803 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013804 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013805 return NULL;
13806}
13807
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013808/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013809
Victor Stinnera47082312012-10-04 02:19:54 +020013810/* Format a float into the writer if the writer is not NULL, or into *p_output
13811 otherwise.
13812
13813 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020013814static int
Victor Stinnera47082312012-10-04 02:19:54 +020013815formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
13816 PyObject **p_output,
13817 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013818{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013819 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013820 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013821 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020013822 int prec;
13823 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000013824
Guido van Rossumd57fd912000-03-10 22:53:23 +000013825 x = PyFloat_AsDouble(v);
13826 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013827 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013828
Victor Stinnera47082312012-10-04 02:19:54 +020013829 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013830 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013831 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013832
Victor Stinnera47082312012-10-04 02:19:54 +020013833 if (arg->flags & F_ALT)
13834 dtoa_flags = Py_DTSF_ALT;
13835 else
13836 dtoa_flags = 0;
13837 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013838 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013839 return -1;
13840 len = strlen(p);
13841 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010013842 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013843 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013844 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013845 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013846 }
13847 else
13848 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013849 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013850 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013851}
13852
Victor Stinnerd0880d52012-04-27 23:40:13 +020013853/* formatlong() emulates the format codes d, u, o, x and X, and
13854 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13855 * Python's regular ints.
13856 * Return value: a new PyUnicodeObject*, or NULL if error.
13857 * The output string is of the form
13858 * "-"? ("0x" | "0X")? digit+
13859 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13860 * set in flags. The case of hex digits will be correct,
13861 * There will be at least prec digits, zero-filled on the left if
13862 * necessary to get that many.
13863 * val object to be converted
13864 * flags bitmask of format flags; only F_ALT is looked at
13865 * prec minimum number of digits; 0-fill on left if needed
13866 * type a character in [duoxX]; u acts the same as d
13867 *
13868 * CAUTION: o, x and X conversions on regular ints can never
13869 * produce a '-' sign, but can for Python's unbounded ints.
13870 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080013871PyObject *
13872_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000013873{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013874 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013875 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013876 Py_ssize_t i;
13877 int sign; /* 1 if '-', else 0 */
13878 int len; /* number of characters */
13879 Py_ssize_t llen;
13880 int numdigits; /* len == numnondigits + numdigits */
13881 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000013882
Victor Stinnerd0880d52012-04-27 23:40:13 +020013883 /* Avoid exceeding SSIZE_T_MAX */
13884 if (prec > INT_MAX-3) {
13885 PyErr_SetString(PyExc_OverflowError,
13886 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013887 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013888 }
13889
13890 assert(PyLong_Check(val));
13891
13892 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020013893 default:
13894 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013895 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020013896 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020013897 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070013898 /* int and int subclasses should print numerically when a numeric */
13899 /* format code is used (see issue18780) */
13900 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013901 break;
13902 case 'o':
13903 numnondigits = 2;
13904 result = PyNumber_ToBase(val, 8);
13905 break;
13906 case 'x':
13907 case 'X':
13908 numnondigits = 2;
13909 result = PyNumber_ToBase(val, 16);
13910 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013911 }
13912 if (!result)
13913 return NULL;
13914
13915 assert(unicode_modifiable(result));
13916 assert(PyUnicode_IS_READY(result));
13917 assert(PyUnicode_IS_ASCII(result));
13918
13919 /* To modify the string in-place, there can only be one reference. */
13920 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013921 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013922 PyErr_BadInternalCall();
13923 return NULL;
13924 }
13925 buf = PyUnicode_DATA(result);
13926 llen = PyUnicode_GET_LENGTH(result);
13927 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013928 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013929 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080013930 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013931 return NULL;
13932 }
13933 len = (int)llen;
13934 sign = buf[0] == '-';
13935 numnondigits += sign;
13936 numdigits = len - numnondigits;
13937 assert(numdigits > 0);
13938
13939 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080013940 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020013941 (type == 'o' || type == 'x' || type == 'X'))) {
13942 assert(buf[sign] == '0');
13943 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
13944 buf[sign+1] == 'o');
13945 numnondigits -= 2;
13946 buf += 2;
13947 len -= 2;
13948 if (sign)
13949 buf[0] = '-';
13950 assert(len == numnondigits + numdigits);
13951 assert(numdigits > 0);
13952 }
13953
13954 /* Fill with leading zeroes to meet minimum width. */
13955 if (prec > numdigits) {
13956 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
13957 numnondigits + prec);
13958 char *b1;
13959 if (!r1) {
13960 Py_DECREF(result);
13961 return NULL;
13962 }
13963 b1 = PyBytes_AS_STRING(r1);
13964 for (i = 0; i < numnondigits; ++i)
13965 *b1++ = *buf++;
13966 for (i = 0; i < prec - numdigits; i++)
13967 *b1++ = '0';
13968 for (i = 0; i < numdigits; i++)
13969 *b1++ = *buf++;
13970 *b1 = '\0';
13971 Py_DECREF(result);
13972 result = r1;
13973 buf = PyBytes_AS_STRING(result);
13974 len = numnondigits + prec;
13975 }
13976
13977 /* Fix up case for hex conversions. */
13978 if (type == 'X') {
13979 /* Need to convert all lower case letters to upper case.
13980 and need to convert 0x to 0X (and -0x to -0X). */
13981 for (i = 0; i < len; i++)
13982 if (buf[i] >= 'a' && buf[i] <= 'x')
13983 buf[i] -= 'a'-'A';
13984 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020013985 if (!PyUnicode_Check(result)
13986 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020013987 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013988 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013989 Py_DECREF(result);
13990 result = unicode;
13991 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020013992 else if (len != PyUnicode_GET_LENGTH(result)) {
13993 if (PyUnicode_Resize(&result, len) < 0)
13994 Py_CLEAR(result);
13995 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000013996 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013997}
13998
Ethan Furmandf3ed242014-01-05 06:50:30 -080013999/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014000 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014001 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014002 * -1 and raise an exception on error */
14003static int
Victor Stinnera47082312012-10-04 02:19:54 +020014004mainformatlong(PyObject *v,
14005 struct unicode_format_arg_t *arg,
14006 PyObject **p_output,
14007 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014008{
14009 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014010 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014011
14012 if (!PyNumber_Check(v))
14013 goto wrongtype;
14014
Ethan Furman9ab74802014-03-21 06:38:46 -070014015 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014016 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014017 if (type == 'o' || type == 'x' || type == 'X') {
14018 iobj = PyNumber_Index(v);
14019 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014020 if (PyErr_ExceptionMatches(PyExc_TypeError))
14021 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014022 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014023 }
14024 }
14025 else {
14026 iobj = PyNumber_Long(v);
14027 if (iobj == NULL ) {
14028 if (PyErr_ExceptionMatches(PyExc_TypeError))
14029 goto wrongtype;
14030 return -1;
14031 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014032 }
14033 assert(PyLong_Check(iobj));
14034 }
14035 else {
14036 iobj = v;
14037 Py_INCREF(iobj);
14038 }
14039
14040 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014041 && arg->width == -1 && arg->prec == -1
14042 && !(arg->flags & (F_SIGN | F_BLANK))
14043 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014044 {
14045 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014046 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014047 int base;
14048
Victor Stinnera47082312012-10-04 02:19:54 +020014049 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014050 {
14051 default:
14052 assert(0 && "'type' not in [diuoxX]");
14053 case 'd':
14054 case 'i':
14055 case 'u':
14056 base = 10;
14057 break;
14058 case 'o':
14059 base = 8;
14060 break;
14061 case 'x':
14062 case 'X':
14063 base = 16;
14064 break;
14065 }
14066
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014067 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14068 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014069 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014070 }
14071 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014072 return 1;
14073 }
14074
Ethan Furmanb95b5612015-01-23 20:05:18 -080014075 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014076 Py_DECREF(iobj);
14077 if (res == NULL)
14078 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014079 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014080 return 0;
14081
14082wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014083 switch(type)
14084 {
14085 case 'o':
14086 case 'x':
14087 case 'X':
14088 PyErr_Format(PyExc_TypeError,
14089 "%%%c format: an integer is required, "
14090 "not %.200s",
14091 type, Py_TYPE(v)->tp_name);
14092 break;
14093 default:
14094 PyErr_Format(PyExc_TypeError,
14095 "%%%c format: a number is required, "
14096 "not %.200s",
14097 type, Py_TYPE(v)->tp_name);
14098 break;
14099 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014100 return -1;
14101}
14102
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014103static Py_UCS4
14104formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014105{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014106 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014107 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014108 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014109 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014110 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014111 goto onError;
14112 }
14113 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014114 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014115 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014116 /* make sure number is a type of integer */
14117 if (!PyLong_Check(v)) {
14118 iobj = PyNumber_Index(v);
14119 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014120 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014121 }
14122 v = iobj;
14123 Py_DECREF(iobj);
14124 }
14125 /* Integer input truncated to a character */
Benjamin Peterson29060642009-01-31 22:14:21 +000014126 x = PyLong_AsLong(v);
14127 if (x == -1 && PyErr_Occurred())
14128 goto onError;
14129
Victor Stinner8faf8212011-12-08 22:14:11 +010014130 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014131 PyErr_SetString(PyExc_OverflowError,
14132 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014133 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014134 }
14135
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014136 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014137 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014138
Benjamin Peterson29060642009-01-31 22:14:21 +000014139 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014140 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014141 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014142 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014143}
14144
Victor Stinnera47082312012-10-04 02:19:54 +020014145/* Parse options of an argument: flags, width, precision.
14146 Handle also "%(name)" syntax.
14147
14148 Return 0 if the argument has been formatted into arg->str.
14149 Return 1 if the argument has been written into ctx->writer,
14150 Raise an exception and return -1 on error. */
14151static int
14152unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14153 struct unicode_format_arg_t *arg)
14154{
14155#define FORMAT_READ(ctx) \
14156 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14157
14158 PyObject *v;
14159
Victor Stinnera47082312012-10-04 02:19:54 +020014160 if (arg->ch == '(') {
14161 /* Get argument value from a dictionary. Example: "%(name)s". */
14162 Py_ssize_t keystart;
14163 Py_ssize_t keylen;
14164 PyObject *key;
14165 int pcount = 1;
14166
14167 if (ctx->dict == NULL) {
14168 PyErr_SetString(PyExc_TypeError,
14169 "format requires a mapping");
14170 return -1;
14171 }
14172 ++ctx->fmtpos;
14173 --ctx->fmtcnt;
14174 keystart = ctx->fmtpos;
14175 /* Skip over balanced parentheses */
14176 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14177 arg->ch = FORMAT_READ(ctx);
14178 if (arg->ch == ')')
14179 --pcount;
14180 else if (arg->ch == '(')
14181 ++pcount;
14182 ctx->fmtpos++;
14183 }
14184 keylen = ctx->fmtpos - keystart - 1;
14185 if (ctx->fmtcnt < 0 || pcount > 0) {
14186 PyErr_SetString(PyExc_ValueError,
14187 "incomplete format key");
14188 return -1;
14189 }
14190 key = PyUnicode_Substring(ctx->fmtstr,
14191 keystart, keystart + keylen);
14192 if (key == NULL)
14193 return -1;
14194 if (ctx->args_owned) {
14195 Py_DECREF(ctx->args);
14196 ctx->args_owned = 0;
14197 }
14198 ctx->args = PyObject_GetItem(ctx->dict, key);
14199 Py_DECREF(key);
14200 if (ctx->args == NULL)
14201 return -1;
14202 ctx->args_owned = 1;
14203 ctx->arglen = -1;
14204 ctx->argidx = -2;
14205 }
14206
14207 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014208 while (--ctx->fmtcnt >= 0) {
14209 arg->ch = FORMAT_READ(ctx);
14210 ctx->fmtpos++;
14211 switch (arg->ch) {
14212 case '-': arg->flags |= F_LJUST; continue;
14213 case '+': arg->flags |= F_SIGN; continue;
14214 case ' ': arg->flags |= F_BLANK; continue;
14215 case '#': arg->flags |= F_ALT; continue;
14216 case '0': arg->flags |= F_ZERO; continue;
14217 }
14218 break;
14219 }
14220
14221 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014222 if (arg->ch == '*') {
14223 v = unicode_format_getnextarg(ctx);
14224 if (v == NULL)
14225 return -1;
14226 if (!PyLong_Check(v)) {
14227 PyErr_SetString(PyExc_TypeError,
14228 "* wants int");
14229 return -1;
14230 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014231 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014232 if (arg->width == -1 && PyErr_Occurred())
14233 return -1;
14234 if (arg->width < 0) {
14235 arg->flags |= F_LJUST;
14236 arg->width = -arg->width;
14237 }
14238 if (--ctx->fmtcnt >= 0) {
14239 arg->ch = FORMAT_READ(ctx);
14240 ctx->fmtpos++;
14241 }
14242 }
14243 else if (arg->ch >= '0' && arg->ch <= '9') {
14244 arg->width = arg->ch - '0';
14245 while (--ctx->fmtcnt >= 0) {
14246 arg->ch = FORMAT_READ(ctx);
14247 ctx->fmtpos++;
14248 if (arg->ch < '0' || arg->ch > '9')
14249 break;
14250 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14251 mixing signed and unsigned comparison. Since arg->ch is between
14252 '0' and '9', casting to int is safe. */
14253 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14254 PyErr_SetString(PyExc_ValueError,
14255 "width too big");
14256 return -1;
14257 }
14258 arg->width = arg->width*10 + (arg->ch - '0');
14259 }
14260 }
14261
14262 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014263 if (arg->ch == '.') {
14264 arg->prec = 0;
14265 if (--ctx->fmtcnt >= 0) {
14266 arg->ch = FORMAT_READ(ctx);
14267 ctx->fmtpos++;
14268 }
14269 if (arg->ch == '*') {
14270 v = unicode_format_getnextarg(ctx);
14271 if (v == NULL)
14272 return -1;
14273 if (!PyLong_Check(v)) {
14274 PyErr_SetString(PyExc_TypeError,
14275 "* wants int");
14276 return -1;
14277 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014278 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014279 if (arg->prec == -1 && PyErr_Occurred())
14280 return -1;
14281 if (arg->prec < 0)
14282 arg->prec = 0;
14283 if (--ctx->fmtcnt >= 0) {
14284 arg->ch = FORMAT_READ(ctx);
14285 ctx->fmtpos++;
14286 }
14287 }
14288 else if (arg->ch >= '0' && arg->ch <= '9') {
14289 arg->prec = arg->ch - '0';
14290 while (--ctx->fmtcnt >= 0) {
14291 arg->ch = FORMAT_READ(ctx);
14292 ctx->fmtpos++;
14293 if (arg->ch < '0' || arg->ch > '9')
14294 break;
14295 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14296 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014297 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014298 return -1;
14299 }
14300 arg->prec = arg->prec*10 + (arg->ch - '0');
14301 }
14302 }
14303 }
14304
14305 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14306 if (ctx->fmtcnt >= 0) {
14307 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14308 if (--ctx->fmtcnt >= 0) {
14309 arg->ch = FORMAT_READ(ctx);
14310 ctx->fmtpos++;
14311 }
14312 }
14313 }
14314 if (ctx->fmtcnt < 0) {
14315 PyErr_SetString(PyExc_ValueError,
14316 "incomplete format");
14317 return -1;
14318 }
14319 return 0;
14320
14321#undef FORMAT_READ
14322}
14323
14324/* Format one argument. Supported conversion specifiers:
14325
14326 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014327 - "i", "d", "u": int or float
14328 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014329 - "e", "E", "f", "F", "g", "G": float
14330 - "c": int or str (1 character)
14331
Victor Stinner8dbd4212012-12-04 09:30:24 +010014332 When possible, the output is written directly into the Unicode writer
14333 (ctx->writer). A string is created when padding is required.
14334
Victor Stinnera47082312012-10-04 02:19:54 +020014335 Return 0 if the argument has been formatted into *p_str,
14336 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014337 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014338static int
14339unicode_format_arg_format(struct unicode_formatter_t *ctx,
14340 struct unicode_format_arg_t *arg,
14341 PyObject **p_str)
14342{
14343 PyObject *v;
14344 _PyUnicodeWriter *writer = &ctx->writer;
14345
14346 if (ctx->fmtcnt == 0)
14347 ctx->writer.overallocate = 0;
14348
14349 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014350 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014351 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014352 return 1;
14353 }
14354
14355 v = unicode_format_getnextarg(ctx);
14356 if (v == NULL)
14357 return -1;
14358
Victor Stinnera47082312012-10-04 02:19:54 +020014359
14360 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014361 case 's':
14362 case 'r':
14363 case 'a':
14364 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14365 /* Fast path */
14366 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14367 return -1;
14368 return 1;
14369 }
14370
14371 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14372 *p_str = v;
14373 Py_INCREF(*p_str);
14374 }
14375 else {
14376 if (arg->ch == 's')
14377 *p_str = PyObject_Str(v);
14378 else if (arg->ch == 'r')
14379 *p_str = PyObject_Repr(v);
14380 else
14381 *p_str = PyObject_ASCII(v);
14382 }
14383 break;
14384
14385 case 'i':
14386 case 'd':
14387 case 'u':
14388 case 'o':
14389 case 'x':
14390 case 'X':
14391 {
14392 int ret = mainformatlong(v, arg, p_str, writer);
14393 if (ret != 0)
14394 return ret;
14395 arg->sign = 1;
14396 break;
14397 }
14398
14399 case 'e':
14400 case 'E':
14401 case 'f':
14402 case 'F':
14403 case 'g':
14404 case 'G':
14405 if (arg->width == -1 && arg->prec == -1
14406 && !(arg->flags & (F_SIGN | F_BLANK)))
14407 {
14408 /* Fast path */
14409 if (formatfloat(v, arg, NULL, writer) == -1)
14410 return -1;
14411 return 1;
14412 }
14413
14414 arg->sign = 1;
14415 if (formatfloat(v, arg, p_str, NULL) == -1)
14416 return -1;
14417 break;
14418
14419 case 'c':
14420 {
14421 Py_UCS4 ch = formatchar(v);
14422 if (ch == (Py_UCS4) -1)
14423 return -1;
14424 if (arg->width == -1 && arg->prec == -1) {
14425 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014426 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014427 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014428 return 1;
14429 }
14430 *p_str = PyUnicode_FromOrdinal(ch);
14431 break;
14432 }
14433
14434 default:
14435 PyErr_Format(PyExc_ValueError,
14436 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014437 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014438 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14439 (int)arg->ch,
14440 ctx->fmtpos - 1);
14441 return -1;
14442 }
14443 if (*p_str == NULL)
14444 return -1;
14445 assert (PyUnicode_Check(*p_str));
14446 return 0;
14447}
14448
14449static int
14450unicode_format_arg_output(struct unicode_formatter_t *ctx,
14451 struct unicode_format_arg_t *arg,
14452 PyObject *str)
14453{
14454 Py_ssize_t len;
14455 enum PyUnicode_Kind kind;
14456 void *pbuf;
14457 Py_ssize_t pindex;
14458 Py_UCS4 signchar;
14459 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014460 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014461 Py_ssize_t sublen;
14462 _PyUnicodeWriter *writer = &ctx->writer;
14463 Py_UCS4 fill;
14464
14465 fill = ' ';
14466 if (arg->sign && arg->flags & F_ZERO)
14467 fill = '0';
14468
14469 if (PyUnicode_READY(str) == -1)
14470 return -1;
14471
14472 len = PyUnicode_GET_LENGTH(str);
14473 if ((arg->width == -1 || arg->width <= len)
14474 && (arg->prec == -1 || arg->prec >= len)
14475 && !(arg->flags & (F_SIGN | F_BLANK)))
14476 {
14477 /* Fast path */
14478 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14479 return -1;
14480 return 0;
14481 }
14482
14483 /* Truncate the string for "s", "r" and "a" formats
14484 if the precision is set */
14485 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14486 if (arg->prec >= 0 && len > arg->prec)
14487 len = arg->prec;
14488 }
14489
14490 /* Adjust sign and width */
14491 kind = PyUnicode_KIND(str);
14492 pbuf = PyUnicode_DATA(str);
14493 pindex = 0;
14494 signchar = '\0';
14495 if (arg->sign) {
14496 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14497 if (ch == '-' || ch == '+') {
14498 signchar = ch;
14499 len--;
14500 pindex++;
14501 }
14502 else if (arg->flags & F_SIGN)
14503 signchar = '+';
14504 else if (arg->flags & F_BLANK)
14505 signchar = ' ';
14506 else
14507 arg->sign = 0;
14508 }
14509 if (arg->width < len)
14510 arg->width = len;
14511
14512 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014513 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014514 if (!(arg->flags & F_LJUST)) {
14515 if (arg->sign) {
14516 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014517 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014518 }
14519 else {
14520 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014521 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014522 }
14523 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014524 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14525 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014526 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014527 }
14528
Victor Stinnera47082312012-10-04 02:19:54 +020014529 buflen = arg->width;
14530 if (arg->sign && len == arg->width)
14531 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014532 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014533 return -1;
14534
14535 /* Write the sign if needed */
14536 if (arg->sign) {
14537 if (fill != ' ') {
14538 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14539 writer->pos += 1;
14540 }
14541 if (arg->width > len)
14542 arg->width--;
14543 }
14544
14545 /* Write the numeric prefix for "x", "X" and "o" formats
14546 if the alternate form is used.
14547 For example, write "0x" for the "%#x" format. */
14548 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14549 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14550 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14551 if (fill != ' ') {
14552 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14553 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14554 writer->pos += 2;
14555 pindex += 2;
14556 }
14557 arg->width -= 2;
14558 if (arg->width < 0)
14559 arg->width = 0;
14560 len -= 2;
14561 }
14562
14563 /* Pad left with the fill character if needed */
14564 if (arg->width > len && !(arg->flags & F_LJUST)) {
14565 sublen = arg->width - len;
14566 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14567 writer->pos += sublen;
14568 arg->width = len;
14569 }
14570
14571 /* If padding with spaces: write sign if needed and/or numeric prefix if
14572 the alternate form is used */
14573 if (fill == ' ') {
14574 if (arg->sign) {
14575 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14576 writer->pos += 1;
14577 }
14578 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14579 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14580 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14581 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14582 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14583 writer->pos += 2;
14584 pindex += 2;
14585 }
14586 }
14587
14588 /* Write characters */
14589 if (len) {
14590 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14591 str, pindex, len);
14592 writer->pos += len;
14593 }
14594
14595 /* Pad right with the fill character if needed */
14596 if (arg->width > len) {
14597 sublen = arg->width - len;
14598 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14599 writer->pos += sublen;
14600 }
14601 return 0;
14602}
14603
14604/* Helper of PyUnicode_Format(): format one arg.
14605 Return 0 on success, raise an exception and return -1 on error. */
14606static int
14607unicode_format_arg(struct unicode_formatter_t *ctx)
14608{
14609 struct unicode_format_arg_t arg;
14610 PyObject *str;
14611 int ret;
14612
Victor Stinner8dbd4212012-12-04 09:30:24 +010014613 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14614 arg.flags = 0;
14615 arg.width = -1;
14616 arg.prec = -1;
14617 arg.sign = 0;
14618 str = NULL;
14619
Victor Stinnera47082312012-10-04 02:19:54 +020014620 ret = unicode_format_arg_parse(ctx, &arg);
14621 if (ret == -1)
14622 return -1;
14623
14624 ret = unicode_format_arg_format(ctx, &arg, &str);
14625 if (ret == -1)
14626 return -1;
14627
14628 if (ret != 1) {
14629 ret = unicode_format_arg_output(ctx, &arg, str);
14630 Py_DECREF(str);
14631 if (ret == -1)
14632 return -1;
14633 }
14634
14635 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14636 PyErr_SetString(PyExc_TypeError,
14637 "not all arguments converted during string formatting");
14638 return -1;
14639 }
14640 return 0;
14641}
14642
Alexander Belopolsky40018472011-02-26 01:02:56 +000014643PyObject *
14644PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014645{
Victor Stinnera47082312012-10-04 02:19:54 +020014646 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014647
Guido van Rossumd57fd912000-03-10 22:53:23 +000014648 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014649 PyErr_BadInternalCall();
14650 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014651 }
Victor Stinnera47082312012-10-04 02:19:54 +020014652
14653 ctx.fmtstr = PyUnicode_FromObject(format);
14654 if (ctx.fmtstr == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000014655 return NULL;
Victor Stinnera47082312012-10-04 02:19:54 +020014656 if (PyUnicode_READY(ctx.fmtstr) == -1) {
14657 Py_DECREF(ctx.fmtstr);
14658 return NULL;
14659 }
14660 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14661 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14662 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14663 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014664
Victor Stinner8f674cc2013-04-17 23:02:17 +020014665 _PyUnicodeWriter_Init(&ctx.writer);
14666 ctx.writer.min_length = ctx.fmtcnt + 100;
14667 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014668
Guido van Rossumd57fd912000-03-10 22:53:23 +000014669 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014670 ctx.arglen = PyTuple_Size(args);
14671 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014672 }
14673 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014674 ctx.arglen = -1;
14675 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014676 }
Victor Stinnera47082312012-10-04 02:19:54 +020014677 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014678 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014679 ctx.dict = args;
14680 else
14681 ctx.dict = NULL;
14682 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014683
Victor Stinnera47082312012-10-04 02:19:54 +020014684 while (--ctx.fmtcnt >= 0) {
14685 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014686 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014687
14688 nonfmtpos = ctx.fmtpos++;
14689 while (ctx.fmtcnt >= 0 &&
14690 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14691 ctx.fmtpos++;
14692 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014693 }
Victor Stinnera47082312012-10-04 02:19:54 +020014694 if (ctx.fmtcnt < 0) {
14695 ctx.fmtpos--;
14696 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014697 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014698
Victor Stinnercfc4c132013-04-03 01:48:39 +020014699 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14700 nonfmtpos, ctx.fmtpos) < 0)
14701 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014702 }
14703 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014704 ctx.fmtpos++;
14705 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014706 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014707 }
14708 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014709
Victor Stinnera47082312012-10-04 02:19:54 +020014710 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014711 PyErr_SetString(PyExc_TypeError,
14712 "not all arguments converted during string formatting");
14713 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014714 }
14715
Victor Stinnera47082312012-10-04 02:19:54 +020014716 if (ctx.args_owned) {
14717 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014718 }
Victor Stinnera47082312012-10-04 02:19:54 +020014719 Py_DECREF(ctx.fmtstr);
14720 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014721
Benjamin Peterson29060642009-01-31 22:14:21 +000014722 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014723 Py_DECREF(ctx.fmtstr);
14724 _PyUnicodeWriter_Dealloc(&ctx.writer);
14725 if (ctx.args_owned) {
14726 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014727 }
14728 return NULL;
14729}
14730
Jeremy Hylton938ace62002-07-17 16:30:39 +000014731static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014732unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14733
Tim Peters6d6c1a32001-08-02 04:15:00 +000014734static PyObject *
14735unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14736{
Benjamin Peterson29060642009-01-31 22:14:21 +000014737 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014738 static char *kwlist[] = {"object", "encoding", "errors", 0};
14739 char *encoding = NULL;
14740 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014741
Benjamin Peterson14339b62009-01-31 16:36:08 +000014742 if (type != &PyUnicode_Type)
14743 return unicode_subtype_new(type, args, kwds);
14744 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014745 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014746 return NULL;
14747 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014748 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014749 if (encoding == NULL && errors == NULL)
14750 return PyObject_Str(x);
14751 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014752 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014753}
14754
Guido van Rossume023fe02001-08-30 03:12:59 +000014755static PyObject *
14756unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14757{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014758 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014759 Py_ssize_t length, char_size;
14760 int share_wstr, share_utf8;
14761 unsigned int kind;
14762 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014763
Benjamin Peterson14339b62009-01-31 16:36:08 +000014764 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014765
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014766 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014767 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014768 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014769 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014770 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014771 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014772 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014773 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014774
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014775 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014776 if (self == NULL) {
14777 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014778 return NULL;
14779 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014780 kind = PyUnicode_KIND(unicode);
14781 length = PyUnicode_GET_LENGTH(unicode);
14782
14783 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014784#ifdef Py_DEBUG
14785 _PyUnicode_HASH(self) = -1;
14786#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014787 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014788#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014789 _PyUnicode_STATE(self).interned = 0;
14790 _PyUnicode_STATE(self).kind = kind;
14791 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014792 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014793 _PyUnicode_STATE(self).ready = 1;
14794 _PyUnicode_WSTR(self) = NULL;
14795 _PyUnicode_UTF8_LENGTH(self) = 0;
14796 _PyUnicode_UTF8(self) = NULL;
14797 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014798 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014799
14800 share_utf8 = 0;
14801 share_wstr = 0;
14802 if (kind == PyUnicode_1BYTE_KIND) {
14803 char_size = 1;
14804 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14805 share_utf8 = 1;
14806 }
14807 else if (kind == PyUnicode_2BYTE_KIND) {
14808 char_size = 2;
14809 if (sizeof(wchar_t) == 2)
14810 share_wstr = 1;
14811 }
14812 else {
14813 assert(kind == PyUnicode_4BYTE_KIND);
14814 char_size = 4;
14815 if (sizeof(wchar_t) == 4)
14816 share_wstr = 1;
14817 }
14818
14819 /* Ensure we won't overflow the length. */
14820 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14821 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014822 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014823 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014824 data = PyObject_MALLOC((length + 1) * char_size);
14825 if (data == NULL) {
14826 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014827 goto onError;
14828 }
14829
Victor Stinnerc3c74152011-10-02 20:39:55 +020014830 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014831 if (share_utf8) {
14832 _PyUnicode_UTF8_LENGTH(self) = length;
14833 _PyUnicode_UTF8(self) = data;
14834 }
14835 if (share_wstr) {
14836 _PyUnicode_WSTR_LENGTH(self) = length;
14837 _PyUnicode_WSTR(self) = (wchar_t *)data;
14838 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014839
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014840 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014841 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014842 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014843#ifdef Py_DEBUG
14844 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14845#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014846 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014847 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014848
14849onError:
14850 Py_DECREF(unicode);
14851 Py_DECREF(self);
14852 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014853}
14854
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014855PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014856"str(object='') -> str\n\
14857str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014858\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014859Create a new string object from the given object. If encoding or\n\
14860errors is specified, then the object must expose a data buffer\n\
14861that will be decoded using the given encoding and error handler.\n\
14862Otherwise, returns the result of object.__str__() (if defined)\n\
14863or repr(object).\n\
14864encoding defaults to sys.getdefaultencoding().\n\
14865errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014866
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014867static PyObject *unicode_iter(PyObject *seq);
14868
Guido van Rossumd57fd912000-03-10 22:53:23 +000014869PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014870 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014871 "str", /* tp_name */
14872 sizeof(PyUnicodeObject), /* tp_size */
14873 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014874 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014875 (destructor)unicode_dealloc, /* tp_dealloc */
14876 0, /* tp_print */
14877 0, /* tp_getattr */
14878 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014879 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014880 unicode_repr, /* tp_repr */
14881 &unicode_as_number, /* tp_as_number */
14882 &unicode_as_sequence, /* tp_as_sequence */
14883 &unicode_as_mapping, /* tp_as_mapping */
14884 (hashfunc) unicode_hash, /* tp_hash*/
14885 0, /* tp_call*/
14886 (reprfunc) unicode_str, /* tp_str */
14887 PyObject_GenericGetAttr, /* tp_getattro */
14888 0, /* tp_setattro */
14889 0, /* tp_as_buffer */
14890 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014891 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014892 unicode_doc, /* tp_doc */
14893 0, /* tp_traverse */
14894 0, /* tp_clear */
14895 PyUnicode_RichCompare, /* tp_richcompare */
14896 0, /* tp_weaklistoffset */
14897 unicode_iter, /* tp_iter */
14898 0, /* tp_iternext */
14899 unicode_methods, /* tp_methods */
14900 0, /* tp_members */
14901 0, /* tp_getset */
14902 &PyBaseObject_Type, /* tp_base */
14903 0, /* tp_dict */
14904 0, /* tp_descr_get */
14905 0, /* tp_descr_set */
14906 0, /* tp_dictoffset */
14907 0, /* tp_init */
14908 0, /* tp_alloc */
14909 unicode_new, /* tp_new */
14910 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014911};
14912
14913/* Initialize the Unicode implementation */
14914
Victor Stinner3a50e702011-10-18 21:21:00 +020014915int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014916{
Thomas Wouters477c8d52006-05-27 19:21:47 +000014917 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014918 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014919 0x000A, /* LINE FEED */
14920 0x000D, /* CARRIAGE RETURN */
14921 0x001C, /* FILE SEPARATOR */
14922 0x001D, /* GROUP SEPARATOR */
14923 0x001E, /* RECORD SEPARATOR */
14924 0x0085, /* NEXT LINE */
14925 0x2028, /* LINE SEPARATOR */
14926 0x2029, /* PARAGRAPH SEPARATOR */
14927 };
14928
Fred Drakee4315f52000-05-09 19:53:39 +000014929 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020014930 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014931 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014932 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020014933 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014934
Guido van Rossumcacfc072002-05-24 19:01:59 +000014935 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014936 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014937
14938 /* initialize the linebreak bloom filter */
14939 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014940 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014941 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014942
Christian Heimes26532f72013-07-20 14:57:16 +020014943 if (PyType_Ready(&EncodingMapType) < 0)
14944 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020014945
Benjamin Petersonc4311282012-10-30 23:21:10 -040014946 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
14947 Py_FatalError("Can't initialize field name iterator type");
14948
14949 if (PyType_Ready(&PyFormatterIter_Type) < 0)
14950 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040014951
Victor Stinner3a50e702011-10-18 21:21:00 +020014952 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014953}
14954
14955/* Finalize the Unicode implementation */
14956
Christian Heimesa156e092008-02-16 07:38:31 +000014957int
14958PyUnicode_ClearFreeList(void)
14959{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014960 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014961}
14962
Guido van Rossumd57fd912000-03-10 22:53:23 +000014963void
Thomas Wouters78890102000-07-22 19:25:51 +000014964_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014965{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014966 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014967
Serhiy Storchaka05997252013-01-26 12:14:02 +020014968 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014969
Serhiy Storchaka05997252013-01-26 12:14:02 +020014970 for (i = 0; i < 256; i++)
14971 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014972 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014973 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014974}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014975
Walter Dörwald16807132007-05-25 13:52:07 +000014976void
14977PyUnicode_InternInPlace(PyObject **p)
14978{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020014979 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014980 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014981#ifdef Py_DEBUG
14982 assert(s != NULL);
14983 assert(_PyUnicode_CHECK(s));
14984#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014985 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014986 return;
14987#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014988 /* If it's a subclass, we don't really know what putting
14989 it in the interned dict might do. */
14990 if (!PyUnicode_CheckExact(s))
14991 return;
14992 if (PyUnicode_CHECK_INTERNED(s))
14993 return;
14994 if (interned == NULL) {
14995 interned = PyDict_New();
14996 if (interned == NULL) {
14997 PyErr_Clear(); /* Don't leave an exception */
14998 return;
14999 }
15000 }
15001 /* It might be that the GetItem call fails even
15002 though the key is present in the dictionary,
15003 namely when this happens during a stack overflow. */
15004 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010015005 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015006 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000015007
Victor Stinnerf0335102013-04-14 19:13:03 +020015008 if (t) {
15009 Py_INCREF(t);
15010 Py_DECREF(*p);
15011 *p = t;
15012 return;
15013 }
Walter Dörwald16807132007-05-25 13:52:07 +000015014
Benjamin Peterson14339b62009-01-31 16:36:08 +000015015 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010015016 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015017 PyErr_Clear();
15018 PyThreadState_GET()->recursion_critical = 0;
15019 return;
15020 }
15021 PyThreadState_GET()->recursion_critical = 0;
15022 /* The two references in interned are not counted by refcnt.
15023 The deallocator will take care of this */
15024 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015025 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015026}
15027
15028void
15029PyUnicode_InternImmortal(PyObject **p)
15030{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015031 PyUnicode_InternInPlace(p);
15032 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015033 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015034 Py_INCREF(*p);
15035 }
Walter Dörwald16807132007-05-25 13:52:07 +000015036}
15037
15038PyObject *
15039PyUnicode_InternFromString(const char *cp)
15040{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015041 PyObject *s = PyUnicode_FromString(cp);
15042 if (s == NULL)
15043 return NULL;
15044 PyUnicode_InternInPlace(&s);
15045 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015046}
15047
Alexander Belopolsky40018472011-02-26 01:02:56 +000015048void
15049_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015050{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015051 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015052 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015053 Py_ssize_t i, n;
15054 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015055
Benjamin Peterson14339b62009-01-31 16:36:08 +000015056 if (interned == NULL || !PyDict_Check(interned))
15057 return;
15058 keys = PyDict_Keys(interned);
15059 if (keys == NULL || !PyList_Check(keys)) {
15060 PyErr_Clear();
15061 return;
15062 }
Walter Dörwald16807132007-05-25 13:52:07 +000015063
Benjamin Peterson14339b62009-01-31 16:36:08 +000015064 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15065 detector, interned unicode strings are not forcibly deallocated;
15066 rather, we give them their stolen references back, and then clear
15067 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015068
Benjamin Peterson14339b62009-01-31 16:36:08 +000015069 n = PyList_GET_SIZE(keys);
15070 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015071 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015072 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015073 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015074 if (PyUnicode_READY(s) == -1) {
15075 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015076 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015077 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015078 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015079 case SSTATE_NOT_INTERNED:
15080 /* XXX Shouldn't happen */
15081 break;
15082 case SSTATE_INTERNED_IMMORTAL:
15083 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015084 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015085 break;
15086 case SSTATE_INTERNED_MORTAL:
15087 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015088 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015089 break;
15090 default:
15091 Py_FatalError("Inconsistent interned string state.");
15092 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015093 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015094 }
15095 fprintf(stderr, "total size of all interned strings: "
15096 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15097 "mortal/immortal\n", mortal_size, immortal_size);
15098 Py_DECREF(keys);
15099 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015100 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015101}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015102
15103
15104/********************* Unicode Iterator **************************/
15105
15106typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015107 PyObject_HEAD
15108 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015109 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015110} unicodeiterobject;
15111
15112static void
15113unicodeiter_dealloc(unicodeiterobject *it)
15114{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015115 _PyObject_GC_UNTRACK(it);
15116 Py_XDECREF(it->it_seq);
15117 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015118}
15119
15120static int
15121unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15122{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015123 Py_VISIT(it->it_seq);
15124 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015125}
15126
15127static PyObject *
15128unicodeiter_next(unicodeiterobject *it)
15129{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015130 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015131
Benjamin Peterson14339b62009-01-31 16:36:08 +000015132 assert(it != NULL);
15133 seq = it->it_seq;
15134 if (seq == NULL)
15135 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015136 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015137
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015138 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15139 int kind = PyUnicode_KIND(seq);
15140 void *data = PyUnicode_DATA(seq);
15141 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15142 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015143 if (item != NULL)
15144 ++it->it_index;
15145 return item;
15146 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015147
Benjamin Peterson14339b62009-01-31 16:36:08 +000015148 Py_DECREF(seq);
15149 it->it_seq = NULL;
15150 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015151}
15152
15153static PyObject *
15154unicodeiter_len(unicodeiterobject *it)
15155{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015156 Py_ssize_t len = 0;
15157 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015158 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015159 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015160}
15161
15162PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15163
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015164static PyObject *
15165unicodeiter_reduce(unicodeiterobject *it)
15166{
15167 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015168 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015169 it->it_seq, it->it_index);
15170 } else {
15171 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
15172 if (u == NULL)
15173 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015174 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015175 }
15176}
15177
15178PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15179
15180static PyObject *
15181unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15182{
15183 Py_ssize_t index = PyLong_AsSsize_t(state);
15184 if (index == -1 && PyErr_Occurred())
15185 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015186 if (it->it_seq != NULL) {
15187 if (index < 0)
15188 index = 0;
15189 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15190 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15191 it->it_index = index;
15192 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015193 Py_RETURN_NONE;
15194}
15195
15196PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15197
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015198static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015199 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015200 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015201 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15202 reduce_doc},
15203 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15204 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015205 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015206};
15207
15208PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015209 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15210 "str_iterator", /* tp_name */
15211 sizeof(unicodeiterobject), /* tp_basicsize */
15212 0, /* tp_itemsize */
15213 /* methods */
15214 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15215 0, /* tp_print */
15216 0, /* tp_getattr */
15217 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015218 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015219 0, /* tp_repr */
15220 0, /* tp_as_number */
15221 0, /* tp_as_sequence */
15222 0, /* tp_as_mapping */
15223 0, /* tp_hash */
15224 0, /* tp_call */
15225 0, /* tp_str */
15226 PyObject_GenericGetAttr, /* tp_getattro */
15227 0, /* tp_setattro */
15228 0, /* tp_as_buffer */
15229 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15230 0, /* tp_doc */
15231 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15232 0, /* tp_clear */
15233 0, /* tp_richcompare */
15234 0, /* tp_weaklistoffset */
15235 PyObject_SelfIter, /* tp_iter */
15236 (iternextfunc)unicodeiter_next, /* tp_iternext */
15237 unicodeiter_methods, /* tp_methods */
15238 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015239};
15240
15241static PyObject *
15242unicode_iter(PyObject *seq)
15243{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015244 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015245
Benjamin Peterson14339b62009-01-31 16:36:08 +000015246 if (!PyUnicode_Check(seq)) {
15247 PyErr_BadInternalCall();
15248 return NULL;
15249 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015250 if (PyUnicode_READY(seq) == -1)
15251 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015252 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15253 if (it == NULL)
15254 return NULL;
15255 it->it_index = 0;
15256 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015257 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015258 _PyObject_GC_TRACK(it);
15259 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015260}
15261
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015262
15263size_t
15264Py_UNICODE_strlen(const Py_UNICODE *u)
15265{
15266 int res = 0;
15267 while(*u++)
15268 res++;
15269 return res;
15270}
15271
15272Py_UNICODE*
15273Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15274{
15275 Py_UNICODE *u = s1;
15276 while ((*u++ = *s2++));
15277 return s1;
15278}
15279
15280Py_UNICODE*
15281Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15282{
15283 Py_UNICODE *u = s1;
15284 while ((*u++ = *s2++))
15285 if (n-- == 0)
15286 break;
15287 return s1;
15288}
15289
15290Py_UNICODE*
15291Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15292{
15293 Py_UNICODE *u1 = s1;
15294 u1 += Py_UNICODE_strlen(u1);
15295 Py_UNICODE_strcpy(u1, s2);
15296 return s1;
15297}
15298
15299int
15300Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15301{
15302 while (*s1 && *s2 && *s1 == *s2)
15303 s1++, s2++;
15304 if (*s1 && *s2)
15305 return (*s1 < *s2) ? -1 : +1;
15306 if (*s1)
15307 return 1;
15308 if (*s2)
15309 return -1;
15310 return 0;
15311}
15312
15313int
15314Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15315{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015316 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015317 for (; n != 0; n--) {
15318 u1 = *s1;
15319 u2 = *s2;
15320 if (u1 != u2)
15321 return (u1 < u2) ? -1 : +1;
15322 if (u1 == '\0')
15323 return 0;
15324 s1++;
15325 s2++;
15326 }
15327 return 0;
15328}
15329
15330Py_UNICODE*
15331Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15332{
15333 const Py_UNICODE *p;
15334 for (p = s; *p; p++)
15335 if (*p == c)
15336 return (Py_UNICODE*)p;
15337 return NULL;
15338}
15339
15340Py_UNICODE*
15341Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15342{
15343 const Py_UNICODE *p;
15344 p = s + Py_UNICODE_strlen(s);
15345 while (p != s) {
15346 p--;
15347 if (*p == c)
15348 return (Py_UNICODE*)p;
15349 }
15350 return NULL;
15351}
Victor Stinner331ea922010-08-10 16:37:20 +000015352
Victor Stinner71133ff2010-09-01 23:43:53 +000015353Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015354PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015355{
Victor Stinner577db2c2011-10-11 22:12:48 +020015356 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015357 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015358
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015359 if (!PyUnicode_Check(unicode)) {
15360 PyErr_BadArgument();
15361 return NULL;
15362 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015363 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015364 if (u == NULL)
15365 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015366 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015367 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015368 PyErr_NoMemory();
15369 return NULL;
15370 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015371 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015372 size *= sizeof(Py_UNICODE);
15373 copy = PyMem_Malloc(size);
15374 if (copy == NULL) {
15375 PyErr_NoMemory();
15376 return NULL;
15377 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015378 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015379 return copy;
15380}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015381
Georg Brandl66c221e2010-10-14 07:04:07 +000015382/* A _string module, to export formatter_parser and formatter_field_name_split
15383 to the string.Formatter class implemented in Python. */
15384
15385static PyMethodDef _string_methods[] = {
15386 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15387 METH_O, PyDoc_STR("split the argument as a field name")},
15388 {"formatter_parser", (PyCFunction) formatter_parser,
15389 METH_O, PyDoc_STR("parse the argument as a format string")},
15390 {NULL, NULL}
15391};
15392
15393static struct PyModuleDef _string_module = {
15394 PyModuleDef_HEAD_INIT,
15395 "_string",
15396 PyDoc_STR("string helper module"),
15397 0,
15398 _string_methods,
15399 NULL,
15400 NULL,
15401 NULL,
15402 NULL
15403};
15404
15405PyMODINIT_FUNC
15406PyInit__string(void)
15407{
15408 return PyModule_Create(&_string_module);
15409}
15410
15411
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015412#ifdef __cplusplus
15413}
15414#endif