blob: b8840e1e360e4ab3ea0d9343dc76ec6b5601919b [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
Victor Stinnerf96418d2015-09-21 23:06:27 +02006647typedef enum {
6648 _Py_ERROR_UNKNOWN=0,
6649 _Py_ERROR_SURROGATEESCAPE,
6650 _Py_ERROR_REPLACE,
6651 _Py_ERROR_IGNORE,
6652 _Py_ERROR_OTHER
6653} _Py_error_handler;
6654
6655static _Py_error_handler
6656get_error_handler(const char *errors)
6657{
6658 if (errors == NULL)
6659 return _Py_ERROR_OTHER;
6660 if (strcmp(errors, "surrogateescape") == 0)
6661 return _Py_ERROR_SURROGATEESCAPE;
6662 if (strcmp(errors, "ignore") == 0)
6663 return _Py_ERROR_IGNORE;
6664 if (strcmp(errors, "replace") == 0)
6665 return _Py_ERROR_REPLACE;
6666 return _Py_ERROR_OTHER;
6667}
6668
Alexander Belopolsky40018472011-02-26 01:02:56 +00006669PyObject *
6670PyUnicode_DecodeASCII(const char *s,
6671 Py_ssize_t size,
6672 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006673{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006674 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006675 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006676 int kind;
6677 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006678 Py_ssize_t startinpos;
6679 Py_ssize_t endinpos;
6680 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006681 const char *e;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006682 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006683 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006684 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00006685
Guido van Rossumd57fd912000-03-10 22:53:23 +00006686 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006687 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006688
Guido van Rossumd57fd912000-03-10 22:53:23 +00006689 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006690 if (size == 1 && (unsigned char)s[0] < 128)
6691 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006692
Victor Stinner8f674cc2013-04-17 23:02:17 +02006693 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006694 writer.min_length = size;
6695 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006696 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006697
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006698 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006699 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006700 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006701 writer.pos = outpos;
6702 if (writer.pos == size)
6703 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006704
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006705 s += writer.pos;
6706 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006707 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006708 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006709 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006710 PyUnicode_WRITE(kind, data, writer.pos, c);
6711 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006712 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006713 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00006714 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006715
6716 /* byte outsize range 0x00..0x7f: call the error handler */
6717
6718 if (error_handler == _Py_ERROR_UNKNOWN)
6719 error_handler = get_error_handler(errors);
6720
6721 switch (error_handler)
6722 {
6723 case _Py_ERROR_REPLACE:
6724 case _Py_ERROR_SURROGATEESCAPE:
6725 /* Fast-path: the error handler only writes one character,
6726 but we must switch to UCS2 at the first write */
6727 if (kind < PyUnicode_2BYTE_KIND) {
6728 if (_PyUnicodeWriter_Prepare(&writer, size - writer.pos,
6729 0xffff) < 0)
6730 return NULL;
6731 kind = writer.kind;
6732 data = writer.data;
6733 }
6734
6735 if (error_handler == _Py_ERROR_REPLACE)
6736 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
6737 else
6738 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
6739 writer.pos++;
6740 ++s;
6741 break;
6742
6743 case _Py_ERROR_IGNORE:
6744 ++s;
6745 break;
6746
6747 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00006748 startinpos = s-starts;
6749 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006750 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02006751 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00006752 "ascii", "ordinal not in range(128)",
6753 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006754 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006755 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006756 kind = writer.kind;
6757 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006758 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006759 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006760 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006761 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006762 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006763
Benjamin Peterson29060642009-01-31 22:14:21 +00006764 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006765 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02006766 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006767 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006768 return NULL;
6769}
6770
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006771/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006772PyObject *
6773PyUnicode_EncodeASCII(const Py_UNICODE *p,
6774 Py_ssize_t size,
6775 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006776{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006777 PyObject *result;
6778 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6779 if (unicode == NULL)
6780 return NULL;
6781 result = unicode_encode_ucs1(unicode, errors, 128);
6782 Py_DECREF(unicode);
6783 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006784}
6785
Alexander Belopolsky40018472011-02-26 01:02:56 +00006786PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006787_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006788{
6789 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006790 PyErr_BadArgument();
6791 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006792 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006793 if (PyUnicode_READY(unicode) == -1)
6794 return NULL;
6795 /* Fast path: if it is an ASCII-only string, construct bytes object
6796 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02006797 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006798 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6799 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006800 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006801}
6802
6803PyObject *
6804PyUnicode_AsASCIIString(PyObject *unicode)
6805{
6806 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006807}
6808
Victor Stinner99b95382011-07-04 14:23:54 +02006809#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006810
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006811/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006812
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006813#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006814#define NEED_RETRY
6815#endif
6816
Victor Stinner3a50e702011-10-18 21:21:00 +02006817#ifndef WC_ERR_INVALID_CHARS
6818# define WC_ERR_INVALID_CHARS 0x0080
6819#endif
6820
6821static char*
6822code_page_name(UINT code_page, PyObject **obj)
6823{
6824 *obj = NULL;
6825 if (code_page == CP_ACP)
6826 return "mbcs";
6827 if (code_page == CP_UTF7)
6828 return "CP_UTF7";
6829 if (code_page == CP_UTF8)
6830 return "CP_UTF8";
6831
6832 *obj = PyBytes_FromFormat("cp%u", code_page);
6833 if (*obj == NULL)
6834 return NULL;
6835 return PyBytes_AS_STRING(*obj);
6836}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006837
Victor Stinner3a50e702011-10-18 21:21:00 +02006838static DWORD
6839decode_code_page_flags(UINT code_page)
6840{
6841 if (code_page == CP_UTF7) {
6842 /* The CP_UTF7 decoder only supports flags=0 */
6843 return 0;
6844 }
6845 else
6846 return MB_ERR_INVALID_CHARS;
6847}
6848
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006849/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006850 * Decode a byte string from a Windows code page into unicode object in strict
6851 * mode.
6852 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006853 * Returns consumed size if succeed, returns -2 on decode error, or raise an
6854 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006855 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006856static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006857decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006858 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006859 const char *in,
6860 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006861{
Victor Stinner3a50e702011-10-18 21:21:00 +02006862 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006863 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006864 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006865
6866 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006867 assert(insize > 0);
6868 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6869 if (outsize <= 0)
6870 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006871
6872 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006873 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01006874 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006875 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006876 if (*v == NULL)
6877 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006878 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006879 }
6880 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006881 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006882 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01006883 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006884 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006885 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006886 }
6887
6888 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006889 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6890 if (outsize <= 0)
6891 goto error;
6892 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006893
Victor Stinner3a50e702011-10-18 21:21:00 +02006894error:
6895 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6896 return -2;
6897 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006898 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006899}
6900
Victor Stinner3a50e702011-10-18 21:21:00 +02006901/*
6902 * Decode a byte string from a code page into unicode object with an error
6903 * handler.
6904 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02006905 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02006906 * UnicodeDecodeError exception and returns -1 on error.
6907 */
6908static int
6909decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006910 PyObject **v,
6911 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01006912 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02006913{
6914 const char *startin = in;
6915 const char *endin = in + size;
6916 const DWORD flags = decode_code_page_flags(code_page);
6917 /* Ideally, we should get reason from FormatMessage. This is the Windows
6918 2000 English version of the message. */
6919 const char *reason = "No mapping for the Unicode character exists "
6920 "in the target code page.";
6921 /* each step cannot decode more than 1 character, but a character can be
6922 represented as a surrogate pair */
6923 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02006924 int insize;
6925 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02006926 PyObject *errorHandler = NULL;
6927 PyObject *exc = NULL;
6928 PyObject *encoding_obj = NULL;
6929 char *encoding;
6930 DWORD err;
6931 int ret = -1;
6932
6933 assert(size > 0);
6934
6935 encoding = code_page_name(code_page, &encoding_obj);
6936 if (encoding == NULL)
6937 return -1;
6938
Victor Stinner7d00cc12014-03-17 23:08:06 +01006939 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02006940 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6941 UnicodeDecodeError. */
6942 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6943 if (exc != NULL) {
6944 PyCodec_StrictErrors(exc);
6945 Py_CLEAR(exc);
6946 }
6947 goto error;
6948 }
6949
6950 if (*v == NULL) {
6951 /* Create unicode object */
6952 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6953 PyErr_NoMemory();
6954 goto error;
6955 }
Victor Stinnerab595942011-12-17 04:59:06 +01006956 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01006957 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006958 if (*v == NULL)
6959 goto error;
6960 startout = PyUnicode_AS_UNICODE(*v);
6961 }
6962 else {
6963 /* Extend unicode object */
6964 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6965 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6966 PyErr_NoMemory();
6967 goto error;
6968 }
Victor Stinner16e6a802011-12-12 13:24:15 +01006969 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006970 goto error;
6971 startout = PyUnicode_AS_UNICODE(*v) + n;
6972 }
6973
6974 /* Decode the byte string character per character */
6975 out = startout;
6976 while (in < endin)
6977 {
6978 /* Decode a character */
6979 insize = 1;
6980 do
6981 {
6982 outsize = MultiByteToWideChar(code_page, flags,
6983 in, insize,
6984 buffer, Py_ARRAY_LENGTH(buffer));
6985 if (outsize > 0)
6986 break;
6987 err = GetLastError();
6988 if (err != ERROR_NO_UNICODE_TRANSLATION
6989 && err != ERROR_INSUFFICIENT_BUFFER)
6990 {
6991 PyErr_SetFromWindowsErr(0);
6992 goto error;
6993 }
6994 insize++;
6995 }
6996 /* 4=maximum length of a UTF-8 sequence */
6997 while (insize <= 4 && (in + insize) <= endin);
6998
6999 if (outsize <= 0) {
7000 Py_ssize_t startinpos, endinpos, outpos;
7001
Victor Stinner7d00cc12014-03-17 23:08:06 +01007002 /* last character in partial decode? */
7003 if (in + insize >= endin && !final)
7004 break;
7005
Victor Stinner3a50e702011-10-18 21:21:00 +02007006 startinpos = in - startin;
7007 endinpos = startinpos + 1;
7008 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007009 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007010 errors, &errorHandler,
7011 encoding, reason,
7012 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007013 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007014 {
7015 goto error;
7016 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007017 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007018 }
7019 else {
7020 in += insize;
7021 memcpy(out, buffer, outsize * sizeof(wchar_t));
7022 out += outsize;
7023 }
7024 }
7025
7026 /* write a NUL character at the end */
7027 *out = 0;
7028
7029 /* Extend unicode object */
7030 outsize = out - startout;
7031 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007032 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007033 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007034 /* (in - startin) <= size and size is an int */
7035 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007036
7037error:
7038 Py_XDECREF(encoding_obj);
7039 Py_XDECREF(errorHandler);
7040 Py_XDECREF(exc);
7041 return ret;
7042}
7043
Victor Stinner3a50e702011-10-18 21:21:00 +02007044static PyObject *
7045decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007046 const char *s, Py_ssize_t size,
7047 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007048{
Victor Stinner76a31a62011-11-04 00:05:13 +01007049 PyObject *v = NULL;
7050 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007051
Victor Stinner3a50e702011-10-18 21:21:00 +02007052 if (code_page < 0) {
7053 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7054 return NULL;
7055 }
7056
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007057 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007058 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007059
Victor Stinner76a31a62011-11-04 00:05:13 +01007060 do
7061 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007062#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007063 if (size > INT_MAX) {
7064 chunk_size = INT_MAX;
7065 final = 0;
7066 done = 0;
7067 }
7068 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007069#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007070 {
7071 chunk_size = (int)size;
7072 final = (consumed == NULL);
7073 done = 1;
7074 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007075
Victor Stinner76a31a62011-11-04 00:05:13 +01007076 if (chunk_size == 0 && done) {
7077 if (v != NULL)
7078 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007079 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007080 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007081
Victor Stinner76a31a62011-11-04 00:05:13 +01007082 converted = decode_code_page_strict(code_page, &v,
7083 s, chunk_size);
7084 if (converted == -2)
7085 converted = decode_code_page_errors(code_page, &v,
7086 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007087 errors, final);
7088 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007089
7090 if (converted < 0) {
7091 Py_XDECREF(v);
7092 return NULL;
7093 }
7094
7095 if (consumed)
7096 *consumed += converted;
7097
7098 s += converted;
7099 size -= converted;
7100 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007101
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007102 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007103}
7104
Alexander Belopolsky40018472011-02-26 01:02:56 +00007105PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007106PyUnicode_DecodeCodePageStateful(int code_page,
7107 const char *s,
7108 Py_ssize_t size,
7109 const char *errors,
7110 Py_ssize_t *consumed)
7111{
7112 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7113}
7114
7115PyObject *
7116PyUnicode_DecodeMBCSStateful(const char *s,
7117 Py_ssize_t size,
7118 const char *errors,
7119 Py_ssize_t *consumed)
7120{
7121 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7122}
7123
7124PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007125PyUnicode_DecodeMBCS(const char *s,
7126 Py_ssize_t size,
7127 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007128{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007129 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7130}
7131
Victor Stinner3a50e702011-10-18 21:21:00 +02007132static DWORD
7133encode_code_page_flags(UINT code_page, const char *errors)
7134{
7135 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007136 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007137 }
7138 else if (code_page == CP_UTF7) {
7139 /* CP_UTF7 only supports flags=0 */
7140 return 0;
7141 }
7142 else {
7143 if (errors != NULL && strcmp(errors, "replace") == 0)
7144 return 0;
7145 else
7146 return WC_NO_BEST_FIT_CHARS;
7147 }
7148}
7149
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007150/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007151 * Encode a Unicode string to a Windows code page into a byte string in strict
7152 * mode.
7153 *
7154 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007155 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007156 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007157static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007158encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007159 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007160 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007161{
Victor Stinner554f3f02010-06-16 23:33:54 +00007162 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007163 BOOL *pusedDefaultChar = &usedDefaultChar;
7164 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007165 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007166 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007167 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007168 const DWORD flags = encode_code_page_flags(code_page, NULL);
7169 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007170 /* Create a substring so that we can get the UTF-16 representation
7171 of just the slice under consideration. */
7172 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007173
Martin v. Löwis3d325192011-11-04 18:23:06 +01007174 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007175
Victor Stinner3a50e702011-10-18 21:21:00 +02007176 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007177 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007178 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007179 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007180
Victor Stinner2fc507f2011-11-04 20:06:39 +01007181 substring = PyUnicode_Substring(unicode, offset, offset+len);
7182 if (substring == NULL)
7183 return -1;
7184 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7185 if (p == NULL) {
7186 Py_DECREF(substring);
7187 return -1;
7188 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007189 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007190
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007191 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007192 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007193 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007194 NULL, 0,
7195 NULL, pusedDefaultChar);
7196 if (outsize <= 0)
7197 goto error;
7198 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007199 if (pusedDefaultChar && *pusedDefaultChar) {
7200 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007201 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007202 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007203
Victor Stinner3a50e702011-10-18 21:21:00 +02007204 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007205 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007206 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007207 if (*outbytes == NULL) {
7208 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007209 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007210 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007211 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007212 }
7213 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007214 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007215 const Py_ssize_t n = PyBytes_Size(*outbytes);
7216 if (outsize > PY_SSIZE_T_MAX - n) {
7217 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007218 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007219 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007220 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007221 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7222 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007223 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007224 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007225 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007226 }
7227
7228 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007229 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007230 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007231 out, outsize,
7232 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007233 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007234 if (outsize <= 0)
7235 goto error;
7236 if (pusedDefaultChar && *pusedDefaultChar)
7237 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007238 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007239
Victor Stinner3a50e702011-10-18 21:21:00 +02007240error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007241 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007242 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7243 return -2;
7244 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007245 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007246}
7247
Victor Stinner3a50e702011-10-18 21:21:00 +02007248/*
7249 * Encode a Unicode string to a Windows code page into a byte string using a
7250 * error handler.
7251 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007252 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007253 * -1 on other error.
7254 */
7255static int
7256encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007257 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007258 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007259{
Victor Stinner3a50e702011-10-18 21:21:00 +02007260 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007261 Py_ssize_t pos = unicode_offset;
7262 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007263 /* Ideally, we should get reason from FormatMessage. This is the Windows
7264 2000 English version of the message. */
7265 const char *reason = "invalid character";
7266 /* 4=maximum length of a UTF-8 sequence */
7267 char buffer[4];
7268 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7269 Py_ssize_t outsize;
7270 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007271 PyObject *errorHandler = NULL;
7272 PyObject *exc = NULL;
7273 PyObject *encoding_obj = NULL;
7274 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007275 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007276 PyObject *rep;
7277 int ret = -1;
7278
7279 assert(insize > 0);
7280
7281 encoding = code_page_name(code_page, &encoding_obj);
7282 if (encoding == NULL)
7283 return -1;
7284
7285 if (errors == NULL || strcmp(errors, "strict") == 0) {
7286 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7287 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007288 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007289 if (exc != NULL) {
7290 PyCodec_StrictErrors(exc);
7291 Py_DECREF(exc);
7292 }
7293 Py_XDECREF(encoding_obj);
7294 return -1;
7295 }
7296
7297 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7298 pusedDefaultChar = &usedDefaultChar;
7299 else
7300 pusedDefaultChar = NULL;
7301
7302 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7303 PyErr_NoMemory();
7304 goto error;
7305 }
7306 outsize = insize * Py_ARRAY_LENGTH(buffer);
7307
7308 if (*outbytes == NULL) {
7309 /* Create string object */
7310 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7311 if (*outbytes == NULL)
7312 goto error;
7313 out = PyBytes_AS_STRING(*outbytes);
7314 }
7315 else {
7316 /* Extend string object */
7317 Py_ssize_t n = PyBytes_Size(*outbytes);
7318 if (n > PY_SSIZE_T_MAX - outsize) {
7319 PyErr_NoMemory();
7320 goto error;
7321 }
7322 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7323 goto error;
7324 out = PyBytes_AS_STRING(*outbytes) + n;
7325 }
7326
7327 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007328 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007329 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007330 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7331 wchar_t chars[2];
7332 int charsize;
7333 if (ch < 0x10000) {
7334 chars[0] = (wchar_t)ch;
7335 charsize = 1;
7336 }
7337 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007338 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7339 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007340 charsize = 2;
7341 }
7342
Victor Stinner3a50e702011-10-18 21:21:00 +02007343 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007344 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007345 buffer, Py_ARRAY_LENGTH(buffer),
7346 NULL, pusedDefaultChar);
7347 if (outsize > 0) {
7348 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7349 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007350 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007351 memcpy(out, buffer, outsize);
7352 out += outsize;
7353 continue;
7354 }
7355 }
7356 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7357 PyErr_SetFromWindowsErr(0);
7358 goto error;
7359 }
7360
Victor Stinner3a50e702011-10-18 21:21:00 +02007361 rep = unicode_encode_call_errorhandler(
7362 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007363 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007364 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007365 if (rep == NULL)
7366 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007367 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007368
7369 if (PyBytes_Check(rep)) {
7370 outsize = PyBytes_GET_SIZE(rep);
7371 if (outsize != 1) {
7372 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7373 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7374 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7375 Py_DECREF(rep);
7376 goto error;
7377 }
7378 out = PyBytes_AS_STRING(*outbytes) + offset;
7379 }
7380 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7381 out += outsize;
7382 }
7383 else {
7384 Py_ssize_t i;
7385 enum PyUnicode_Kind kind;
7386 void *data;
7387
Benjamin Petersonbac79492012-01-14 13:34:47 -05007388 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007389 Py_DECREF(rep);
7390 goto error;
7391 }
7392
7393 outsize = PyUnicode_GET_LENGTH(rep);
7394 if (outsize != 1) {
7395 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7396 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7397 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7398 Py_DECREF(rep);
7399 goto error;
7400 }
7401 out = PyBytes_AS_STRING(*outbytes) + offset;
7402 }
7403 kind = PyUnicode_KIND(rep);
7404 data = PyUnicode_DATA(rep);
7405 for (i=0; i < outsize; i++) {
7406 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7407 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007408 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007409 encoding, unicode,
7410 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007411 "unable to encode error handler result to ASCII");
7412 Py_DECREF(rep);
7413 goto error;
7414 }
7415 *out = (unsigned char)ch;
7416 out++;
7417 }
7418 }
7419 Py_DECREF(rep);
7420 }
7421 /* write a NUL byte */
7422 *out = 0;
7423 outsize = out - PyBytes_AS_STRING(*outbytes);
7424 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7425 if (_PyBytes_Resize(outbytes, outsize) < 0)
7426 goto error;
7427 ret = 0;
7428
7429error:
7430 Py_XDECREF(encoding_obj);
7431 Py_XDECREF(errorHandler);
7432 Py_XDECREF(exc);
7433 return ret;
7434}
7435
Victor Stinner3a50e702011-10-18 21:21:00 +02007436static PyObject *
7437encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007438 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007439 const char *errors)
7440{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007441 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007442 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007443 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007444 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007445
Victor Stinner29dacf22015-01-26 16:41:32 +01007446 if (!PyUnicode_Check(unicode)) {
7447 PyErr_BadArgument();
7448 return NULL;
7449 }
7450
Benjamin Petersonbac79492012-01-14 13:34:47 -05007451 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007452 return NULL;
7453 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007454
Victor Stinner3a50e702011-10-18 21:21:00 +02007455 if (code_page < 0) {
7456 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7457 return NULL;
7458 }
7459
Martin v. Löwis3d325192011-11-04 18:23:06 +01007460 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007461 return PyBytes_FromStringAndSize(NULL, 0);
7462
Victor Stinner7581cef2011-11-03 22:32:33 +01007463 offset = 0;
7464 do
7465 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007466#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007467 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007468 chunks. */
7469 if (len > INT_MAX/2) {
7470 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007471 done = 0;
7472 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007473 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007474#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007475 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007476 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007477 done = 1;
7478 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007479
Victor Stinner76a31a62011-11-04 00:05:13 +01007480 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007481 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007482 errors);
7483 if (ret == -2)
7484 ret = encode_code_page_errors(code_page, &outbytes,
7485 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007486 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007487 if (ret < 0) {
7488 Py_XDECREF(outbytes);
7489 return NULL;
7490 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007491
Victor Stinner7581cef2011-11-03 22:32:33 +01007492 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007493 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007494 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007495
Victor Stinner3a50e702011-10-18 21:21:00 +02007496 return outbytes;
7497}
7498
7499PyObject *
7500PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7501 Py_ssize_t size,
7502 const char *errors)
7503{
Victor Stinner7581cef2011-11-03 22:32:33 +01007504 PyObject *unicode, *res;
7505 unicode = PyUnicode_FromUnicode(p, size);
7506 if (unicode == NULL)
7507 return NULL;
7508 res = encode_code_page(CP_ACP, unicode, errors);
7509 Py_DECREF(unicode);
7510 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007511}
7512
7513PyObject *
7514PyUnicode_EncodeCodePage(int code_page,
7515 PyObject *unicode,
7516 const char *errors)
7517{
Victor Stinner7581cef2011-11-03 22:32:33 +01007518 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007519}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007520
Alexander Belopolsky40018472011-02-26 01:02:56 +00007521PyObject *
7522PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007523{
Victor Stinner7581cef2011-11-03 22:32:33 +01007524 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007525}
7526
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007527#undef NEED_RETRY
7528
Victor Stinner99b95382011-07-04 14:23:54 +02007529#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007530
Guido van Rossumd57fd912000-03-10 22:53:23 +00007531/* --- Character Mapping Codec -------------------------------------------- */
7532
Victor Stinnerfb161b12013-04-18 01:44:27 +02007533static int
7534charmap_decode_string(const char *s,
7535 Py_ssize_t size,
7536 PyObject *mapping,
7537 const char *errors,
7538 _PyUnicodeWriter *writer)
7539{
7540 const char *starts = s;
7541 const char *e;
7542 Py_ssize_t startinpos, endinpos;
7543 PyObject *errorHandler = NULL, *exc = NULL;
7544 Py_ssize_t maplen;
7545 enum PyUnicode_Kind mapkind;
7546 void *mapdata;
7547 Py_UCS4 x;
7548 unsigned char ch;
7549
7550 if (PyUnicode_READY(mapping) == -1)
7551 return -1;
7552
7553 maplen = PyUnicode_GET_LENGTH(mapping);
7554 mapdata = PyUnicode_DATA(mapping);
7555 mapkind = PyUnicode_KIND(mapping);
7556
7557 e = s + size;
7558
7559 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7560 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7561 * is disabled in encoding aliases, latin1 is preferred because
7562 * its implementation is faster. */
7563 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7564 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7565 Py_UCS4 maxchar = writer->maxchar;
7566
7567 assert (writer->kind == PyUnicode_1BYTE_KIND);
7568 while (s < e) {
7569 ch = *s;
7570 x = mapdata_ucs1[ch];
7571 if (x > maxchar) {
7572 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7573 goto onError;
7574 maxchar = writer->maxchar;
7575 outdata = (Py_UCS1 *)writer->data;
7576 }
7577 outdata[writer->pos] = x;
7578 writer->pos++;
7579 ++s;
7580 }
7581 return 0;
7582 }
7583
7584 while (s < e) {
7585 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7586 enum PyUnicode_Kind outkind = writer->kind;
7587 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7588 if (outkind == PyUnicode_1BYTE_KIND) {
7589 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7590 Py_UCS4 maxchar = writer->maxchar;
7591 while (s < e) {
7592 ch = *s;
7593 x = mapdata_ucs2[ch];
7594 if (x > maxchar)
7595 goto Error;
7596 outdata[writer->pos] = x;
7597 writer->pos++;
7598 ++s;
7599 }
7600 break;
7601 }
7602 else if (outkind == PyUnicode_2BYTE_KIND) {
7603 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7604 while (s < e) {
7605 ch = *s;
7606 x = mapdata_ucs2[ch];
7607 if (x == 0xFFFE)
7608 goto Error;
7609 outdata[writer->pos] = x;
7610 writer->pos++;
7611 ++s;
7612 }
7613 break;
7614 }
7615 }
7616 ch = *s;
7617
7618 if (ch < maplen)
7619 x = PyUnicode_READ(mapkind, mapdata, ch);
7620 else
7621 x = 0xfffe; /* invalid value */
7622Error:
7623 if (x == 0xfffe)
7624 {
7625 /* undefined mapping */
7626 startinpos = s-starts;
7627 endinpos = startinpos+1;
7628 if (unicode_decode_call_errorhandler_writer(
7629 errors, &errorHandler,
7630 "charmap", "character maps to <undefined>",
7631 &starts, &e, &startinpos, &endinpos, &exc, &s,
7632 writer)) {
7633 goto onError;
7634 }
7635 continue;
7636 }
7637
7638 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7639 goto onError;
7640 ++s;
7641 }
7642 Py_XDECREF(errorHandler);
7643 Py_XDECREF(exc);
7644 return 0;
7645
7646onError:
7647 Py_XDECREF(errorHandler);
7648 Py_XDECREF(exc);
7649 return -1;
7650}
7651
7652static int
7653charmap_decode_mapping(const char *s,
7654 Py_ssize_t size,
7655 PyObject *mapping,
7656 const char *errors,
7657 _PyUnicodeWriter *writer)
7658{
7659 const char *starts = s;
7660 const char *e;
7661 Py_ssize_t startinpos, endinpos;
7662 PyObject *errorHandler = NULL, *exc = NULL;
7663 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007664 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007665
7666 e = s + size;
7667
7668 while (s < e) {
7669 ch = *s;
7670
7671 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7672 key = PyLong_FromLong((long)ch);
7673 if (key == NULL)
7674 goto onError;
7675
7676 item = PyObject_GetItem(mapping, key);
7677 Py_DECREF(key);
7678 if (item == NULL) {
7679 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7680 /* No mapping found means: mapping is undefined. */
7681 PyErr_Clear();
7682 goto Undefined;
7683 } else
7684 goto onError;
7685 }
7686
7687 /* Apply mapping */
7688 if (item == Py_None)
7689 goto Undefined;
7690 if (PyLong_Check(item)) {
7691 long value = PyLong_AS_LONG(item);
7692 if (value == 0xFFFE)
7693 goto Undefined;
7694 if (value < 0 || value > MAX_UNICODE) {
7695 PyErr_Format(PyExc_TypeError,
7696 "character mapping must be in range(0x%lx)",
7697 (unsigned long)MAX_UNICODE + 1);
7698 goto onError;
7699 }
7700
7701 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7702 goto onError;
7703 }
7704 else if (PyUnicode_Check(item)) {
7705 if (PyUnicode_READY(item) == -1)
7706 goto onError;
7707 if (PyUnicode_GET_LENGTH(item) == 1) {
7708 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7709 if (value == 0xFFFE)
7710 goto Undefined;
7711 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7712 goto onError;
7713 }
7714 else {
7715 writer->overallocate = 1;
7716 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7717 goto onError;
7718 }
7719 }
7720 else {
7721 /* wrong return value */
7722 PyErr_SetString(PyExc_TypeError,
7723 "character mapping must return integer, None or str");
7724 goto onError;
7725 }
7726 Py_CLEAR(item);
7727 ++s;
7728 continue;
7729
7730Undefined:
7731 /* undefined mapping */
7732 Py_CLEAR(item);
7733 startinpos = s-starts;
7734 endinpos = startinpos+1;
7735 if (unicode_decode_call_errorhandler_writer(
7736 errors, &errorHandler,
7737 "charmap", "character maps to <undefined>",
7738 &starts, &e, &startinpos, &endinpos, &exc, &s,
7739 writer)) {
7740 goto onError;
7741 }
7742 }
7743 Py_XDECREF(errorHandler);
7744 Py_XDECREF(exc);
7745 return 0;
7746
7747onError:
7748 Py_XDECREF(item);
7749 Py_XDECREF(errorHandler);
7750 Py_XDECREF(exc);
7751 return -1;
7752}
7753
Alexander Belopolsky40018472011-02-26 01:02:56 +00007754PyObject *
7755PyUnicode_DecodeCharmap(const char *s,
7756 Py_ssize_t size,
7757 PyObject *mapping,
7758 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007759{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007760 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007761
Guido van Rossumd57fd912000-03-10 22:53:23 +00007762 /* Default to Latin-1 */
7763 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007764 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007765
Guido van Rossumd57fd912000-03-10 22:53:23 +00007766 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007767 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007768 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007769 writer.min_length = size;
7770 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007771 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007772
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007773 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007774 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
7775 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007776 }
7777 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007778 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
7779 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007780 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007781 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007782
Benjamin Peterson29060642009-01-31 22:14:21 +00007783 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007784 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007785 return NULL;
7786}
7787
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007788/* Charmap encoding: the lookup table */
7789
Alexander Belopolsky40018472011-02-26 01:02:56 +00007790struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007791 PyObject_HEAD
7792 unsigned char level1[32];
7793 int count2, count3;
7794 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007795};
7796
7797static PyObject*
7798encoding_map_size(PyObject *obj, PyObject* args)
7799{
7800 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007801 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007802 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007803}
7804
7805static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007806 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007807 PyDoc_STR("Return the size (in bytes) of this object") },
7808 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007809};
7810
7811static void
7812encoding_map_dealloc(PyObject* o)
7813{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007814 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007815}
7816
7817static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007818 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007819 "EncodingMap", /*tp_name*/
7820 sizeof(struct encoding_map), /*tp_basicsize*/
7821 0, /*tp_itemsize*/
7822 /* methods */
7823 encoding_map_dealloc, /*tp_dealloc*/
7824 0, /*tp_print*/
7825 0, /*tp_getattr*/
7826 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007827 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007828 0, /*tp_repr*/
7829 0, /*tp_as_number*/
7830 0, /*tp_as_sequence*/
7831 0, /*tp_as_mapping*/
7832 0, /*tp_hash*/
7833 0, /*tp_call*/
7834 0, /*tp_str*/
7835 0, /*tp_getattro*/
7836 0, /*tp_setattro*/
7837 0, /*tp_as_buffer*/
7838 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7839 0, /*tp_doc*/
7840 0, /*tp_traverse*/
7841 0, /*tp_clear*/
7842 0, /*tp_richcompare*/
7843 0, /*tp_weaklistoffset*/
7844 0, /*tp_iter*/
7845 0, /*tp_iternext*/
7846 encoding_map_methods, /*tp_methods*/
7847 0, /*tp_members*/
7848 0, /*tp_getset*/
7849 0, /*tp_base*/
7850 0, /*tp_dict*/
7851 0, /*tp_descr_get*/
7852 0, /*tp_descr_set*/
7853 0, /*tp_dictoffset*/
7854 0, /*tp_init*/
7855 0, /*tp_alloc*/
7856 0, /*tp_new*/
7857 0, /*tp_free*/
7858 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007859};
7860
7861PyObject*
7862PyUnicode_BuildEncodingMap(PyObject* string)
7863{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007864 PyObject *result;
7865 struct encoding_map *mresult;
7866 int i;
7867 int need_dict = 0;
7868 unsigned char level1[32];
7869 unsigned char level2[512];
7870 unsigned char *mlevel1, *mlevel2, *mlevel3;
7871 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007872 int kind;
7873 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007874 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007875 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007876
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007877 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007878 PyErr_BadArgument();
7879 return NULL;
7880 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007881 kind = PyUnicode_KIND(string);
7882 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007883 length = PyUnicode_GET_LENGTH(string);
7884 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007885 memset(level1, 0xFF, sizeof level1);
7886 memset(level2, 0xFF, sizeof level2);
7887
7888 /* If there isn't a one-to-one mapping of NULL to \0,
7889 or if there are non-BMP characters, we need to use
7890 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007891 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007892 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007893 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007894 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007895 ch = PyUnicode_READ(kind, data, i);
7896 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007897 need_dict = 1;
7898 break;
7899 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007900 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007901 /* unmapped character */
7902 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007903 l1 = ch >> 11;
7904 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007905 if (level1[l1] == 0xFF)
7906 level1[l1] = count2++;
7907 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007908 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007909 }
7910
7911 if (count2 >= 0xFF || count3 >= 0xFF)
7912 need_dict = 1;
7913
7914 if (need_dict) {
7915 PyObject *result = PyDict_New();
7916 PyObject *key, *value;
7917 if (!result)
7918 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007919 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007920 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007921 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007922 if (!key || !value)
7923 goto failed1;
7924 if (PyDict_SetItem(result, key, value) == -1)
7925 goto failed1;
7926 Py_DECREF(key);
7927 Py_DECREF(value);
7928 }
7929 return result;
7930 failed1:
7931 Py_XDECREF(key);
7932 Py_XDECREF(value);
7933 Py_DECREF(result);
7934 return NULL;
7935 }
7936
7937 /* Create a three-level trie */
7938 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7939 16*count2 + 128*count3 - 1);
7940 if (!result)
7941 return PyErr_NoMemory();
7942 PyObject_Init(result, &EncodingMapType);
7943 mresult = (struct encoding_map*)result;
7944 mresult->count2 = count2;
7945 mresult->count3 = count3;
7946 mlevel1 = mresult->level1;
7947 mlevel2 = mresult->level23;
7948 mlevel3 = mresult->level23 + 16*count2;
7949 memcpy(mlevel1, level1, 32);
7950 memset(mlevel2, 0xFF, 16*count2);
7951 memset(mlevel3, 0, 128*count3);
7952 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007953 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007954 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007955 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7956 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007957 /* unmapped character */
7958 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007959 o1 = ch>>11;
7960 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007961 i2 = 16*mlevel1[o1] + o2;
7962 if (mlevel2[i2] == 0xFF)
7963 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02007964 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007965 i3 = 128*mlevel2[i2] + o3;
7966 mlevel3[i3] = i;
7967 }
7968 return result;
7969}
7970
7971static int
Victor Stinner22168992011-11-20 17:09:18 +01007972encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007973{
7974 struct encoding_map *map = (struct encoding_map*)mapping;
7975 int l1 = c>>11;
7976 int l2 = (c>>7) & 0xF;
7977 int l3 = c & 0x7F;
7978 int i;
7979
Victor Stinner22168992011-11-20 17:09:18 +01007980 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007981 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007982 if (c == 0)
7983 return 0;
7984 /* level 1*/
7985 i = map->level1[l1];
7986 if (i == 0xFF) {
7987 return -1;
7988 }
7989 /* level 2*/
7990 i = map->level23[16*i+l2];
7991 if (i == 0xFF) {
7992 return -1;
7993 }
7994 /* level 3 */
7995 i = map->level23[16*map->count2 + 128*i + l3];
7996 if (i == 0) {
7997 return -1;
7998 }
7999 return i;
8000}
8001
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008002/* Lookup the character ch in the mapping. If the character
8003 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008004 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008005static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008006charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008007{
Christian Heimes217cfd12007-12-02 14:31:20 +00008008 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008009 PyObject *x;
8010
8011 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008012 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008013 x = PyObject_GetItem(mapping, w);
8014 Py_DECREF(w);
8015 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008016 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8017 /* No mapping found means: mapping is undefined. */
8018 PyErr_Clear();
8019 x = Py_None;
8020 Py_INCREF(x);
8021 return x;
8022 } else
8023 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008024 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008025 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008026 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008027 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008028 long value = PyLong_AS_LONG(x);
8029 if (value < 0 || value > 255) {
8030 PyErr_SetString(PyExc_TypeError,
8031 "character mapping must be in range(256)");
8032 Py_DECREF(x);
8033 return NULL;
8034 }
8035 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008036 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008037 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008038 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008039 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008040 /* wrong return value */
8041 PyErr_Format(PyExc_TypeError,
8042 "character mapping must return integer, bytes or None, not %.400s",
8043 x->ob_type->tp_name);
8044 Py_DECREF(x);
8045 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008046 }
8047}
8048
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008049static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008050charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008051{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008052 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8053 /* exponentially overallocate to minimize reallocations */
8054 if (requiredsize < 2*outsize)
8055 requiredsize = 2*outsize;
8056 if (_PyBytes_Resize(outobj, requiredsize))
8057 return -1;
8058 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008059}
8060
Benjamin Peterson14339b62009-01-31 16:36:08 +00008061typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008062 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008063} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008064/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008065 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008066 space is available. Return a new reference to the object that
8067 was put in the output buffer, or Py_None, if the mapping was undefined
8068 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008069 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008070static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008071charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008072 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008073{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008074 PyObject *rep;
8075 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008076 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008077
Christian Heimes90aa7642007-12-19 02:45:37 +00008078 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008079 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008080 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008081 if (res == -1)
8082 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008083 if (outsize<requiredsize)
8084 if (charmapencode_resize(outobj, outpos, requiredsize))
8085 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008086 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008087 outstart[(*outpos)++] = (char)res;
8088 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008089 }
8090
8091 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008092 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008093 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008094 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008095 Py_DECREF(rep);
8096 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008097 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008098 if (PyLong_Check(rep)) {
8099 Py_ssize_t requiredsize = *outpos+1;
8100 if (outsize<requiredsize)
8101 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8102 Py_DECREF(rep);
8103 return enc_EXCEPTION;
8104 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008105 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008106 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008107 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008108 else {
8109 const char *repchars = PyBytes_AS_STRING(rep);
8110 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8111 Py_ssize_t requiredsize = *outpos+repsize;
8112 if (outsize<requiredsize)
8113 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8114 Py_DECREF(rep);
8115 return enc_EXCEPTION;
8116 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008117 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008118 memcpy(outstart + *outpos, repchars, repsize);
8119 *outpos += repsize;
8120 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008121 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008122 Py_DECREF(rep);
8123 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008124}
8125
8126/* handle an error in PyUnicode_EncodeCharmap
8127 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008128static int
8129charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008130 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008131 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008132 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008133 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008134{
8135 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008136 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008137 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008138 enum PyUnicode_Kind kind;
8139 void *data;
8140 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008141 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008142 Py_ssize_t collstartpos = *inpos;
8143 Py_ssize_t collendpos = *inpos+1;
8144 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008145 char *encoding = "charmap";
8146 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008147 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008148 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008149 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008150
Benjamin Petersonbac79492012-01-14 13:34:47 -05008151 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008152 return -1;
8153 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008154 /* find all unencodable characters */
8155 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008156 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008157 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008158 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008159 val = encoding_map_lookup(ch, mapping);
8160 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008161 break;
8162 ++collendpos;
8163 continue;
8164 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008165
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008166 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8167 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008168 if (rep==NULL)
8169 return -1;
8170 else if (rep!=Py_None) {
8171 Py_DECREF(rep);
8172 break;
8173 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008174 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008175 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008176 }
8177 /* cache callback name lookup
8178 * (if not done yet, i.e. it's the first error) */
8179 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008180 if ((errors==NULL) || (!strcmp(errors, "strict")))
8181 *known_errorHandler = 1;
8182 else if (!strcmp(errors, "replace"))
8183 *known_errorHandler = 2;
8184 else if (!strcmp(errors, "ignore"))
8185 *known_errorHandler = 3;
8186 else if (!strcmp(errors, "xmlcharrefreplace"))
8187 *known_errorHandler = 4;
8188 else
8189 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008190 }
8191 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008192 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008193 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008194 return -1;
8195 case 2: /* replace */
8196 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008197 x = charmapencode_output('?', mapping, res, respos);
8198 if (x==enc_EXCEPTION) {
8199 return -1;
8200 }
8201 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008202 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008203 return -1;
8204 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008205 }
8206 /* fall through */
8207 case 3: /* ignore */
8208 *inpos = collendpos;
8209 break;
8210 case 4: /* xmlcharrefreplace */
8211 /* generate replacement (temporarily (mis)uses p) */
8212 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008213 char buffer[2+29+1+1];
8214 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008215 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008216 for (cp = buffer; *cp; ++cp) {
8217 x = charmapencode_output(*cp, mapping, res, respos);
8218 if (x==enc_EXCEPTION)
8219 return -1;
8220 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008221 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008222 return -1;
8223 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008224 }
8225 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008226 *inpos = collendpos;
8227 break;
8228 default:
8229 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008230 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008231 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008232 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008233 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008234 if (PyBytes_Check(repunicode)) {
8235 /* Directly copy bytes result to output. */
8236 Py_ssize_t outsize = PyBytes_Size(*res);
8237 Py_ssize_t requiredsize;
8238 repsize = PyBytes_Size(repunicode);
8239 requiredsize = *respos + repsize;
8240 if (requiredsize > outsize)
8241 /* Make room for all additional bytes. */
8242 if (charmapencode_resize(res, respos, requiredsize)) {
8243 Py_DECREF(repunicode);
8244 return -1;
8245 }
8246 memcpy(PyBytes_AsString(*res) + *respos,
8247 PyBytes_AsString(repunicode), repsize);
8248 *respos += repsize;
8249 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008250 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008251 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008252 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008253 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008254 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008255 Py_DECREF(repunicode);
8256 return -1;
8257 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008258 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008259 data = PyUnicode_DATA(repunicode);
8260 kind = PyUnicode_KIND(repunicode);
8261 for (index = 0; index < repsize; index++) {
8262 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8263 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008264 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008265 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008266 return -1;
8267 }
8268 else if (x==enc_FAILED) {
8269 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008270 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008271 return -1;
8272 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008273 }
8274 *inpos = newpos;
8275 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008276 }
8277 return 0;
8278}
8279
Alexander Belopolsky40018472011-02-26 01:02:56 +00008280PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008281_PyUnicode_EncodeCharmap(PyObject *unicode,
8282 PyObject *mapping,
8283 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008284{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008285 /* output object */
8286 PyObject *res = NULL;
8287 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008288 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008289 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008290 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008291 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008292 PyObject *errorHandler = NULL;
8293 PyObject *exc = NULL;
8294 /* the following variable is used for caching string comparisons
8295 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8296 * 3=ignore, 4=xmlcharrefreplace */
8297 int known_errorHandler = -1;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008298 void *data;
8299 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008300
Benjamin Petersonbac79492012-01-14 13:34:47 -05008301 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008302 return NULL;
8303 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008304 data = PyUnicode_DATA(unicode);
8305 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008306
Guido van Rossumd57fd912000-03-10 22:53:23 +00008307 /* Default to Latin-1 */
8308 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008309 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008310
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008311 /* allocate enough for a simple encoding without
8312 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008313 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008314 if (res == NULL)
8315 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008316 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008317 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008318
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008319 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008320 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008321 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008322 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008323 if (x==enc_EXCEPTION) /* error */
8324 goto onError;
8325 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008326 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008327 &exc,
8328 &known_errorHandler, &errorHandler, errors,
8329 &res, &respos)) {
8330 goto onError;
8331 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008332 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008333 else
8334 /* done with this character => adjust input position */
8335 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008336 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008337
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008338 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008339 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008340 if (_PyBytes_Resize(&res, respos) < 0)
8341 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008342
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008343 Py_XDECREF(exc);
8344 Py_XDECREF(errorHandler);
8345 return res;
8346
Benjamin Peterson29060642009-01-31 22:14:21 +00008347 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008348 Py_XDECREF(res);
8349 Py_XDECREF(exc);
8350 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008351 return NULL;
8352}
8353
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008354/* Deprecated */
8355PyObject *
8356PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8357 Py_ssize_t size,
8358 PyObject *mapping,
8359 const char *errors)
8360{
8361 PyObject *result;
8362 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8363 if (unicode == NULL)
8364 return NULL;
8365 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8366 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008367 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008368}
8369
Alexander Belopolsky40018472011-02-26 01:02:56 +00008370PyObject *
8371PyUnicode_AsCharmapString(PyObject *unicode,
8372 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008373{
8374 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008375 PyErr_BadArgument();
8376 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008377 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008378 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008379}
8380
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008381/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008382static void
8383make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008384 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008385 Py_ssize_t startpos, Py_ssize_t endpos,
8386 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008387{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008388 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008389 *exceptionObject = _PyUnicodeTranslateError_Create(
8390 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008391 }
8392 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008393 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8394 goto onError;
8395 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8396 goto onError;
8397 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8398 goto onError;
8399 return;
8400 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008401 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008402 }
8403}
8404
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008405/* error handling callback helper:
8406 build arguments, call the callback and check the arguments,
8407 put the result into newpos and return the replacement string, which
8408 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008409static PyObject *
8410unicode_translate_call_errorhandler(const char *errors,
8411 PyObject **errorHandler,
8412 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008413 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008414 Py_ssize_t startpos, Py_ssize_t endpos,
8415 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008416{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008417 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008418
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008419 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008420 PyObject *restuple;
8421 PyObject *resunicode;
8422
8423 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008424 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008425 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008426 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008427 }
8428
8429 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008430 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008431 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008432 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008433
8434 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008435 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008436 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008437 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008438 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008439 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008440 Py_DECREF(restuple);
8441 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008442 }
8443 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008444 &resunicode, &i_newpos)) {
8445 Py_DECREF(restuple);
8446 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008447 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008448 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008449 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008450 else
8451 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008452 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008453 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008454 Py_DECREF(restuple);
8455 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008456 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008457 Py_INCREF(resunicode);
8458 Py_DECREF(restuple);
8459 return resunicode;
8460}
8461
8462/* Lookup the character ch in the mapping and put the result in result,
8463 which must be decrefed by the caller.
8464 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008465static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008466charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008467{
Christian Heimes217cfd12007-12-02 14:31:20 +00008468 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008469 PyObject *x;
8470
8471 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008472 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008473 x = PyObject_GetItem(mapping, w);
8474 Py_DECREF(w);
8475 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008476 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8477 /* No mapping found means: use 1:1 mapping. */
8478 PyErr_Clear();
8479 *result = NULL;
8480 return 0;
8481 } else
8482 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008483 }
8484 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008485 *result = x;
8486 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008487 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008488 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008489 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008490 if (value < 0 || value > MAX_UNICODE) {
8491 PyErr_Format(PyExc_ValueError,
8492 "character mapping must be in range(0x%x)",
8493 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008494 Py_DECREF(x);
8495 return -1;
8496 }
8497 *result = x;
8498 return 0;
8499 }
8500 else if (PyUnicode_Check(x)) {
8501 *result = x;
8502 return 0;
8503 }
8504 else {
8505 /* wrong return value */
8506 PyErr_SetString(PyExc_TypeError,
8507 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008508 Py_DECREF(x);
8509 return -1;
8510 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008511}
Victor Stinner1194ea02014-04-04 19:37:40 +02008512
8513/* lookup the character, write the result into the writer.
8514 Return 1 if the result was written into the writer, return 0 if the mapping
8515 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008516static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008517charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8518 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008519{
Victor Stinner1194ea02014-04-04 19:37:40 +02008520 PyObject *item;
8521
8522 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008523 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008524
8525 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008526 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008527 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008528 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008529 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008530 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008531 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008532
8533 if (item == Py_None) {
8534 Py_DECREF(item);
8535 return 0;
8536 }
8537
8538 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008539 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8540 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8541 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008542 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8543 Py_DECREF(item);
8544 return -1;
8545 }
8546 Py_DECREF(item);
8547 return 1;
8548 }
8549
8550 if (!PyUnicode_Check(item)) {
8551 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008552 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008553 }
8554
8555 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8556 Py_DECREF(item);
8557 return -1;
8558 }
8559
8560 Py_DECREF(item);
8561 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008562}
8563
Victor Stinner89a76ab2014-04-05 11:44:04 +02008564static int
8565unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8566 Py_UCS1 *translate)
8567{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008568 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008569 int ret = 0;
8570
Victor Stinner89a76ab2014-04-05 11:44:04 +02008571 if (charmaptranslate_lookup(ch, mapping, &item)) {
8572 return -1;
8573 }
8574
8575 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008576 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008577 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008578 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008579 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008580 /* not found => default to 1:1 mapping */
8581 translate[ch] = ch;
8582 return 1;
8583 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008584 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008585 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008586 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8587 used it */
8588 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008589 /* invalid character or character outside ASCII:
8590 skip the fast translate */
8591 goto exit;
8592 }
8593 translate[ch] = (Py_UCS1)replace;
8594 }
8595 else if (PyUnicode_Check(item)) {
8596 Py_UCS4 replace;
8597
8598 if (PyUnicode_READY(item) == -1) {
8599 Py_DECREF(item);
8600 return -1;
8601 }
8602 if (PyUnicode_GET_LENGTH(item) != 1)
8603 goto exit;
8604
8605 replace = PyUnicode_READ_CHAR(item, 0);
8606 if (replace > 127)
8607 goto exit;
8608 translate[ch] = (Py_UCS1)replace;
8609 }
8610 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008611 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008612 goto exit;
8613 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008614 ret = 1;
8615
Benjamin Peterson1365de72014-04-07 20:15:41 -04008616 exit:
8617 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008618 return ret;
8619}
8620
8621/* Fast path for ascii => ascii translation. Return 1 if the whole string
8622 was translated into writer, return 0 if the input string was partially
8623 translated into writer, raise an exception and return -1 on error. */
8624static int
8625unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner872b2912014-04-05 14:27:07 +02008626 _PyUnicodeWriter *writer, int ignore)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008627{
Victor Stinner872b2912014-04-05 14:27:07 +02008628 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008629 Py_ssize_t len;
8630 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008631 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008632
8633 if (PyUnicode_READY(input) == -1)
8634 return -1;
8635 if (!PyUnicode_IS_ASCII(input))
8636 return 0;
8637 len = PyUnicode_GET_LENGTH(input);
8638
Victor Stinner872b2912014-04-05 14:27:07 +02008639 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008640
8641 in = PyUnicode_1BYTE_DATA(input);
8642 end = in + len;
8643
8644 assert(PyUnicode_IS_ASCII(writer->buffer));
8645 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8646 out = PyUnicode_1BYTE_DATA(writer->buffer);
8647
Victor Stinner872b2912014-04-05 14:27:07 +02008648 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008649 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008650 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008651 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008652 int translate = unicode_fast_translate_lookup(mapping, ch,
8653 ascii_table);
8654 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008655 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008656 if (translate == 0)
8657 goto exit;
8658 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008659 }
Victor Stinner872b2912014-04-05 14:27:07 +02008660 if (ch2 == 0xfe) {
8661 if (ignore)
8662 continue;
8663 goto exit;
8664 }
8665 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008666 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008667 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008668 }
Victor Stinner872b2912014-04-05 14:27:07 +02008669 res = 1;
8670
8671exit:
8672 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
8673 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008674}
8675
Alexander Belopolsky40018472011-02-26 01:02:56 +00008676PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008677_PyUnicode_TranslateCharmap(PyObject *input,
8678 PyObject *mapping,
8679 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008680{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008681 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008682 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008683 Py_ssize_t size, i;
8684 int kind;
8685 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008686 _PyUnicodeWriter writer;
8687 /* error handler */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008688 char *reason = "character maps to <undefined>";
8689 PyObject *errorHandler = NULL;
8690 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008691 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008692 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008693
Guido van Rossumd57fd912000-03-10 22:53:23 +00008694 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008695 PyErr_BadArgument();
8696 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008697 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008698
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008699 if (PyUnicode_READY(input) == -1)
8700 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008701 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008702 kind = PyUnicode_KIND(input);
8703 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008704
8705 if (size == 0) {
8706 Py_INCREF(input);
8707 return input;
8708 }
8709
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008710 /* allocate enough for a simple 1:1 translation without
8711 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008712 _PyUnicodeWriter_Init(&writer);
8713 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008714 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008715
Victor Stinner872b2912014-04-05 14:27:07 +02008716 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
8717
8718 res = unicode_fast_translate(input, mapping, &writer, ignore);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008719 if (res < 0) {
8720 _PyUnicodeWriter_Dealloc(&writer);
8721 return NULL;
8722 }
8723 if (res == 1)
8724 return _PyUnicodeWriter_Finish(&writer);
8725
Victor Stinner89a76ab2014-04-05 11:44:04 +02008726 i = writer.pos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008727 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008728 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008729 int translate;
8730 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8731 Py_ssize_t newpos;
8732 /* startpos for collecting untranslatable chars */
8733 Py_ssize_t collstart;
8734 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02008735 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008736
Victor Stinner1194ea02014-04-04 19:37:40 +02008737 ch = PyUnicode_READ(kind, data, i);
8738 translate = charmaptranslate_output(ch, mapping, &writer);
8739 if (translate < 0)
8740 goto onError;
8741
8742 if (translate != 0) {
8743 /* it worked => adjust input pointer */
8744 ++i;
8745 continue;
8746 }
8747
8748 /* untranslatable character */
8749 collstart = i;
8750 collend = i+1;
8751
8752 /* find all untranslatable characters */
8753 while (collend < size) {
8754 PyObject *x;
8755 ch = PyUnicode_READ(kind, data, collend);
8756 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008757 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02008758 Py_XDECREF(x);
8759 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008760 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02008761 ++collend;
8762 }
8763
8764 if (ignore) {
8765 i = collend;
8766 }
8767 else {
8768 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
8769 reason, input, &exc,
8770 collstart, collend, &newpos);
8771 if (repunicode == NULL)
8772 goto onError;
8773 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008774 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02008775 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008776 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008777 Py_DECREF(repunicode);
8778 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008779 }
8780 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008781 Py_XDECREF(exc);
8782 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02008783 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008784
Benjamin Peterson29060642009-01-31 22:14:21 +00008785 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02008786 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008787 Py_XDECREF(exc);
8788 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008789 return NULL;
8790}
8791
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008792/* Deprecated. Use PyUnicode_Translate instead. */
8793PyObject *
8794PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8795 Py_ssize_t size,
8796 PyObject *mapping,
8797 const char *errors)
8798{
Christian Heimes5f520f42012-09-11 14:03:25 +02008799 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008800 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8801 if (!unicode)
8802 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02008803 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8804 Py_DECREF(unicode);
8805 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008806}
8807
Alexander Belopolsky40018472011-02-26 01:02:56 +00008808PyObject *
8809PyUnicode_Translate(PyObject *str,
8810 PyObject *mapping,
8811 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008812{
8813 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008814
Guido van Rossumd57fd912000-03-10 22:53:23 +00008815 str = PyUnicode_FromObject(str);
8816 if (str == NULL)
Christian Heimes5f520f42012-09-11 14:03:25 +02008817 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008818 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008819 Py_DECREF(str);
8820 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008821}
Tim Petersced69f82003-09-16 20:30:58 +00008822
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008823static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008824fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008825{
8826 /* No need to call PyUnicode_READY(self) because this function is only
8827 called as a callback from fixup() which does it already. */
8828 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8829 const int kind = PyUnicode_KIND(self);
8830 void *data = PyUnicode_DATA(self);
Victor Stinnere6abb482012-05-02 01:15:40 +02008831 Py_UCS4 maxchar = 127, ch, fixed;
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008832 int modified = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008833 Py_ssize_t i;
8834
8835 for (i = 0; i < len; ++i) {
8836 ch = PyUnicode_READ(kind, data, i);
8837 fixed = 0;
8838 if (ch > 127) {
8839 if (Py_UNICODE_ISSPACE(ch))
8840 fixed = ' ';
8841 else {
8842 const int decimal = Py_UNICODE_TODECIMAL(ch);
8843 if (decimal >= 0)
8844 fixed = '0' + decimal;
8845 }
8846 if (fixed != 0) {
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008847 modified = 1;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008848 maxchar = Py_MAX(maxchar, fixed);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008849 PyUnicode_WRITE(kind, data, i, fixed);
8850 }
Victor Stinnere6abb482012-05-02 01:15:40 +02008851 else
Benjamin Peterson7e303732013-06-10 09:19:46 -07008852 maxchar = Py_MAX(maxchar, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008853 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008854 }
8855
Benjamin Peterson821e4cf2012-01-12 15:40:18 -05008856 return (modified) ? maxchar : 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008857}
8858
8859PyObject *
8860_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8861{
8862 if (!PyUnicode_Check(unicode)) {
8863 PyErr_BadInternalCall();
8864 return NULL;
8865 }
8866 if (PyUnicode_READY(unicode) == -1)
8867 return NULL;
8868 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8869 /* If the string is already ASCII, just return the same string */
8870 Py_INCREF(unicode);
8871 return unicode;
8872 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008873 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008874}
8875
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008876PyObject *
8877PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8878 Py_ssize_t length)
8879{
Victor Stinnerf0124502011-11-21 23:12:56 +01008880 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008881 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01008882 Py_UCS4 maxchar;
8883 enum PyUnicode_Kind kind;
8884 void *data;
8885
Victor Stinner99d7ad02012-02-22 13:37:39 +01008886 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008887 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02008888 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008889 if (ch > 127) {
8890 int decimal = Py_UNICODE_TODECIMAL(ch);
8891 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01008892 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07008893 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008894 }
8895 }
Victor Stinnerf0124502011-11-21 23:12:56 +01008896
8897 /* Copy to a new string */
8898 decimal = PyUnicode_New(length, maxchar);
8899 if (decimal == NULL)
8900 return decimal;
8901 kind = PyUnicode_KIND(decimal);
8902 data = PyUnicode_DATA(decimal);
8903 /* Iterate over code points */
8904 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02008905 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01008906 if (ch > 127) {
8907 int decimal = Py_UNICODE_TODECIMAL(ch);
8908 if (decimal >= 0)
8909 ch = '0' + decimal;
8910 }
8911 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008912 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01008913 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008914}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008915/* --- Decimal Encoder ---------------------------------------------------- */
8916
Alexander Belopolsky40018472011-02-26 01:02:56 +00008917int
8918PyUnicode_EncodeDecimal(Py_UNICODE *s,
8919 Py_ssize_t length,
8920 char *output,
8921 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008922{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008923 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01008924 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01008925 enum PyUnicode_Kind kind;
8926 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008927
8928 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008929 PyErr_BadArgument();
8930 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008931 }
8932
Victor Stinner42bf7752011-11-21 22:52:58 +01008933 unicode = PyUnicode_FromUnicode(s, length);
8934 if (unicode == NULL)
8935 return -1;
8936
Benjamin Petersonbac79492012-01-14 13:34:47 -05008937 if (PyUnicode_READY(unicode) == -1) {
Victor Stinner6345be92011-11-25 20:09:01 +01008938 Py_DECREF(unicode);
8939 return -1;
8940 }
Victor Stinner42bf7752011-11-21 22:52:58 +01008941 kind = PyUnicode_KIND(unicode);
8942 data = PyUnicode_DATA(unicode);
8943
Victor Stinnerb84d7232011-11-22 01:50:07 +01008944 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01008945 PyObject *exc;
8946 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00008947 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01008948 Py_ssize_t startpos;
8949
8950 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00008951
Benjamin Peterson29060642009-01-31 22:14:21 +00008952 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008953 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01008954 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008955 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008956 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008957 decimal = Py_UNICODE_TODECIMAL(ch);
8958 if (decimal >= 0) {
8959 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008960 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008961 continue;
8962 }
8963 if (0 < ch && ch < 256) {
8964 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01008965 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00008966 continue;
8967 }
Victor Stinner6345be92011-11-25 20:09:01 +01008968
Victor Stinner42bf7752011-11-21 22:52:58 +01008969 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01008970 exc = NULL;
8971 raise_encode_exception(&exc, "decimal", unicode,
8972 startpos, startpos+1,
8973 "invalid decimal Unicode string");
8974 Py_XDECREF(exc);
8975 Py_DECREF(unicode);
8976 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008977 }
8978 /* 0-terminate the output string */
8979 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01008980 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008981 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008982}
8983
Guido van Rossumd57fd912000-03-10 22:53:23 +00008984/* --- Helpers ------------------------------------------------------------ */
8985
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02008986/* helper macro to fixup start/end slice values */
8987#define ADJUST_INDICES(start, end, len) \
8988 if (end > len) \
8989 end = len; \
8990 else if (end < 0) { \
8991 end += len; \
8992 if (end < 0) \
8993 end = 0; \
8994 } \
8995 if (start < 0) { \
8996 start += len; \
8997 if (start < 0) \
8998 start = 0; \
8999 }
9000
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009001static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02009002any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009003 Py_ssize_t start,
9004 Py_ssize_t end)
9005{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009006 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009007 void *buf1, *buf2;
9008 Py_ssize_t len1, len2, result;
9009
9010 kind1 = PyUnicode_KIND(s1);
9011 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009012 if (kind1 < kind2)
9013 return -1;
9014
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009015 len1 = PyUnicode_GET_LENGTH(s1);
9016 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009017 ADJUST_INDICES(start, end, len1);
9018 if (end - start < len2)
9019 return -1;
9020
9021 buf1 = PyUnicode_DATA(s1);
9022 buf2 = PyUnicode_DATA(s2);
9023 if (len2 == 1) {
9024 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9025 result = findchar((const char *)buf1 + kind1*start,
9026 kind1, end - start, ch, direction);
9027 if (result == -1)
9028 return -1;
9029 else
9030 return start + result;
9031 }
9032
9033 if (kind2 != kind1) {
9034 buf2 = _PyUnicode_AsKind(s2, kind1);
9035 if (!buf2)
9036 return -2;
9037 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009038
Victor Stinner794d5672011-10-10 03:21:36 +02009039 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009040 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009041 case PyUnicode_1BYTE_KIND:
9042 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9043 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9044 else
9045 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9046 break;
9047 case PyUnicode_2BYTE_KIND:
9048 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9049 break;
9050 case PyUnicode_4BYTE_KIND:
9051 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9052 break;
9053 default:
9054 assert(0); result = -2;
9055 }
9056 }
9057 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009058 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009059 case PyUnicode_1BYTE_KIND:
9060 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9061 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9062 else
9063 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9064 break;
9065 case PyUnicode_2BYTE_KIND:
9066 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9067 break;
9068 case PyUnicode_4BYTE_KIND:
9069 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9070 break;
9071 default:
9072 assert(0); result = -2;
9073 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009074 }
9075
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009076 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009077 PyMem_Free(buf2);
9078
9079 return result;
9080}
9081
9082Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009083_PyUnicode_InsertThousandsGrouping(
9084 PyObject *unicode, Py_ssize_t index,
9085 Py_ssize_t n_buffer,
9086 void *digits, Py_ssize_t n_digits,
9087 Py_ssize_t min_width,
9088 const char *grouping, PyObject *thousands_sep,
9089 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009090{
Victor Stinner41a863c2012-02-24 00:37:51 +01009091 unsigned int kind, thousands_sep_kind;
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009092 char *data, *thousands_sep_data;
Victor Stinner41a863c2012-02-24 00:37:51 +01009093 Py_ssize_t thousands_sep_len;
9094 Py_ssize_t len;
9095
9096 if (unicode != NULL) {
9097 kind = PyUnicode_KIND(unicode);
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009098 data = (char *) PyUnicode_DATA(unicode) + index * kind;
Victor Stinner41a863c2012-02-24 00:37:51 +01009099 }
9100 else {
9101 kind = PyUnicode_1BYTE_KIND;
9102 data = NULL;
9103 }
9104 thousands_sep_kind = PyUnicode_KIND(thousands_sep);
9105 thousands_sep_data = PyUnicode_DATA(thousands_sep);
9106 thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9107 if (unicode != NULL && thousands_sep_kind != kind) {
Victor Stinner90f50d42012-02-24 01:44:47 +01009108 if (thousands_sep_kind < kind) {
9109 thousands_sep_data = _PyUnicode_AsKind(thousands_sep, kind);
9110 if (!thousands_sep_data)
9111 return -1;
9112 }
9113 else {
9114 data = _PyUnicode_AsKind(unicode, thousands_sep_kind);
9115 if (!data)
9116 return -1;
9117 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009118 }
9119
Benjamin Petersonead6b532011-12-20 17:23:42 -06009120 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009121 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009122 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
Victor Stinner41a863c2012-02-24 00:37:51 +01009123 len = asciilib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009124 (Py_UCS1 *) data, n_buffer, (Py_UCS1 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009125 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009126 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009127 else
Victor Stinner41a863c2012-02-24 00:37:51 +01009128 len = ucs1lib_InsertThousandsGrouping(
Victor Stinnerc3cec782011-10-05 21:24:08 +02009129 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009130 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009131 (Py_UCS1 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009132 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009133 case PyUnicode_2BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009134 len = ucs2lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009135 (Py_UCS2 *) data, n_buffer, (Py_UCS2 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009136 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009137 (Py_UCS2 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009138 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009139 case PyUnicode_4BYTE_KIND:
Victor Stinner41a863c2012-02-24 00:37:51 +01009140 len = ucs4lib_InsertThousandsGrouping(
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009141 (Py_UCS4 *) data, n_buffer, (Py_UCS4 *) digits, n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009142 min_width, grouping,
Antoine Pitrou842c0f12012-02-24 13:30:46 +01009143 (Py_UCS4 *) thousands_sep_data, thousands_sep_len);
Victor Stinner41a863c2012-02-24 00:37:51 +01009144 break;
9145 default:
9146 assert(0);
9147 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009148 }
Victor Stinner90f50d42012-02-24 01:44:47 +01009149 if (unicode != NULL && thousands_sep_kind != kind) {
9150 if (thousands_sep_kind < kind)
9151 PyMem_Free(thousands_sep_data);
9152 else
9153 PyMem_Free(data);
9154 }
Victor Stinner41a863c2012-02-24 00:37:51 +01009155 if (unicode == NULL) {
9156 *maxchar = 127;
9157 if (len != n_digits) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009158 *maxchar = Py_MAX(*maxchar,
Victor Stinnere6abb482012-05-02 01:15:40 +02009159 PyUnicode_MAX_CHAR_VALUE(thousands_sep));
Victor Stinner41a863c2012-02-24 00:37:51 +01009160 }
9161 }
9162 return len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009163}
9164
9165
Alexander Belopolsky40018472011-02-26 01:02:56 +00009166Py_ssize_t
9167PyUnicode_Count(PyObject *str,
9168 PyObject *substr,
9169 Py_ssize_t start,
9170 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009171{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009172 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009173 PyObject* str_obj;
9174 PyObject* sub_obj;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009175 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009176 void *buf1 = NULL, *buf2 = NULL;
9177 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009178
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009179 str_obj = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009180 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +00009181 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009182 sub_obj = PyUnicode_FromObject(substr);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009183 if (!sub_obj) {
9184 Py_DECREF(str_obj);
9185 return -1;
9186 }
Benjamin Peterson4c13a4a2012-01-02 09:07:38 -06009187 if (PyUnicode_READY(sub_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
Benjamin Peterson5e458f52012-01-02 10:12:13 -06009188 Py_DECREF(sub_obj);
Benjamin Peterson29060642009-01-31 22:14:21 +00009189 Py_DECREF(str_obj);
9190 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009191 }
Tim Petersced69f82003-09-16 20:30:58 +00009192
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009193 kind1 = PyUnicode_KIND(str_obj);
9194 kind2 = PyUnicode_KIND(sub_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009195 if (kind1 < kind2) {
9196 Py_DECREF(sub_obj);
9197 Py_DECREF(str_obj);
9198 return 0;
Benjamin Peterson1ff2e352012-05-11 17:41:20 -05009199 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009200
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009201 len1 = PyUnicode_GET_LENGTH(str_obj);
9202 len2 = PyUnicode_GET_LENGTH(sub_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009203 ADJUST_INDICES(start, end, len1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009204 if (end - start < len2) {
9205 Py_DECREF(sub_obj);
9206 Py_DECREF(str_obj);
9207 return 0;
9208 }
9209
9210 buf1 = PyUnicode_DATA(str_obj);
9211 buf2 = PyUnicode_DATA(sub_obj);
9212 if (kind2 != kind1) {
9213 buf2 = _PyUnicode_AsKind(sub_obj, kind1);
9214 if (!buf2)
9215 goto onError;
9216 }
9217
9218 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009219 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009220 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9221 result = asciilib_count(
9222 ((Py_UCS1*)buf1) + start, end - start,
9223 buf2, len2, PY_SSIZE_T_MAX
9224 );
9225 else
9226 result = ucs1lib_count(
9227 ((Py_UCS1*)buf1) + start, end - start,
9228 buf2, len2, PY_SSIZE_T_MAX
9229 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009230 break;
9231 case PyUnicode_2BYTE_KIND:
9232 result = ucs2lib_count(
9233 ((Py_UCS2*)buf1) + start, end - start,
9234 buf2, len2, PY_SSIZE_T_MAX
9235 );
9236 break;
9237 case PyUnicode_4BYTE_KIND:
9238 result = ucs4lib_count(
9239 ((Py_UCS4*)buf1) + start, end - start,
9240 buf2, len2, PY_SSIZE_T_MAX
9241 );
9242 break;
9243 default:
9244 assert(0); result = 0;
9245 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009246
9247 Py_DECREF(sub_obj);
9248 Py_DECREF(str_obj);
9249
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009250 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009251 PyMem_Free(buf2);
9252
Guido van Rossumd57fd912000-03-10 22:53:23 +00009253 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009254 onError:
9255 Py_DECREF(sub_obj);
9256 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009257 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009258 PyMem_Free(buf2);
9259 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009260}
9261
Alexander Belopolsky40018472011-02-26 01:02:56 +00009262Py_ssize_t
9263PyUnicode_Find(PyObject *str,
9264 PyObject *sub,
9265 Py_ssize_t start,
9266 Py_ssize_t end,
9267 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009268{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009269 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009270
Guido van Rossumd57fd912000-03-10 22:53:23 +00009271 str = PyUnicode_FromObject(str);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009272 if (!str)
Benjamin Peterson29060642009-01-31 22:14:21 +00009273 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009274 sub = PyUnicode_FromObject(sub);
Benjamin Peterson22a29702012-01-02 09:00:30 -06009275 if (!sub) {
9276 Py_DECREF(str);
9277 return -2;
9278 }
9279 if (PyUnicode_READY(sub) == -1 || PyUnicode_READY(str) == -1) {
9280 Py_DECREF(sub);
Benjamin Peterson29060642009-01-31 22:14:21 +00009281 Py_DECREF(str);
9282 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009283 }
Tim Petersced69f82003-09-16 20:30:58 +00009284
Victor Stinner794d5672011-10-10 03:21:36 +02009285 result = any_find_slice(direction,
9286 str, sub, start, end
9287 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009288
Guido van Rossumd57fd912000-03-10 22:53:23 +00009289 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009290 Py_DECREF(sub);
9291
Guido van Rossumd57fd912000-03-10 22:53:23 +00009292 return result;
9293}
9294
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009295Py_ssize_t
9296PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9297 Py_ssize_t start, Py_ssize_t end,
9298 int direction)
9299{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009300 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009301 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009302 if (PyUnicode_READY(str) == -1)
9303 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009304 if (start < 0 || end < 0) {
9305 PyErr_SetString(PyExc_IndexError, "string index out of range");
9306 return -2;
9307 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009308 if (end > PyUnicode_GET_LENGTH(str))
9309 end = PyUnicode_GET_LENGTH(str);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009310 if (start >= end)
9311 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009312 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009313 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9314 kind, end-start, ch, direction);
9315 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009316 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009317 else
9318 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009319}
9320
Alexander Belopolsky40018472011-02-26 01:02:56 +00009321static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009322tailmatch(PyObject *self,
9323 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009324 Py_ssize_t start,
9325 Py_ssize_t end,
9326 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009327{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009328 int kind_self;
9329 int kind_sub;
9330 void *data_self;
9331 void *data_sub;
9332 Py_ssize_t offset;
9333 Py_ssize_t i;
9334 Py_ssize_t end_sub;
9335
9336 if (PyUnicode_READY(self) == -1 ||
9337 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009338 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009339
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009340 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9341 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009342 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009343 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009344
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009345 if (PyUnicode_GET_LENGTH(substring) == 0)
9346 return 1;
9347
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009348 kind_self = PyUnicode_KIND(self);
9349 data_self = PyUnicode_DATA(self);
9350 kind_sub = PyUnicode_KIND(substring);
9351 data_sub = PyUnicode_DATA(substring);
9352 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9353
9354 if (direction > 0)
9355 offset = end;
9356 else
9357 offset = start;
9358
9359 if (PyUnicode_READ(kind_self, data_self, offset) ==
9360 PyUnicode_READ(kind_sub, data_sub, 0) &&
9361 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9362 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9363 /* If both are of the same kind, memcmp is sufficient */
9364 if (kind_self == kind_sub) {
9365 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009366 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009367 data_sub,
9368 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009369 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009370 }
9371 /* otherwise we have to compare each character by first accesing it */
9372 else {
9373 /* We do not need to compare 0 and len(substring)-1 because
9374 the if statement above ensured already that they are equal
9375 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009376 for (i = 1; i < end_sub; ++i) {
9377 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9378 PyUnicode_READ(kind_sub, data_sub, i))
9379 return 0;
9380 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009381 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009382 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009383 }
9384
9385 return 0;
9386}
9387
Alexander Belopolsky40018472011-02-26 01:02:56 +00009388Py_ssize_t
9389PyUnicode_Tailmatch(PyObject *str,
9390 PyObject *substr,
9391 Py_ssize_t start,
9392 Py_ssize_t end,
9393 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009394{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009395 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009396
Guido van Rossumd57fd912000-03-10 22:53:23 +00009397 str = PyUnicode_FromObject(str);
9398 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009399 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009400 substr = PyUnicode_FromObject(substr);
9401 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009402 Py_DECREF(str);
9403 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009404 }
Tim Petersced69f82003-09-16 20:30:58 +00009405
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009406 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009407 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009408 Py_DECREF(str);
9409 Py_DECREF(substr);
9410 return result;
9411}
9412
Guido van Rossumd57fd912000-03-10 22:53:23 +00009413/* Apply fixfct filter to the Unicode object self and return a
9414 reference to the modified object */
9415
Alexander Belopolsky40018472011-02-26 01:02:56 +00009416static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009417fixup(PyObject *self,
9418 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009419{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009420 PyObject *u;
9421 Py_UCS4 maxchar_old, maxchar_new = 0;
Victor Stinnereaab6042011-12-11 22:22:39 +01009422 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009423
Victor Stinnerbf6e5602011-12-12 01:53:47 +01009424 u = _PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009425 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009426 return NULL;
Victor Stinner87af4f22011-11-21 23:03:47 +01009427 maxchar_old = PyUnicode_MAX_CHAR_VALUE(u);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009428
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009429 /* fix functions return the new maximum character in a string,
9430 if the kind of the resulting unicode object does not change,
9431 everything is fine. Otherwise we need to change the string kind
9432 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009433 maxchar_new = fixfct(u);
Victor Stinnereaab6042011-12-11 22:22:39 +01009434
9435 if (maxchar_new == 0) {
9436 /* no changes */;
9437 if (PyUnicode_CheckExact(self)) {
9438 Py_DECREF(u);
9439 Py_INCREF(self);
9440 return self;
9441 }
9442 else
9443 return u;
9444 }
9445
Victor Stinnere6abb482012-05-02 01:15:40 +02009446 maxchar_new = align_maxchar(maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009447
Victor Stinnereaab6042011-12-11 22:22:39 +01009448 if (maxchar_new == maxchar_old)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009449 return u;
Victor Stinnereaab6042011-12-11 22:22:39 +01009450
9451 /* In case the maximum character changed, we need to
9452 convert the string to the new category. */
9453 v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
9454 if (v == NULL) {
9455 Py_DECREF(u);
9456 return NULL;
9457 }
9458 if (maxchar_new > maxchar_old) {
9459 /* If the maxchar increased so that the kind changed, not all
9460 characters are representable anymore and we need to fix the
9461 string again. This only happens in very few cases. */
Victor Stinnerd3f08822012-05-29 12:57:52 +02009462 _PyUnicode_FastCopyCharacters(v, 0,
9463 self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinnereaab6042011-12-11 22:22:39 +01009464 maxchar_old = fixfct(v);
9465 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009466 }
9467 else {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009468 _PyUnicode_FastCopyCharacters(v, 0,
9469 u, 0, PyUnicode_GET_LENGTH(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009470 }
Victor Stinnereaab6042011-12-11 22:22:39 +01009471 Py_DECREF(u);
9472 assert(_PyUnicode_CheckConsistency(v, 1));
9473 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009474}
9475
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009476static PyObject *
9477ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009478{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009479 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9480 char *resdata, *data = PyUnicode_DATA(self);
9481 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009482
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009483 res = PyUnicode_New(len, 127);
9484 if (res == NULL)
9485 return NULL;
9486 resdata = PyUnicode_DATA(res);
9487 if (lower)
9488 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009489 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009490 _Py_bytes_upper(resdata, data, len);
9491 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009492}
9493
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009494static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009495handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009496{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009497 Py_ssize_t j;
9498 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009499 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009500 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009501
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009502 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9503
9504 where ! is a negation and \p{xxx} is a character with property xxx.
9505 */
9506 for (j = i - 1; j >= 0; j--) {
9507 c = PyUnicode_READ(kind, data, j);
9508 if (!_PyUnicode_IsCaseIgnorable(c))
9509 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009510 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009511 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9512 if (final_sigma) {
9513 for (j = i + 1; j < length; j++) {
9514 c = PyUnicode_READ(kind, data, j);
9515 if (!_PyUnicode_IsCaseIgnorable(c))
9516 break;
9517 }
9518 final_sigma = j == length || !_PyUnicode_IsCased(c);
9519 }
9520 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009521}
9522
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009523static int
9524lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9525 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009526{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009527 /* Obscure special case. */
9528 if (c == 0x3A3) {
9529 mapped[0] = handle_capital_sigma(kind, data, length, i);
9530 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009531 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009532 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009533}
9534
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009535static Py_ssize_t
9536do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009537{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009538 Py_ssize_t i, k = 0;
9539 int n_res, j;
9540 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009541
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009542 c = PyUnicode_READ(kind, data, 0);
9543 n_res = _PyUnicode_ToUpperFull(c, mapped);
9544 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009545 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009546 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009547 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009548 for (i = 1; i < length; i++) {
9549 c = PyUnicode_READ(kind, data, i);
9550 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9551 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009552 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009553 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009554 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009555 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009556 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009557}
9558
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009559static Py_ssize_t
9560do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9561 Py_ssize_t i, k = 0;
9562
9563 for (i = 0; i < length; i++) {
9564 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9565 int n_res, j;
9566 if (Py_UNICODE_ISUPPER(c)) {
9567 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9568 }
9569 else if (Py_UNICODE_ISLOWER(c)) {
9570 n_res = _PyUnicode_ToUpperFull(c, mapped);
9571 }
9572 else {
9573 n_res = 1;
9574 mapped[0] = c;
9575 }
9576 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009577 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009578 res[k++] = mapped[j];
9579 }
9580 }
9581 return k;
9582}
9583
9584static Py_ssize_t
9585do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9586 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009587{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009588 Py_ssize_t i, k = 0;
9589
9590 for (i = 0; i < length; i++) {
9591 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9592 int n_res, j;
9593 if (lower)
9594 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9595 else
9596 n_res = _PyUnicode_ToUpperFull(c, mapped);
9597 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009598 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009599 res[k++] = mapped[j];
9600 }
9601 }
9602 return k;
9603}
9604
9605static Py_ssize_t
9606do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9607{
9608 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9609}
9610
9611static Py_ssize_t
9612do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9613{
9614 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9615}
9616
Benjamin Petersone51757f2012-01-12 21:10:29 -05009617static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009618do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9619{
9620 Py_ssize_t i, k = 0;
9621
9622 for (i = 0; i < length; i++) {
9623 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9624 Py_UCS4 mapped[3];
9625 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9626 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009627 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009628 res[k++] = mapped[j];
9629 }
9630 }
9631 return k;
9632}
9633
9634static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009635do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9636{
9637 Py_ssize_t i, k = 0;
9638 int previous_is_cased;
9639
9640 previous_is_cased = 0;
9641 for (i = 0; i < length; i++) {
9642 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9643 Py_UCS4 mapped[3];
9644 int n_res, j;
9645
9646 if (previous_is_cased)
9647 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9648 else
9649 n_res = _PyUnicode_ToTitleFull(c, mapped);
9650
9651 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009652 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009653 res[k++] = mapped[j];
9654 }
9655
9656 previous_is_cased = _PyUnicode_IsCased(c);
9657 }
9658 return k;
9659}
9660
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009661static PyObject *
9662case_operation(PyObject *self,
9663 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9664{
9665 PyObject *res = NULL;
9666 Py_ssize_t length, newlength = 0;
9667 int kind, outkind;
9668 void *data, *outdata;
9669 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9670
Benjamin Petersoneea48462012-01-16 14:28:50 -05009671 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009672
9673 kind = PyUnicode_KIND(self);
9674 data = PyUnicode_DATA(self);
9675 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009676 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009677 PyErr_SetString(PyExc_OverflowError, "string is too long");
9678 return NULL;
9679 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009680 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009681 if (tmp == NULL)
9682 return PyErr_NoMemory();
9683 newlength = perform(kind, data, length, tmp, &maxchar);
9684 res = PyUnicode_New(newlength, maxchar);
9685 if (res == NULL)
9686 goto leave;
9687 tmpend = tmp + newlength;
9688 outdata = PyUnicode_DATA(res);
9689 outkind = PyUnicode_KIND(res);
9690 switch (outkind) {
9691 case PyUnicode_1BYTE_KIND:
9692 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9693 break;
9694 case PyUnicode_2BYTE_KIND:
9695 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9696 break;
9697 case PyUnicode_4BYTE_KIND:
9698 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9699 break;
9700 default:
9701 assert(0);
9702 break;
9703 }
9704 leave:
9705 PyMem_FREE(tmp);
9706 return res;
9707}
9708
Tim Peters8ce9f162004-08-27 01:49:32 +00009709PyObject *
9710PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009711{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009712 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009713 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009714 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009715 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009716 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9717 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009718 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009719 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009720 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009721 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009722 int use_memcpy;
9723 unsigned char *res_data = NULL, *sep_data = NULL;
9724 PyObject *last_obj;
9725 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009726
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009727 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009728 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009729 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009730 }
9731
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009732 /* NOTE: the following code can't call back into Python code,
9733 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009734 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009735
Tim Peters05eba1f2004-08-27 21:32:02 +00009736 seqlen = PySequence_Fast_GET_SIZE(fseq);
9737 /* If empty sequence, return u"". */
9738 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009739 Py_DECREF(fseq);
Serhiy Storchaka678db842013-01-26 12:16:36 +02009740 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009741 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009742
Tim Peters05eba1f2004-08-27 21:32:02 +00009743 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009744 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009745 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009746 if (seqlen == 1) {
9747 if (PyUnicode_CheckExact(items[0])) {
9748 res = items[0];
9749 Py_INCREF(res);
9750 Py_DECREF(fseq);
9751 return res;
9752 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009753 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009754 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009755 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009756 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009757 /* Set up sep and seplen */
9758 if (separator == NULL) {
9759 /* fall back to a blank space separator */
9760 sep = PyUnicode_FromOrdinal(' ');
9761 if (!sep)
9762 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009763 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009764 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009765 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009766 else {
9767 if (!PyUnicode_Check(separator)) {
9768 PyErr_Format(PyExc_TypeError,
9769 "separator: expected str instance,"
9770 " %.80s found",
9771 Py_TYPE(separator)->tp_name);
9772 goto onError;
9773 }
9774 if (PyUnicode_READY(separator))
9775 goto onError;
9776 sep = separator;
9777 seplen = PyUnicode_GET_LENGTH(separator);
9778 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9779 /* inc refcount to keep this code path symmetric with the
9780 above case of a blank separator */
9781 Py_INCREF(sep);
9782 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009783 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009784 }
9785
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009786 /* There are at least two things to join, or else we have a subclass
9787 * of str in the sequence.
9788 * Do a pre-pass to figure out the total amount of space we'll
9789 * need (sz), and see whether all argument are strings.
9790 */
9791 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009792#ifdef Py_DEBUG
9793 use_memcpy = 0;
9794#else
9795 use_memcpy = 1;
9796#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009797 for (i = 0; i < seqlen; i++) {
9798 const Py_ssize_t old_sz = sz;
9799 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009800 if (!PyUnicode_Check(item)) {
9801 PyErr_Format(PyExc_TypeError,
Victor Stinnera33bce02014-07-04 22:47:46 +02009802 "sequence item %zd: expected str instance,"
Benjamin Peterson29060642009-01-31 22:14:21 +00009803 " %.80s found",
9804 i, Py_TYPE(item)->tp_name);
9805 goto onError;
9806 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009807 if (PyUnicode_READY(item) == -1)
9808 goto onError;
9809 sz += PyUnicode_GET_LENGTH(item);
9810 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009811 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009812 if (i != 0)
9813 sz += seplen;
9814 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9815 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009816 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009817 goto onError;
9818 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009819 if (use_memcpy && last_obj != NULL) {
9820 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9821 use_memcpy = 0;
9822 }
9823 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009824 }
Tim Petersced69f82003-09-16 20:30:58 +00009825
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009826 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009827 if (res == NULL)
9828 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009829
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009830 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009831#ifdef Py_DEBUG
9832 use_memcpy = 0;
9833#else
9834 if (use_memcpy) {
9835 res_data = PyUnicode_1BYTE_DATA(res);
9836 kind = PyUnicode_KIND(res);
9837 if (seplen != 0)
9838 sep_data = PyUnicode_1BYTE_DATA(sep);
9839 }
9840#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009841 if (use_memcpy) {
9842 for (i = 0; i < seqlen; ++i) {
9843 Py_ssize_t itemlen;
9844 item = items[i];
9845
9846 /* Copy item, and maybe the separator. */
9847 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009848 Py_MEMCPY(res_data,
9849 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009850 kind * seplen);
9851 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009852 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009853
9854 itemlen = PyUnicode_GET_LENGTH(item);
9855 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009856 Py_MEMCPY(res_data,
9857 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009858 kind * itemlen);
9859 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009860 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009861 }
9862 assert(res_data == PyUnicode_1BYTE_DATA(res)
9863 + kind * PyUnicode_GET_LENGTH(res));
9864 }
9865 else {
9866 for (i = 0, res_offset = 0; i < seqlen; ++i) {
9867 Py_ssize_t itemlen;
9868 item = items[i];
9869
9870 /* Copy item, and maybe the separator. */
9871 if (i && seplen != 0) {
9872 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
9873 res_offset += seplen;
9874 }
9875
9876 itemlen = PyUnicode_GET_LENGTH(item);
9877 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02009878 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +02009879 res_offset += itemlen;
9880 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009881 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009882 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +02009883 }
Tim Peters8ce9f162004-08-27 01:49:32 +00009884
Tim Peters05eba1f2004-08-27 21:32:02 +00009885 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009886 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009887 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009888 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009889
Benjamin Peterson29060642009-01-31 22:14:21 +00009890 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009891 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009892 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009893 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009894 return NULL;
9895}
9896
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009897#define FILL(kind, data, value, start, length) \
9898 do { \
9899 Py_ssize_t i_ = 0; \
9900 assert(kind != PyUnicode_WCHAR_KIND); \
9901 switch ((kind)) { \
9902 case PyUnicode_1BYTE_KIND: { \
9903 unsigned char * to_ = (unsigned char *)((data)) + (start); \
Victor Stinnerf2c76aa2012-05-03 13:10:40 +02009904 memset(to_, (unsigned char)value, (length)); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009905 break; \
9906 } \
9907 case PyUnicode_2BYTE_KIND: { \
9908 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9909 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9910 break; \
9911 } \
Benjamin Petersone157cf12012-01-01 15:56:20 -06009912 case PyUnicode_4BYTE_KIND: { \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009913 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9914 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9915 break; \
9916 } \
Serhiy Storchaka133b11b2014-12-01 18:56:28 +02009917 default: assert(0); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009918 } \
9919 } while (0)
9920
Victor Stinnerd3f08822012-05-29 12:57:52 +02009921void
9922_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9923 Py_UCS4 fill_char)
9924{
9925 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
9926 const void *data = PyUnicode_DATA(unicode);
9927 assert(PyUnicode_IS_READY(unicode));
9928 assert(unicode_modifiable(unicode));
9929 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
9930 assert(start >= 0);
9931 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
9932 FILL(kind, data, fill_char, start, length);
9933}
9934
Victor Stinner3fe55312012-01-04 00:33:50 +01009935Py_ssize_t
9936PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
9937 Py_UCS4 fill_char)
9938{
9939 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +01009940
9941 if (!PyUnicode_Check(unicode)) {
9942 PyErr_BadInternalCall();
9943 return -1;
9944 }
9945 if (PyUnicode_READY(unicode) == -1)
9946 return -1;
9947 if (unicode_check_modifiable(unicode))
9948 return -1;
9949
Victor Stinnerd3f08822012-05-29 12:57:52 +02009950 if (start < 0) {
9951 PyErr_SetString(PyExc_IndexError, "string index out of range");
9952 return -1;
9953 }
Victor Stinner3fe55312012-01-04 00:33:50 +01009954 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
9955 PyErr_SetString(PyExc_ValueError,
9956 "fill character is bigger than "
9957 "the string maximum character");
9958 return -1;
9959 }
9960
9961 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
9962 length = Py_MIN(maxlen, length);
9963 if (length <= 0)
9964 return 0;
9965
Victor Stinnerd3f08822012-05-29 12:57:52 +02009966 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +01009967 return length;
9968}
9969
Victor Stinner9310abb2011-10-05 00:59:23 +02009970static PyObject *
9971pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009972 Py_ssize_t left,
9973 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009974 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009975{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009976 PyObject *u;
9977 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009978 int kind;
9979 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009980
9981 if (left < 0)
9982 left = 0;
9983 if (right < 0)
9984 right = 0;
9985
Victor Stinnerc4b49542011-12-11 22:44:26 +01009986 if (left == 0 && right == 0)
9987 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009988
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009989 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9990 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009991 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9992 return NULL;
9993 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009994 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009995 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009996 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009997 if (!u)
9998 return NULL;
9999
10000 kind = PyUnicode_KIND(u);
10001 data = PyUnicode_DATA(u);
10002 if (left)
10003 FILL(kind, data, fill, 0, left);
10004 if (right)
10005 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010006 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010007 assert(_PyUnicode_CheckConsistency(u, 1));
10008 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010009}
10010
Alexander Belopolsky40018472011-02-26 01:02:56 +000010011PyObject *
10012PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010013{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010014 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010015
10016 string = PyUnicode_FromObject(string);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010017 if (string == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010018 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060010019 if (PyUnicode_READY(string) == -1) {
10020 Py_DECREF(string);
10021 return NULL;
10022 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010023
Benjamin Petersonead6b532011-12-20 17:23:42 -060010024 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010025 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010026 if (PyUnicode_IS_ASCII(string))
10027 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010028 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010029 PyUnicode_GET_LENGTH(string), keepends);
10030 else
10031 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010032 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010033 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010034 break;
10035 case PyUnicode_2BYTE_KIND:
10036 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010037 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010038 PyUnicode_GET_LENGTH(string), keepends);
10039 break;
10040 case PyUnicode_4BYTE_KIND:
10041 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010042 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010043 PyUnicode_GET_LENGTH(string), keepends);
10044 break;
10045 default:
10046 assert(0);
10047 list = 0;
10048 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010049 Py_DECREF(string);
10050 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010051}
10052
Alexander Belopolsky40018472011-02-26 01:02:56 +000010053static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010054split(PyObject *self,
10055 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010056 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010057{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010058 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010059 void *buf1, *buf2;
10060 Py_ssize_t len1, len2;
10061 PyObject* out;
10062
Guido van Rossumd57fd912000-03-10 22:53:23 +000010063 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010064 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010065
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010066 if (PyUnicode_READY(self) == -1)
10067 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010068
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010069 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010070 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010071 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010072 if (PyUnicode_IS_ASCII(self))
10073 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010074 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010075 PyUnicode_GET_LENGTH(self), maxcount
10076 );
10077 else
10078 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010079 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010080 PyUnicode_GET_LENGTH(self), maxcount
10081 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010082 case PyUnicode_2BYTE_KIND:
10083 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010084 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010085 PyUnicode_GET_LENGTH(self), maxcount
10086 );
10087 case PyUnicode_4BYTE_KIND:
10088 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010089 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010090 PyUnicode_GET_LENGTH(self), maxcount
10091 );
10092 default:
10093 assert(0);
10094 return NULL;
10095 }
10096
10097 if (PyUnicode_READY(substring) == -1)
10098 return NULL;
10099
10100 kind1 = PyUnicode_KIND(self);
10101 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010102 len1 = PyUnicode_GET_LENGTH(self);
10103 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010104 if (kind1 < kind2 || len1 < len2) {
10105 out = PyList_New(1);
10106 if (out == NULL)
10107 return NULL;
10108 Py_INCREF(self);
10109 PyList_SET_ITEM(out, 0, self);
10110 return out;
10111 }
10112 buf1 = PyUnicode_DATA(self);
10113 buf2 = PyUnicode_DATA(substring);
10114 if (kind2 != kind1) {
10115 buf2 = _PyUnicode_AsKind(substring, kind1);
10116 if (!buf2)
10117 return NULL;
10118 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010119
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010120 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010121 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010122 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10123 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010124 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010125 else
10126 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010127 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010128 break;
10129 case PyUnicode_2BYTE_KIND:
10130 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010131 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010132 break;
10133 case PyUnicode_4BYTE_KIND:
10134 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010135 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010136 break;
10137 default:
10138 out = NULL;
10139 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010140 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010141 PyMem_Free(buf2);
10142 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010143}
10144
Alexander Belopolsky40018472011-02-26 01:02:56 +000010145static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010146rsplit(PyObject *self,
10147 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010148 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010149{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010150 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010151 void *buf1, *buf2;
10152 Py_ssize_t len1, len2;
10153 PyObject* out;
10154
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010155 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010156 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010157
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010158 if (PyUnicode_READY(self) == -1)
10159 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010160
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010161 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010162 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010163 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010164 if (PyUnicode_IS_ASCII(self))
10165 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010166 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010167 PyUnicode_GET_LENGTH(self), maxcount
10168 );
10169 else
10170 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010171 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010172 PyUnicode_GET_LENGTH(self), maxcount
10173 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010174 case PyUnicode_2BYTE_KIND:
10175 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010176 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010177 PyUnicode_GET_LENGTH(self), maxcount
10178 );
10179 case PyUnicode_4BYTE_KIND:
10180 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010181 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010182 PyUnicode_GET_LENGTH(self), maxcount
10183 );
10184 default:
10185 assert(0);
10186 return NULL;
10187 }
10188
10189 if (PyUnicode_READY(substring) == -1)
10190 return NULL;
10191
10192 kind1 = PyUnicode_KIND(self);
10193 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010194 len1 = PyUnicode_GET_LENGTH(self);
10195 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010196 if (kind1 < kind2 || len1 < len2) {
10197 out = PyList_New(1);
10198 if (out == NULL)
10199 return NULL;
10200 Py_INCREF(self);
10201 PyList_SET_ITEM(out, 0, self);
10202 return out;
10203 }
10204 buf1 = PyUnicode_DATA(self);
10205 buf2 = PyUnicode_DATA(substring);
10206 if (kind2 != kind1) {
10207 buf2 = _PyUnicode_AsKind(substring, kind1);
10208 if (!buf2)
10209 return NULL;
10210 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010211
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010212 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010213 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010214 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10215 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010216 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010217 else
10218 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010219 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010220 break;
10221 case PyUnicode_2BYTE_KIND:
10222 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010223 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010224 break;
10225 case PyUnicode_4BYTE_KIND:
10226 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010227 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010228 break;
10229 default:
10230 out = NULL;
10231 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010232 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010233 PyMem_Free(buf2);
10234 return out;
10235}
10236
10237static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010238anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10239 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010240{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010241 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010242 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010243 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10244 return asciilib_find(buf1, len1, buf2, len2, offset);
10245 else
10246 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010247 case PyUnicode_2BYTE_KIND:
10248 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10249 case PyUnicode_4BYTE_KIND:
10250 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10251 }
10252 assert(0);
10253 return -1;
10254}
10255
10256static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010257anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10258 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010259{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010260 switch (kind) {
10261 case PyUnicode_1BYTE_KIND:
10262 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10263 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10264 else
10265 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10266 case PyUnicode_2BYTE_KIND:
10267 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10268 case PyUnicode_4BYTE_KIND:
10269 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10270 }
10271 assert(0);
10272 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010273}
10274
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010275static void
10276replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10277 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10278{
10279 int kind = PyUnicode_KIND(u);
10280 void *data = PyUnicode_DATA(u);
10281 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10282 if (kind == PyUnicode_1BYTE_KIND) {
10283 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10284 (Py_UCS1 *)data + len,
10285 u1, u2, maxcount);
10286 }
10287 else if (kind == PyUnicode_2BYTE_KIND) {
10288 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10289 (Py_UCS2 *)data + len,
10290 u1, u2, maxcount);
10291 }
10292 else {
10293 assert(kind == PyUnicode_4BYTE_KIND);
10294 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10295 (Py_UCS4 *)data + len,
10296 u1, u2, maxcount);
10297 }
10298}
10299
Alexander Belopolsky40018472011-02-26 01:02:56 +000010300static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010301replace(PyObject *self, PyObject *str1,
10302 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010303{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010304 PyObject *u;
10305 char *sbuf = PyUnicode_DATA(self);
10306 char *buf1 = PyUnicode_DATA(str1);
10307 char *buf2 = PyUnicode_DATA(str2);
10308 int srelease = 0, release1 = 0, release2 = 0;
10309 int skind = PyUnicode_KIND(self);
10310 int kind1 = PyUnicode_KIND(str1);
10311 int kind2 = PyUnicode_KIND(str2);
10312 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10313 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10314 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010315 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010316 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010317
10318 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010319 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010320 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010321 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010322
Victor Stinner59de0ee2011-10-07 10:01:28 +020010323 if (str1 == str2)
10324 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010325
Victor Stinner49a0a212011-10-12 23:46:10 +020010326 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010327 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10328 if (maxchar < maxchar_str1)
10329 /* substring too wide to be present */
10330 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010331 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10332 /* Replacing str1 with str2 may cause a maxchar reduction in the
10333 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010334 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010335 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010336
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010337 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010338 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010339 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010340 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010341 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010342 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010343 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010344 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010345
Victor Stinner69ed0f42013-04-09 21:48:24 +020010346 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010347 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010348 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010349 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010350 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010351 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010352 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010353 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010354
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010355 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10356 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010357 }
10358 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010359 int rkind = skind;
10360 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010361 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010362
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010363 if (kind1 < rkind) {
10364 /* widen substring */
10365 buf1 = _PyUnicode_AsKind(str1, rkind);
10366 if (!buf1) goto error;
10367 release1 = 1;
10368 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010369 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010370 if (i < 0)
10371 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010372 if (rkind > kind2) {
10373 /* widen replacement */
10374 buf2 = _PyUnicode_AsKind(str2, rkind);
10375 if (!buf2) goto error;
10376 release2 = 1;
10377 }
10378 else if (rkind < kind2) {
10379 /* widen self and buf1 */
10380 rkind = kind2;
10381 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010382 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010383 sbuf = _PyUnicode_AsKind(self, rkind);
10384 if (!sbuf) goto error;
10385 srelease = 1;
10386 buf1 = _PyUnicode_AsKind(str1, rkind);
10387 if (!buf1) goto error;
10388 release1 = 1;
10389 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010390 u = PyUnicode_New(slen, maxchar);
10391 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010392 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010393 assert(PyUnicode_KIND(u) == rkind);
10394 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010395
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010396 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010397 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010398 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010399 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010400 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010401 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010402
10403 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010404 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010405 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010406 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010407 if (i == -1)
10408 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010409 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010410 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010411 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010412 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010413 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010414 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010415 }
10416 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010417 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010418 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010419 int rkind = skind;
10420 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010421
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010422 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010423 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010424 buf1 = _PyUnicode_AsKind(str1, rkind);
10425 if (!buf1) goto error;
10426 release1 = 1;
10427 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010428 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010429 if (n == 0)
10430 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010431 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010432 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010433 buf2 = _PyUnicode_AsKind(str2, rkind);
10434 if (!buf2) goto error;
10435 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010436 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010437 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010438 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010439 rkind = kind2;
10440 sbuf = _PyUnicode_AsKind(self, rkind);
10441 if (!sbuf) goto error;
10442 srelease = 1;
10443 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010444 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010445 buf1 = _PyUnicode_AsKind(str1, rkind);
10446 if (!buf1) goto error;
10447 release1 = 1;
10448 }
10449 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10450 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010451 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010452 PyErr_SetString(PyExc_OverflowError,
10453 "replace string is too long");
10454 goto error;
10455 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010456 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010457 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010458 _Py_INCREF_UNICODE_EMPTY();
10459 if (!unicode_empty)
10460 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010461 u = unicode_empty;
10462 goto done;
10463 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010464 if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010465 PyErr_SetString(PyExc_OverflowError,
10466 "replace string is too long");
10467 goto error;
10468 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010469 u = PyUnicode_New(new_size, maxchar);
10470 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010471 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010472 assert(PyUnicode_KIND(u) == rkind);
10473 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010474 ires = i = 0;
10475 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010476 while (n-- > 0) {
10477 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010478 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010479 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010480 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010481 if (j == -1)
10482 break;
10483 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010484 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010485 memcpy(res + rkind * ires,
10486 sbuf + rkind * i,
10487 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010488 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010489 }
10490 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010491 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010492 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010493 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010494 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010495 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010496 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010497 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010498 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010499 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010500 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010501 memcpy(res + rkind * ires,
10502 sbuf + rkind * i,
10503 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010504 }
10505 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010506 /* interleave */
10507 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010508 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010509 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010510 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010511 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010512 if (--n <= 0)
10513 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010514 memcpy(res + rkind * ires,
10515 sbuf + rkind * i,
10516 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010517 ires++;
10518 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010519 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010520 memcpy(res + rkind * ires,
10521 sbuf + rkind * i,
10522 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010523 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010524 }
10525
10526 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010527 unicode_adjust_maxchar(&u);
10528 if (u == NULL)
10529 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010530 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010531
10532 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010533 if (srelease)
10534 PyMem_FREE(sbuf);
10535 if (release1)
10536 PyMem_FREE(buf1);
10537 if (release2)
10538 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010539 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010540 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010541
Benjamin Peterson29060642009-01-31 22:14:21 +000010542 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010543 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010544 if (srelease)
10545 PyMem_FREE(sbuf);
10546 if (release1)
10547 PyMem_FREE(buf1);
10548 if (release2)
10549 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010550 return unicode_result_unchanged(self);
10551
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010552 error:
10553 if (srelease && sbuf)
10554 PyMem_FREE(sbuf);
10555 if (release1 && buf1)
10556 PyMem_FREE(buf1);
10557 if (release2 && buf2)
10558 PyMem_FREE(buf2);
10559 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010560}
10561
10562/* --- Unicode Object Methods --------------------------------------------- */
10563
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010564PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010565 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010566\n\
10567Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010568characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010569
10570static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010571unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010572{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010573 if (PyUnicode_READY(self) == -1)
10574 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010575 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010576}
10577
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010578PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010579 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010580\n\
10581Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010582have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010583
10584static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010585unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010586{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010587 if (PyUnicode_READY(self) == -1)
10588 return NULL;
10589 if (PyUnicode_GET_LENGTH(self) == 0)
10590 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010591 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010592}
10593
Benjamin Petersond5890c82012-01-14 13:23:30 -050010594PyDoc_STRVAR(casefold__doc__,
10595 "S.casefold() -> str\n\
10596\n\
10597Return a version of S suitable for caseless comparisons.");
10598
10599static PyObject *
10600unicode_casefold(PyObject *self)
10601{
10602 if (PyUnicode_READY(self) == -1)
10603 return NULL;
10604 if (PyUnicode_IS_ASCII(self))
10605 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010606 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010607}
10608
10609
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010610/* Argument converter. Coerces to a single unicode character */
10611
10612static int
10613convert_uc(PyObject *obj, void *addr)
10614{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010615 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010616 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010617
Benjamin Peterson14339b62009-01-31 16:36:08 +000010618 uniobj = PyUnicode_FromObject(obj);
10619 if (uniobj == NULL) {
10620 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010621 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010622 return 0;
10623 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010624 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010625 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010626 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010627 Py_DECREF(uniobj);
10628 return 0;
10629 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010630 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010631 Py_DECREF(uniobj);
10632 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010633}
10634
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010635PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010636 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010637\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010638Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010639done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010640
10641static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010642unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010643{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010644 Py_ssize_t marg, left;
10645 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010646 Py_UCS4 fillchar = ' ';
10647
Victor Stinnere9a29352011-10-01 02:14:59 +020010648 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010649 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010650
Benjamin Petersonbac79492012-01-14 13:34:47 -050010651 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010652 return NULL;
10653
Victor Stinnerc4b49542011-12-11 22:44:26 +010010654 if (PyUnicode_GET_LENGTH(self) >= width)
10655 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010656
Victor Stinnerc4b49542011-12-11 22:44:26 +010010657 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010658 left = marg / 2 + (marg & width & 1);
10659
Victor Stinner9310abb2011-10-05 00:59:23 +020010660 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010661}
10662
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010663/* This function assumes that str1 and str2 are readied by the caller. */
10664
Marc-André Lemburge5034372000-08-08 08:04:29 +000010665static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010666unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010667{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010668#define COMPARE(TYPE1, TYPE2) \
10669 do { \
10670 TYPE1* p1 = (TYPE1 *)data1; \
10671 TYPE2* p2 = (TYPE2 *)data2; \
10672 TYPE1* end = p1 + len; \
10673 Py_UCS4 c1, c2; \
10674 for (; p1 != end; p1++, p2++) { \
10675 c1 = *p1; \
10676 c2 = *p2; \
10677 if (c1 != c2) \
10678 return (c1 < c2) ? -1 : 1; \
10679 } \
10680 } \
10681 while (0)
10682
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010683 int kind1, kind2;
10684 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010685 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010686
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010687 kind1 = PyUnicode_KIND(str1);
10688 kind2 = PyUnicode_KIND(str2);
10689 data1 = PyUnicode_DATA(str1);
10690 data2 = PyUnicode_DATA(str2);
10691 len1 = PyUnicode_GET_LENGTH(str1);
10692 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010693 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010694
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010695 switch(kind1) {
10696 case PyUnicode_1BYTE_KIND:
10697 {
10698 switch(kind2) {
10699 case PyUnicode_1BYTE_KIND:
10700 {
10701 int cmp = memcmp(data1, data2, len);
10702 /* normalize result of memcmp() into the range [-1; 1] */
10703 if (cmp < 0)
10704 return -1;
10705 if (cmp > 0)
10706 return 1;
10707 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010708 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010709 case PyUnicode_2BYTE_KIND:
10710 COMPARE(Py_UCS1, Py_UCS2);
10711 break;
10712 case PyUnicode_4BYTE_KIND:
10713 COMPARE(Py_UCS1, Py_UCS4);
10714 break;
10715 default:
10716 assert(0);
10717 }
10718 break;
10719 }
10720 case PyUnicode_2BYTE_KIND:
10721 {
10722 switch(kind2) {
10723 case PyUnicode_1BYTE_KIND:
10724 COMPARE(Py_UCS2, Py_UCS1);
10725 break;
10726 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010727 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010728 COMPARE(Py_UCS2, Py_UCS2);
10729 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010730 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010731 case PyUnicode_4BYTE_KIND:
10732 COMPARE(Py_UCS2, Py_UCS4);
10733 break;
10734 default:
10735 assert(0);
10736 }
10737 break;
10738 }
10739 case PyUnicode_4BYTE_KIND:
10740 {
10741 switch(kind2) {
10742 case PyUnicode_1BYTE_KIND:
10743 COMPARE(Py_UCS4, Py_UCS1);
10744 break;
10745 case PyUnicode_2BYTE_KIND:
10746 COMPARE(Py_UCS4, Py_UCS2);
10747 break;
10748 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010749 {
10750#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10751 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10752 /* normalize result of wmemcmp() into the range [-1; 1] */
10753 if (cmp < 0)
10754 return -1;
10755 if (cmp > 0)
10756 return 1;
10757#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010758 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010759#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010760 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010761 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010762 default:
10763 assert(0);
10764 }
10765 break;
10766 }
10767 default:
10768 assert(0);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010769 }
10770
Victor Stinner770e19e2012-10-04 22:59:45 +020010771 if (len1 == len2)
10772 return 0;
10773 if (len1 < len2)
10774 return -1;
10775 else
10776 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010777
10778#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010779}
10780
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010781Py_LOCAL(int)
Victor Stinnere5567ad2012-10-23 02:48:49 +020010782unicode_compare_eq(PyObject *str1, PyObject *str2)
10783{
10784 int kind;
10785 void *data1, *data2;
10786 Py_ssize_t len;
10787 int cmp;
10788
Victor Stinnere5567ad2012-10-23 02:48:49 +020010789 len = PyUnicode_GET_LENGTH(str1);
10790 if (PyUnicode_GET_LENGTH(str2) != len)
10791 return 0;
10792 kind = PyUnicode_KIND(str1);
10793 if (PyUnicode_KIND(str2) != kind)
10794 return 0;
10795 data1 = PyUnicode_DATA(str1);
10796 data2 = PyUnicode_DATA(str2);
10797
10798 cmp = memcmp(data1, data2, len * kind);
10799 return (cmp == 0);
10800}
10801
10802
Alexander Belopolsky40018472011-02-26 01:02:56 +000010803int
10804PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010805{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010806 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10807 if (PyUnicode_READY(left) == -1 ||
10808 PyUnicode_READY(right) == -1)
10809 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010810
10811 /* a string is equal to itself */
10812 if (left == right)
10813 return 0;
10814
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010815 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010816 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010817 PyErr_Format(PyExc_TypeError,
10818 "Can't compare %.100s and %.100s",
10819 left->ob_type->tp_name,
10820 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010821 return -1;
10822}
10823
Martin v. Löwis5b222132007-06-10 09:51:05 +000010824int
Victor Stinnerad14ccd2013-11-07 00:46:04 +010010825_PyUnicode_CompareWithId(PyObject *left, _Py_Identifier *right)
10826{
10827 PyObject *right_str = _PyUnicode_FromId(right); /* borrowed */
10828 if (right_str == NULL)
10829 return -1;
10830 return PyUnicode_Compare(left, right_str);
10831}
10832
10833int
Martin v. Löwis5b222132007-06-10 09:51:05 +000010834PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10835{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010836 Py_ssize_t i;
10837 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010838 Py_UCS4 chr;
10839
Victor Stinner910337b2011-10-03 03:20:16 +020010840 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010841 if (PyUnicode_READY(uni) == -1)
10842 return -1;
10843 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010844 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010010845 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010010846 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010847 size_t len, len2 = strlen(str);
10848 int cmp;
10849
10850 len = Py_MIN(len1, len2);
10851 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010010852 if (cmp != 0) {
10853 if (cmp < 0)
10854 return -1;
10855 else
10856 return 1;
10857 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010010858 if (len1 > len2)
10859 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010860 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010010861 return -1; /* str is longer */
10862 return 0;
10863 }
10864 else {
10865 void *data = PyUnicode_DATA(uni);
10866 /* Compare Unicode string and source character set string */
10867 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020010868 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010010869 return (chr < (unsigned char)(str[i])) ? -1 : 1;
10870 /* This check keeps Python strings that end in '\0' from comparing equal
10871 to C strings identical up to that point. */
10872 if (PyUnicode_GET_LENGTH(uni) != i || chr)
10873 return 1; /* uni is longer */
10874 if (str[i])
10875 return -1; /* str is longer */
10876 return 0;
10877 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000010878}
10879
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010880
Benjamin Peterson29060642009-01-31 22:14:21 +000010881#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010882 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010883
Alexander Belopolsky40018472011-02-26 01:02:56 +000010884PyObject *
10885PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010886{
10887 int result;
Victor Stinnere5567ad2012-10-23 02:48:49 +020010888 PyObject *v;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010889
Victor Stinnere5567ad2012-10-23 02:48:49 +020010890 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
10891 Py_RETURN_NOTIMPLEMENTED;
10892
10893 if (PyUnicode_READY(left) == -1 ||
10894 PyUnicode_READY(right) == -1)
10895 return NULL;
10896
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010010897 if (left == right) {
10898 switch (op) {
10899 case Py_EQ:
10900 case Py_LE:
10901 case Py_GE:
10902 /* a string is equal to itself */
10903 v = Py_True;
10904 break;
10905 case Py_NE:
10906 case Py_LT:
10907 case Py_GT:
10908 v = Py_False;
10909 break;
10910 default:
10911 PyErr_BadArgument();
10912 return NULL;
10913 }
10914 }
10915 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020010916 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010010917 result ^= (op == Py_NE);
10918 v = TEST_COND(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020010919 }
10920 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020010921 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010922
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010923 /* Convert the return value to a Boolean */
10924 switch (op) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010925 case Py_LE:
10926 v = TEST_COND(result <= 0);
10927 break;
10928 case Py_GE:
10929 v = TEST_COND(result >= 0);
10930 break;
10931 case Py_LT:
10932 v = TEST_COND(result == -1);
10933 break;
10934 case Py_GT:
10935 v = TEST_COND(result == 1);
10936 break;
10937 default:
10938 PyErr_BadArgument();
10939 return NULL;
10940 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010941 }
Victor Stinnere5567ad2012-10-23 02:48:49 +020010942 Py_INCREF(v);
10943 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010944}
10945
Alexander Belopolsky40018472011-02-26 01:02:56 +000010946int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070010947_PyUnicode_EQ(PyObject *aa, PyObject *bb)
10948{
10949 return unicode_eq(aa, bb);
10950}
10951
10952int
Alexander Belopolsky40018472011-02-26 01:02:56 +000010953PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010954{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010955 PyObject *str, *sub;
Victor Stinner77282cb2013-04-14 19:22:47 +020010956 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010957 void *buf1, *buf2;
10958 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010959 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010960
10961 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010962 sub = PyUnicode_FromObject(element);
10963 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010964 PyErr_Format(PyExc_TypeError,
10965 "'in <string>' requires string as left operand, not %s",
10966 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010967 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010968 }
10969
Thomas Wouters477c8d52006-05-27 19:21:47 +000010970 str = PyUnicode_FromObject(container);
Benjamin Peterson22a29702012-01-02 09:00:30 -060010971 if (!str) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010972 Py_DECREF(sub);
10973 return -1;
10974 }
10975
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010976 kind1 = PyUnicode_KIND(str);
10977 kind2 = PyUnicode_KIND(sub);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010978 if (kind1 < kind2) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010979 Py_DECREF(sub);
Benjamin Peterson1ff2e352012-05-11 17:41:20 -050010980 Py_DECREF(str);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010981 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010982 }
10983 len1 = PyUnicode_GET_LENGTH(str);
10984 len2 = PyUnicode_GET_LENGTH(sub);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010985 if (len1 < len2) {
10986 Py_DECREF(sub);
10987 Py_DECREF(str);
10988 return 0;
10989 }
10990 buf1 = PyUnicode_DATA(str);
10991 buf2 = PyUnicode_DATA(sub);
10992 if (len2 == 1) {
10993 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
10994 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
10995 Py_DECREF(sub);
10996 Py_DECREF(str);
10997 return result;
10998 }
10999 if (kind2 != kind1) {
11000 buf2 = _PyUnicode_AsKind(sub, kind1);
11001 if (!buf2) {
11002 Py_DECREF(sub);
11003 Py_DECREF(str);
11004 return -1;
11005 }
11006 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011007
Victor Stinner77282cb2013-04-14 19:22:47 +020011008 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011009 case PyUnicode_1BYTE_KIND:
11010 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11011 break;
11012 case PyUnicode_2BYTE_KIND:
11013 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11014 break;
11015 case PyUnicode_4BYTE_KIND:
11016 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11017 break;
11018 default:
11019 result = -1;
11020 assert(0);
11021 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011022
11023 Py_DECREF(str);
11024 Py_DECREF(sub);
11025
Victor Stinner77282cb2013-04-14 19:22:47 +020011026 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011027 PyMem_Free(buf2);
11028
Guido van Rossum403d68b2000-03-13 15:55:09 +000011029 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011030}
11031
Guido van Rossumd57fd912000-03-10 22:53:23 +000011032/* Concat to string or Unicode object giving a new Unicode object. */
11033
Alexander Belopolsky40018472011-02-26 01:02:56 +000011034PyObject *
11035PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011036{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011037 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020011038 Py_UCS4 maxchar, maxchar2;
Victor Stinner488fa492011-12-12 00:01:39 +010011039 Py_ssize_t u_len, v_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011040
11041 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011042 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011043 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011044 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011045 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011046 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011047 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011048
11049 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020011050 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011051 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011052 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011053 }
Victor Stinnera464fc12011-10-02 20:39:30 +020011054 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011055 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011056 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011057 }
11058
Victor Stinner488fa492011-12-12 00:01:39 +010011059 u_len = PyUnicode_GET_LENGTH(u);
11060 v_len = PyUnicode_GET_LENGTH(v);
11061 if (u_len > PY_SSIZE_T_MAX - v_len) {
11062 PyErr_SetString(PyExc_OverflowError,
11063 "strings are too large to concat");
11064 goto onError;
11065 }
11066 new_len = u_len + v_len;
11067
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011068 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020011069 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011070 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011071
Guido van Rossumd57fd912000-03-10 22:53:23 +000011072 /* Concat the two Unicode strings */
Victor Stinner488fa492011-12-12 00:01:39 +010011073 w = PyUnicode_New(new_len, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011074 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000011075 goto onError;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011076 _PyUnicode_FastCopyCharacters(w, 0, u, 0, u_len);
11077 _PyUnicode_FastCopyCharacters(w, u_len, v, 0, v_len);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011078 Py_DECREF(u);
11079 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011080 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011081 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011082
Benjamin Peterson29060642009-01-31 22:14:21 +000011083 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000011084 Py_XDECREF(u);
11085 Py_XDECREF(v);
11086 return NULL;
11087}
11088
Walter Dörwald1ab83302007-05-18 17:15:44 +000011089void
Victor Stinner23e56682011-10-03 03:54:37 +020011090PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011091{
Victor Stinner23e56682011-10-03 03:54:37 +020011092 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011093 Py_UCS4 maxchar, maxchar2;
11094 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011095
11096 if (p_left == NULL) {
11097 if (!PyErr_Occurred())
11098 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011099 return;
11100 }
Victor Stinner23e56682011-10-03 03:54:37 +020011101 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011102 if (right == NULL || left == NULL
11103 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011104 if (!PyErr_Occurred())
11105 PyErr_BadInternalCall();
11106 goto error;
11107 }
11108
Benjamin Petersonbac79492012-01-14 13:34:47 -050011109 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011110 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011111 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011112 goto error;
11113
Victor Stinner488fa492011-12-12 00:01:39 +010011114 /* Shortcuts */
11115 if (left == unicode_empty) {
11116 Py_DECREF(left);
11117 Py_INCREF(right);
11118 *p_left = right;
11119 return;
11120 }
11121 if (right == unicode_empty)
11122 return;
11123
11124 left_len = PyUnicode_GET_LENGTH(left);
11125 right_len = PyUnicode_GET_LENGTH(right);
11126 if (left_len > PY_SSIZE_T_MAX - right_len) {
11127 PyErr_SetString(PyExc_OverflowError,
11128 "strings are too large to concat");
11129 goto error;
11130 }
11131 new_len = left_len + right_len;
11132
11133 if (unicode_modifiable(left)
11134 && PyUnicode_CheckExact(right)
11135 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011136 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11137 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011138 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011139 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011140 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11141 {
11142 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011143 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011144 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011145
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011146 /* copy 'right' into the newly allocated area of 'left' */
11147 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011148 }
Victor Stinner488fa492011-12-12 00:01:39 +010011149 else {
11150 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11151 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011152 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011153
Victor Stinner488fa492011-12-12 00:01:39 +010011154 /* Concat the two Unicode strings */
11155 res = PyUnicode_New(new_len, maxchar);
11156 if (res == NULL)
11157 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011158 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11159 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011160 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011161 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011162 }
11163 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011164 return;
11165
11166error:
Victor Stinner488fa492011-12-12 00:01:39 +010011167 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011168}
11169
11170void
11171PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11172{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011173 PyUnicode_Append(pleft, right);
11174 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011175}
11176
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011177PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011178 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011179\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011180Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011181string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011182interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011183
11184static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011185unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011186{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011187 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011188 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011189 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011190 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011191 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011192 void *buf1, *buf2;
11193 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011194
Jesus Ceaac451502011-04-20 17:09:23 +020011195 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
11196 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011197 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011198
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011199 kind1 = PyUnicode_KIND(self);
11200 kind2 = PyUnicode_KIND(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011201 if (kind1 < kind2) {
Christian Heimesd47802e2013-06-29 21:33:36 +020011202 Py_DECREF(substring);
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011203 return PyLong_FromLong(0);
Christian Heimesd47802e2013-06-29 21:33:36 +020011204 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011205 len1 = PyUnicode_GET_LENGTH(self);
11206 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011207 ADJUST_INDICES(start, end, len1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011208 if (end - start < len2) {
11209 Py_DECREF(substring);
11210 return PyLong_FromLong(0);
11211 }
11212 buf1 = PyUnicode_DATA(self);
11213 buf2 = PyUnicode_DATA(substring);
11214 if (kind2 != kind1) {
11215 buf2 = _PyUnicode_AsKind(substring, kind1);
11216 if (!buf2) {
11217 Py_DECREF(substring);
11218 return NULL;
11219 }
11220 }
11221 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011222 case PyUnicode_1BYTE_KIND:
11223 iresult = ucs1lib_count(
11224 ((Py_UCS1*)buf1) + start, end - start,
11225 buf2, len2, PY_SSIZE_T_MAX
11226 );
11227 break;
11228 case PyUnicode_2BYTE_KIND:
11229 iresult = ucs2lib_count(
11230 ((Py_UCS2*)buf1) + start, end - start,
11231 buf2, len2, PY_SSIZE_T_MAX
11232 );
11233 break;
11234 case PyUnicode_4BYTE_KIND:
11235 iresult = ucs4lib_count(
11236 ((Py_UCS4*)buf1) + start, end - start,
11237 buf2, len2, PY_SSIZE_T_MAX
11238 );
11239 break;
11240 default:
11241 assert(0); iresult = 0;
11242 }
11243
11244 result = PyLong_FromSsize_t(iresult);
11245
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011246 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011247 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011248
11249 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011250
Guido van Rossumd57fd912000-03-10 22:53:23 +000011251 return result;
11252}
11253
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011254PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011255 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011256\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011257Encode S using the codec registered for encoding. Default encoding\n\
11258is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011259handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011260a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11261'xmlcharrefreplace' as well as any other name registered with\n\
11262codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011263
11264static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011265unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011266{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011267 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011268 char *encoding = NULL;
11269 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011270
Benjamin Peterson308d6372009-09-18 21:42:35 +000011271 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11272 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011273 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011274 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011275}
11276
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011277PyDoc_STRVAR(expandtabs__doc__,
Ezio Melotti745d54d2013-11-16 19:10:57 +020011278 "S.expandtabs(tabsize=8) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011279\n\
11280Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011281If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011282
11283static PyObject*
Ezio Melotti745d54d2013-11-16 19:10:57 +020011284unicode_expandtabs(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011285{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011286 Py_ssize_t i, j, line_pos, src_len, incr;
11287 Py_UCS4 ch;
11288 PyObject *u;
11289 void *src_data, *dest_data;
Ezio Melotti745d54d2013-11-16 19:10:57 +020011290 static char *kwlist[] = {"tabsize", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011291 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011292 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011293 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011294
Ezio Melotti745d54d2013-11-16 19:10:57 +020011295 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:expandtabs",
11296 kwlist, &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011297 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011298
Antoine Pitrou22425222011-10-04 19:10:51 +020011299 if (PyUnicode_READY(self) == -1)
11300 return NULL;
11301
Thomas Wouters7e474022000-07-16 12:04:32 +000011302 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011303 src_len = PyUnicode_GET_LENGTH(self);
11304 i = j = line_pos = 0;
11305 kind = PyUnicode_KIND(self);
11306 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011307 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011308 for (; i < src_len; i++) {
11309 ch = PyUnicode_READ(kind, src_data, i);
11310 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011311 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011312 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011313 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011314 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011315 goto overflow;
11316 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011317 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011318 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011319 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011320 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011321 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011322 goto overflow;
11323 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011324 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011325 if (ch == '\n' || ch == '\r')
11326 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011327 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011328 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011329 if (!found)
11330 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011331
Guido van Rossumd57fd912000-03-10 22:53:23 +000011332 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011333 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011334 if (!u)
11335 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011336 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011337
Antoine Pitroue71d5742011-10-04 15:55:09 +020011338 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011339
Antoine Pitroue71d5742011-10-04 15:55:09 +020011340 for (; i < src_len; i++) {
11341 ch = PyUnicode_READ(kind, src_data, i);
11342 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011343 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011344 incr = tabsize - (line_pos % tabsize);
11345 line_pos += incr;
Victor Stinnerda79e632012-02-22 13:37:04 +010011346 FILL(kind, dest_data, ' ', j, incr);
11347 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011348 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011349 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011350 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011351 line_pos++;
11352 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011353 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011354 if (ch == '\n' || ch == '\r')
11355 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011356 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011357 }
11358 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011359 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011360
Antoine Pitroue71d5742011-10-04 15:55:09 +020011361 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011362 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11363 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011364}
11365
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011366PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011367 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011368\n\
11369Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011370such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011371arguments start and end are interpreted as in slice notation.\n\
11372\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011373Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011374
11375static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011376unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011377{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011378 /* initialize variables to prevent gcc warning */
11379 PyObject *substring = NULL;
11380 Py_ssize_t start = 0;
11381 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011382 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011383
Jesus Ceaac451502011-04-20 17:09:23 +020011384 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11385 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011386 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011387
Christian Heimesd47802e2013-06-29 21:33:36 +020011388 if (PyUnicode_READY(self) == -1) {
11389 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011390 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011391 }
11392 if (PyUnicode_READY(substring) == -1) {
11393 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011394 return NULL;
Christian Heimesd47802e2013-06-29 21:33:36 +020011395 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011396
Victor Stinner7931d9a2011-11-04 00:22:48 +010011397 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011398
11399 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011400
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011401 if (result == -2)
11402 return NULL;
11403
Christian Heimes217cfd12007-12-02 14:31:20 +000011404 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011405}
11406
11407static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011408unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011409{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011410 void *data;
11411 enum PyUnicode_Kind kind;
11412 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011413
11414 if (!PyUnicode_Check(self) || PyUnicode_READY(self) == -1) {
11415 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011416 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011417 }
11418 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11419 PyErr_SetString(PyExc_IndexError, "string index out of range");
11420 return NULL;
11421 }
11422 kind = PyUnicode_KIND(self);
11423 data = PyUnicode_DATA(self);
11424 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011425 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011426}
11427
Guido van Rossumc2504932007-09-18 19:42:40 +000011428/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011429 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011430static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011431unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011432{
Guido van Rossumc2504932007-09-18 19:42:40 +000011433 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011434 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011435
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011436#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011437 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011438#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011439 if (_PyUnicode_HASH(self) != -1)
11440 return _PyUnicode_HASH(self);
11441 if (PyUnicode_READY(self) == -1)
11442 return -1;
11443 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011444 /*
11445 We make the hash of the empty string be 0, rather than using
11446 (prefix ^ suffix), since this slightly obfuscates the hash secret
11447 */
11448 if (len == 0) {
11449 _PyUnicode_HASH(self) = 0;
11450 return 0;
11451 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011452 x = _Py_HashBytes(PyUnicode_DATA(self),
11453 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011454 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011455 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011456}
11457
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011458PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011459 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011460\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011461Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011462
11463static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011464unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011465{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011466 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011467 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011468 PyObject *substring = NULL;
11469 Py_ssize_t start = 0;
11470 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011471
Jesus Ceaac451502011-04-20 17:09:23 +020011472 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11473 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011474 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011475
Christian Heimesd47a0452013-06-29 21:21:37 +020011476 if (PyUnicode_READY(self) == -1) {
11477 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011478 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011479 }
11480 if (PyUnicode_READY(substring) == -1) {
11481 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011482 return NULL;
Christian Heimesd47a0452013-06-29 21:21:37 +020011483 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011484
Victor Stinner7931d9a2011-11-04 00:22:48 +010011485 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011486
11487 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011488
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011489 if (result == -2)
11490 return NULL;
11491
Guido van Rossumd57fd912000-03-10 22:53:23 +000011492 if (result < 0) {
11493 PyErr_SetString(PyExc_ValueError, "substring not found");
11494 return NULL;
11495 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011496
Christian Heimes217cfd12007-12-02 14:31:20 +000011497 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011498}
11499
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011500PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011501 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011502\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011503Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011504at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011505
11506static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011507unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011508{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011509 Py_ssize_t i, length;
11510 int kind;
11511 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011512 int cased;
11513
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011514 if (PyUnicode_READY(self) == -1)
11515 return NULL;
11516 length = PyUnicode_GET_LENGTH(self);
11517 kind = PyUnicode_KIND(self);
11518 data = PyUnicode_DATA(self);
11519
Guido van Rossumd57fd912000-03-10 22:53:23 +000011520 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011521 if (length == 1)
11522 return PyBool_FromLong(
11523 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011524
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011525 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011526 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011527 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011528
Guido van Rossumd57fd912000-03-10 22:53:23 +000011529 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011530 for (i = 0; i < length; i++) {
11531 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011532
Benjamin Peterson29060642009-01-31 22:14:21 +000011533 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11534 return PyBool_FromLong(0);
11535 else if (!cased && Py_UNICODE_ISLOWER(ch))
11536 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011537 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011538 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011539}
11540
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011541PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011542 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011543\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011544Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011545at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011546
11547static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011548unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011549{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011550 Py_ssize_t i, length;
11551 int kind;
11552 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011553 int cased;
11554
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011555 if (PyUnicode_READY(self) == -1)
11556 return NULL;
11557 length = PyUnicode_GET_LENGTH(self);
11558 kind = PyUnicode_KIND(self);
11559 data = PyUnicode_DATA(self);
11560
Guido van Rossumd57fd912000-03-10 22:53:23 +000011561 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011562 if (length == 1)
11563 return PyBool_FromLong(
11564 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011565
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011566 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011567 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011568 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011569
Guido van Rossumd57fd912000-03-10 22:53:23 +000011570 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011571 for (i = 0; i < length; i++) {
11572 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011573
Benjamin Peterson29060642009-01-31 22:14:21 +000011574 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11575 return PyBool_FromLong(0);
11576 else if (!cased && Py_UNICODE_ISUPPER(ch))
11577 cased = 1;
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(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011583 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011584\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011585Return True if S is a titlecased string and there is at least one\n\
11586character in S, i.e. upper- and titlecase characters may only\n\
11587follow uncased characters and lowercase characters only cased ones.\n\
11588Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011589
11590static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011591unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011592{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011593 Py_ssize_t i, length;
11594 int kind;
11595 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011596 int cased, previous_is_cased;
11597
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011598 if (PyUnicode_READY(self) == -1)
11599 return NULL;
11600 length = PyUnicode_GET_LENGTH(self);
11601 kind = PyUnicode_KIND(self);
11602 data = PyUnicode_DATA(self);
11603
Guido van Rossumd57fd912000-03-10 22:53:23 +000011604 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011605 if (length == 1) {
11606 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11607 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11608 (Py_UNICODE_ISUPPER(ch) != 0));
11609 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011610
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011611 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011612 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011613 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011614
Guido van Rossumd57fd912000-03-10 22:53:23 +000011615 cased = 0;
11616 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011617 for (i = 0; i < length; i++) {
11618 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011619
Benjamin Peterson29060642009-01-31 22:14:21 +000011620 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11621 if (previous_is_cased)
11622 return PyBool_FromLong(0);
11623 previous_is_cased = 1;
11624 cased = 1;
11625 }
11626 else if (Py_UNICODE_ISLOWER(ch)) {
11627 if (!previous_is_cased)
11628 return PyBool_FromLong(0);
11629 previous_is_cased = 1;
11630 cased = 1;
11631 }
11632 else
11633 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011634 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011635 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011636}
11637
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011638PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011639 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011640\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011641Return True if all characters in S are whitespace\n\
11642and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011643
11644static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011645unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011646{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011647 Py_ssize_t i, length;
11648 int kind;
11649 void *data;
11650
11651 if (PyUnicode_READY(self) == -1)
11652 return NULL;
11653 length = PyUnicode_GET_LENGTH(self);
11654 kind = PyUnicode_KIND(self);
11655 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011656
Guido van Rossumd57fd912000-03-10 22:53:23 +000011657 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011658 if (length == 1)
11659 return PyBool_FromLong(
11660 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011661
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011662 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011663 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011664 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011665
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011666 for (i = 0; i < length; i++) {
11667 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011668 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011669 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011670 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011671 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011672}
11673
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011674PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011675 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011676\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011677Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011678and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011679
11680static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011681unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011682{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011683 Py_ssize_t i, length;
11684 int kind;
11685 void *data;
11686
11687 if (PyUnicode_READY(self) == -1)
11688 return NULL;
11689 length = PyUnicode_GET_LENGTH(self);
11690 kind = PyUnicode_KIND(self);
11691 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011692
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011693 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011694 if (length == 1)
11695 return PyBool_FromLong(
11696 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011697
11698 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011699 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011700 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011701
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011702 for (i = 0; i < length; i++) {
11703 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011704 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011705 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011706 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011707}
11708
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011709PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011710 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011711\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011712Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011713and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011714
11715static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011716unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011717{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011718 int kind;
11719 void *data;
11720 Py_ssize_t len, i;
11721
11722 if (PyUnicode_READY(self) == -1)
11723 return NULL;
11724
11725 kind = PyUnicode_KIND(self);
11726 data = PyUnicode_DATA(self);
11727 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011728
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011729 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011730 if (len == 1) {
11731 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11732 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11733 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011734
11735 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011736 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011737 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011738
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011739 for (i = 0; i < len; i++) {
11740 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011741 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011742 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011743 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011744 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011745}
11746
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011747PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011748 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011749\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011750Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011751False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011752
11753static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011754unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011755{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011756 Py_ssize_t i, length;
11757 int kind;
11758 void *data;
11759
11760 if (PyUnicode_READY(self) == -1)
11761 return NULL;
11762 length = PyUnicode_GET_LENGTH(self);
11763 kind = PyUnicode_KIND(self);
11764 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011765
Guido van Rossumd57fd912000-03-10 22:53:23 +000011766 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011767 if (length == 1)
11768 return PyBool_FromLong(
11769 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011770
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011771 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011772 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011773 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011774
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011775 for (i = 0; i < length; i++) {
11776 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011777 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011778 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011779 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011780}
11781
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011782PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011783 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011784\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011785Return True if all characters in S are digits\n\
11786and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011787
11788static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011789unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011790{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011791 Py_ssize_t i, length;
11792 int kind;
11793 void *data;
11794
11795 if (PyUnicode_READY(self) == -1)
11796 return NULL;
11797 length = PyUnicode_GET_LENGTH(self);
11798 kind = PyUnicode_KIND(self);
11799 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011800
Guido van Rossumd57fd912000-03-10 22:53:23 +000011801 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011802 if (length == 1) {
11803 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11804 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11805 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011806
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011807 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011808 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011809 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011810
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011811 for (i = 0; i < length; i++) {
11812 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011813 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011814 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011815 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011816}
11817
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011818PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011819 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011820\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011821Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011822False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011823
11824static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011825unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011826{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011827 Py_ssize_t i, length;
11828 int kind;
11829 void *data;
11830
11831 if (PyUnicode_READY(self) == -1)
11832 return NULL;
11833 length = PyUnicode_GET_LENGTH(self);
11834 kind = PyUnicode_KIND(self);
11835 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011836
Guido van Rossumd57fd912000-03-10 22:53:23 +000011837 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011838 if (length == 1)
11839 return PyBool_FromLong(
11840 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011841
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011842 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011843 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011844 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011845
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011846 for (i = 0; i < length; i++) {
11847 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011848 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011849 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011850 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011851}
11852
Martin v. Löwis47383402007-08-15 07:32:56 +000011853int
11854PyUnicode_IsIdentifier(PyObject *self)
11855{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011856 int kind;
11857 void *data;
11858 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011859 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011860
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011861 if (PyUnicode_READY(self) == -1) {
11862 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011863 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011864 }
11865
11866 /* Special case for empty strings */
11867 if (PyUnicode_GET_LENGTH(self) == 0)
11868 return 0;
11869 kind = PyUnicode_KIND(self);
11870 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011871
11872 /* PEP 3131 says that the first character must be in
11873 XID_Start and subsequent characters in XID_Continue,
11874 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011875 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011876 letters, digits, underscore). However, given the current
11877 definition of XID_Start and XID_Continue, it is sufficient
11878 to check just for these, except that _ must be allowed
11879 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011880 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011881 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011882 return 0;
11883
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011884 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011885 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011886 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011887 return 1;
11888}
11889
11890PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011891 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011892\n\
11893Return True if S is a valid identifier according\n\
Raymond Hettinger378170d2013-03-23 08:21:12 -070011894to the language definition.\n\
11895\n\
11896Use keyword.iskeyword() to test for reserved identifiers\n\
11897such as \"def\" and \"class\".\n");
Martin v. Löwis47383402007-08-15 07:32:56 +000011898
11899static PyObject*
11900unicode_isidentifier(PyObject *self)
11901{
11902 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11903}
11904
Georg Brandl559e5d72008-06-11 18:37:52 +000011905PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011906 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011907\n\
11908Return True if all characters in S are considered\n\
11909printable in repr() or S is empty, False otherwise.");
11910
11911static PyObject*
11912unicode_isprintable(PyObject *self)
11913{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011914 Py_ssize_t i, length;
11915 int kind;
11916 void *data;
11917
11918 if (PyUnicode_READY(self) == -1)
11919 return NULL;
11920 length = PyUnicode_GET_LENGTH(self);
11921 kind = PyUnicode_KIND(self);
11922 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011923
11924 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011925 if (length == 1)
11926 return PyBool_FromLong(
11927 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011928
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011929 for (i = 0; i < length; i++) {
11930 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011931 Py_RETURN_FALSE;
11932 }
11933 }
11934 Py_RETURN_TRUE;
11935}
11936
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011937PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011938 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011939\n\
11940Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011941iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011942
11943static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011944unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011945{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011946 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011947}
11948
Martin v. Löwis18e16552006-02-15 17:27:45 +000011949static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011950unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011951{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011952 if (PyUnicode_READY(self) == -1)
11953 return -1;
11954 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011955}
11956
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011957PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011958 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011959\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011960Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011961done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011962
11963static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011964unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011965{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011966 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011967 Py_UCS4 fillchar = ' ';
11968
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011969 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011970 return NULL;
11971
Benjamin Petersonbac79492012-01-14 13:34:47 -050011972 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010011973 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011974
Victor Stinnerc4b49542011-12-11 22:44:26 +010011975 if (PyUnicode_GET_LENGTH(self) >= width)
11976 return unicode_result_unchanged(self);
11977
11978 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011979}
11980
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011981PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011982 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011983\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011984Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011985
11986static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011987unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011988{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050011989 if (PyUnicode_READY(self) == -1)
11990 return NULL;
11991 if (PyUnicode_IS_ASCII(self))
11992 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010011993 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011994}
11995
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011996#define LEFTSTRIP 0
11997#define RIGHTSTRIP 1
11998#define BOTHSTRIP 2
11999
12000/* Arrays indexed by above */
12001static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
12002
12003#define STRIPNAME(i) (stripformat[i]+3)
12004
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012005/* externally visible for str.strip(unicode) */
12006PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012007_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012008{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012009 void *data;
12010 int kind;
12011 Py_ssize_t i, j, len;
12012 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012013 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012014
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012015 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12016 return NULL;
12017
12018 kind = PyUnicode_KIND(self);
12019 data = PyUnicode_DATA(self);
12020 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012021 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012022 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12023 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012024 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012025
Benjamin Peterson14339b62009-01-31 16:36:08 +000012026 i = 0;
12027 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012028 while (i < len) {
12029 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12030 if (!BLOOM(sepmask, ch))
12031 break;
12032 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12033 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012034 i++;
12035 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012036 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012037
Benjamin Peterson14339b62009-01-31 16:36:08 +000012038 j = len;
12039 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012040 j--;
12041 while (j >= i) {
12042 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12043 if (!BLOOM(sepmask, ch))
12044 break;
12045 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12046 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012047 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012048 }
12049
Benjamin Peterson29060642009-01-31 22:14:21 +000012050 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012051 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012052
Victor Stinner7931d9a2011-11-04 00:22:48 +010012053 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012054}
12055
12056PyObject*
12057PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12058{
12059 unsigned char *data;
12060 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012061 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012062
Victor Stinnerde636f32011-10-01 03:55:54 +020012063 if (PyUnicode_READY(self) == -1)
12064 return NULL;
12065
Victor Stinner684d5fd2012-05-03 02:32:34 +020012066 length = PyUnicode_GET_LENGTH(self);
12067 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012068
Victor Stinner684d5fd2012-05-03 02:32:34 +020012069 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012070 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012071
Victor Stinnerde636f32011-10-01 03:55:54 +020012072 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012073 PyErr_SetString(PyExc_IndexError, "string index out of range");
12074 return NULL;
12075 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012076 if (start >= length || end < start)
12077 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012078
Victor Stinner684d5fd2012-05-03 02:32:34 +020012079 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012080 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012081 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012082 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012083 }
12084 else {
12085 kind = PyUnicode_KIND(self);
12086 data = PyUnicode_1BYTE_DATA(self);
12087 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012088 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012089 length);
12090 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012091}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012092
12093static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012094do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012095{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012096 Py_ssize_t len, i, j;
12097
12098 if (PyUnicode_READY(self) == -1)
12099 return NULL;
12100
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012101 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012102
Victor Stinnercc7af722013-04-09 22:39:24 +020012103 if (PyUnicode_IS_ASCII(self)) {
12104 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12105
12106 i = 0;
12107 if (striptype != RIGHTSTRIP) {
12108 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012109 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012110 if (!_Py_ascii_whitespace[ch])
12111 break;
12112 i++;
12113 }
12114 }
12115
12116 j = len;
12117 if (striptype != LEFTSTRIP) {
12118 j--;
12119 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012120 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012121 if (!_Py_ascii_whitespace[ch])
12122 break;
12123 j--;
12124 }
12125 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012126 }
12127 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012128 else {
12129 int kind = PyUnicode_KIND(self);
12130 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012131
Victor Stinnercc7af722013-04-09 22:39:24 +020012132 i = 0;
12133 if (striptype != RIGHTSTRIP) {
12134 while (i < len) {
12135 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12136 if (!Py_UNICODE_ISSPACE(ch))
12137 break;
12138 i++;
12139 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012140 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012141
12142 j = len;
12143 if (striptype != LEFTSTRIP) {
12144 j--;
12145 while (j >= i) {
12146 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12147 if (!Py_UNICODE_ISSPACE(ch))
12148 break;
12149 j--;
12150 }
12151 j++;
12152 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012153 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012154
Victor Stinner7931d9a2011-11-04 00:22:48 +010012155 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012156}
12157
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012158
12159static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012160do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012161{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012162 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012163
Serhiy Storchakac6792272013-10-19 21:03:34 +030012164 if (!PyArg_ParseTuple(args, stripformat[striptype], &sep))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012165 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012166
Benjamin Peterson14339b62009-01-31 16:36:08 +000012167 if (sep != NULL && sep != Py_None) {
12168 if (PyUnicode_Check(sep))
12169 return _PyUnicode_XStrip(self, striptype, sep);
12170 else {
12171 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012172 "%s arg must be None or str",
12173 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012174 return NULL;
12175 }
12176 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012177
Benjamin Peterson14339b62009-01-31 16:36:08 +000012178 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012179}
12180
12181
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012182PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012183 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012184\n\
12185Return a copy of the string S with leading and trailing\n\
12186whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012187If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012188
12189static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012190unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012191{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012192 if (PyTuple_GET_SIZE(args) == 0)
12193 return do_strip(self, BOTHSTRIP); /* Common case */
12194 else
12195 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012196}
12197
12198
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012199PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012200 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012201\n\
12202Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012203If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012204
12205static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012206unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012207{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012208 if (PyTuple_GET_SIZE(args) == 0)
12209 return do_strip(self, LEFTSTRIP); /* Common case */
12210 else
12211 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012212}
12213
12214
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012215PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012216 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012217\n\
12218Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012219If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012220
12221static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012222unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012223{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012224 if (PyTuple_GET_SIZE(args) == 0)
12225 return do_strip(self, RIGHTSTRIP); /* Common case */
12226 else
12227 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012228}
12229
12230
Guido van Rossumd57fd912000-03-10 22:53:23 +000012231static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012232unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012233{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012234 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012235 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012236
Serhiy Storchaka05997252013-01-26 12:14:02 +020012237 if (len < 1)
12238 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012239
Victor Stinnerc4b49542011-12-11 22:44:26 +010012240 /* no repeat, return original string */
12241 if (len == 1)
12242 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012243
Benjamin Petersonbac79492012-01-14 13:34:47 -050012244 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012245 return NULL;
12246
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012247 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012248 PyErr_SetString(PyExc_OverflowError,
12249 "repeated string is too long");
12250 return NULL;
12251 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012252 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012253
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012254 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012255 if (!u)
12256 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012257 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012258
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012259 if (PyUnicode_GET_LENGTH(str) == 1) {
12260 const int kind = PyUnicode_KIND(str);
12261 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012262 if (kind == PyUnicode_1BYTE_KIND) {
12263 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012264 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012265 }
12266 else if (kind == PyUnicode_2BYTE_KIND) {
12267 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012268 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012269 ucs2[n] = fill_char;
12270 } else {
12271 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12272 assert(kind == PyUnicode_4BYTE_KIND);
12273 for (n = 0; n < len; ++n)
12274 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012275 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012276 }
12277 else {
12278 /* number of characters copied this far */
12279 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012280 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012281 char *to = (char *) PyUnicode_DATA(u);
12282 Py_MEMCPY(to, PyUnicode_DATA(str),
12283 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012284 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012285 n = (done <= nchars-done) ? done : nchars-done;
12286 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012287 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012288 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012289 }
12290
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012291 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012292 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012293}
12294
Alexander Belopolsky40018472011-02-26 01:02:56 +000012295PyObject *
12296PyUnicode_Replace(PyObject *obj,
12297 PyObject *subobj,
12298 PyObject *replobj,
12299 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012300{
12301 PyObject *self;
12302 PyObject *str1;
12303 PyObject *str2;
12304 PyObject *result;
12305
12306 self = PyUnicode_FromObject(obj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012307 if (self == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012308 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012309 str1 = PyUnicode_FromObject(subobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012310 if (str1 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012311 Py_DECREF(self);
12312 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012313 }
12314 str2 = PyUnicode_FromObject(replobj);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012315 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012316 Py_DECREF(self);
12317 Py_DECREF(str1);
12318 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012319 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012320 if (PyUnicode_READY(self) == -1 ||
12321 PyUnicode_READY(str1) == -1 ||
12322 PyUnicode_READY(str2) == -1)
12323 result = NULL;
12324 else
12325 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012326 Py_DECREF(self);
12327 Py_DECREF(str1);
12328 Py_DECREF(str2);
12329 return result;
12330}
12331
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012332PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012333 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012334\n\
12335Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012336old replaced by new. If the optional argument count is\n\
12337given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012338
12339static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012340unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012341{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012342 PyObject *str1;
12343 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012344 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012345 PyObject *result;
12346
Martin v. Löwis18e16552006-02-15 17:27:45 +000012347 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012348 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060012349 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012350 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012351 str1 = PyUnicode_FromObject(str1);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012352 if (str1 == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012353 return NULL;
12354 str2 = PyUnicode_FromObject(str2);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012355 if (str2 == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012356 Py_DECREF(str1);
12357 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012358 }
Benjamin Peterson22a29702012-01-02 09:00:30 -060012359 if (PyUnicode_READY(str1) == -1 || PyUnicode_READY(str2) == -1)
12360 result = NULL;
12361 else
12362 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012363
12364 Py_DECREF(str1);
12365 Py_DECREF(str2);
12366 return result;
12367}
12368
Alexander Belopolsky40018472011-02-26 01:02:56 +000012369static PyObject *
12370unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012371{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012372 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012373 Py_ssize_t isize;
12374 Py_ssize_t osize, squote, dquote, i, o;
12375 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012376 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012377 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012378
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012379 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012380 return NULL;
12381
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012382 isize = PyUnicode_GET_LENGTH(unicode);
12383 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012384
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012385 /* Compute length of output, quote characters, and
12386 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012387 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012388 max = 127;
12389 squote = dquote = 0;
12390 ikind = PyUnicode_KIND(unicode);
12391 for (i = 0; i < isize; i++) {
12392 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012393 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012394 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012395 case '\'': squote++; break;
12396 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012397 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012398 incr = 2;
12399 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012400 default:
12401 /* Fast-path ASCII */
12402 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012403 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012404 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012405 ;
12406 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012407 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012408 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012409 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012410 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012411 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012412 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012413 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012414 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012415 if (osize > PY_SSIZE_T_MAX - incr) {
12416 PyErr_SetString(PyExc_OverflowError,
12417 "string is too long to generate repr");
12418 return NULL;
12419 }
12420 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012421 }
12422
12423 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012424 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012425 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012426 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012427 if (dquote)
12428 /* Both squote and dquote present. Use squote,
12429 and escape them */
12430 osize += squote;
12431 else
12432 quote = '"';
12433 }
Victor Stinner55c08782013-04-14 18:45:39 +020012434 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012435
12436 repr = PyUnicode_New(osize, max);
12437 if (repr == NULL)
12438 return NULL;
12439 okind = PyUnicode_KIND(repr);
12440 odata = PyUnicode_DATA(repr);
12441
12442 PyUnicode_WRITE(okind, odata, 0, quote);
12443 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012444 if (unchanged) {
12445 _PyUnicode_FastCopyCharacters(repr, 1,
12446 unicode, 0,
12447 isize);
12448 }
12449 else {
12450 for (i = 0, o = 1; i < isize; i++) {
12451 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012452
Victor Stinner55c08782013-04-14 18:45:39 +020012453 /* Escape quotes and backslashes */
12454 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012455 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012456 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012457 continue;
12458 }
12459
12460 /* Map special whitespace to '\t', \n', '\r' */
12461 if (ch == '\t') {
12462 PyUnicode_WRITE(okind, odata, o++, '\\');
12463 PyUnicode_WRITE(okind, odata, o++, 't');
12464 }
12465 else if (ch == '\n') {
12466 PyUnicode_WRITE(okind, odata, o++, '\\');
12467 PyUnicode_WRITE(okind, odata, o++, 'n');
12468 }
12469 else if (ch == '\r') {
12470 PyUnicode_WRITE(okind, odata, o++, '\\');
12471 PyUnicode_WRITE(okind, odata, o++, 'r');
12472 }
12473
12474 /* Map non-printable US ASCII to '\xhh' */
12475 else if (ch < ' ' || ch == 0x7F) {
12476 PyUnicode_WRITE(okind, odata, o++, '\\');
12477 PyUnicode_WRITE(okind, odata, o++, 'x');
12478 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12479 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12480 }
12481
12482 /* Copy ASCII characters as-is */
12483 else if (ch < 0x7F) {
12484 PyUnicode_WRITE(okind, odata, o++, ch);
12485 }
12486
12487 /* Non-ASCII characters */
12488 else {
12489 /* Map Unicode whitespace and control characters
12490 (categories Z* and C* except ASCII space)
12491 */
12492 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12493 PyUnicode_WRITE(okind, odata, o++, '\\');
12494 /* Map 8-bit characters to '\xhh' */
12495 if (ch <= 0xff) {
12496 PyUnicode_WRITE(okind, odata, o++, 'x');
12497 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12498 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12499 }
12500 /* Map 16-bit characters to '\uxxxx' */
12501 else if (ch <= 0xffff) {
12502 PyUnicode_WRITE(okind, odata, o++, 'u');
12503 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12504 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12505 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12506 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12507 }
12508 /* Map 21-bit characters to '\U00xxxxxx' */
12509 else {
12510 PyUnicode_WRITE(okind, odata, o++, 'U');
12511 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12512 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12513 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12514 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12515 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12516 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12517 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12518 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12519 }
12520 }
12521 /* Copy characters as-is */
12522 else {
12523 PyUnicode_WRITE(okind, odata, o++, ch);
12524 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012525 }
12526 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012527 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012528 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012529 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012530 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012531}
12532
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012533PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012534 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012535\n\
12536Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012537such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012538arguments start and end are interpreted as in slice notation.\n\
12539\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012540Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012541
12542static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012543unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012544{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012545 /* initialize variables to prevent gcc warning */
12546 PyObject *substring = NULL;
12547 Py_ssize_t start = 0;
12548 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012549 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012550
Jesus Ceaac451502011-04-20 17:09:23 +020012551 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12552 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012553 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012554
Christian Heimesea71a522013-06-29 21:17:34 +020012555 if (PyUnicode_READY(self) == -1) {
12556 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012557 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012558 }
12559 if (PyUnicode_READY(substring) == -1) {
12560 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012561 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012562 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012563
Victor Stinner7931d9a2011-11-04 00:22:48 +010012564 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012565
12566 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012567
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012568 if (result == -2)
12569 return NULL;
12570
Christian Heimes217cfd12007-12-02 14:31:20 +000012571 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012572}
12573
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012574PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012575 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012576\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012577Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012578
12579static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012580unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012581{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012582 /* initialize variables to prevent gcc warning */
12583 PyObject *substring = NULL;
12584 Py_ssize_t start = 0;
12585 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012586 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012587
Jesus Ceaac451502011-04-20 17:09:23 +020012588 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12589 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012590 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012591
Christian Heimesea71a522013-06-29 21:17:34 +020012592 if (PyUnicode_READY(self) == -1) {
12593 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012594 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012595 }
12596 if (PyUnicode_READY(substring) == -1) {
12597 Py_DECREF(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012598 return NULL;
Christian Heimesea71a522013-06-29 21:17:34 +020012599 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012600
Victor Stinner7931d9a2011-11-04 00:22:48 +010012601 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012602
12603 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012604
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012605 if (result == -2)
12606 return NULL;
12607
Guido van Rossumd57fd912000-03-10 22:53:23 +000012608 if (result < 0) {
12609 PyErr_SetString(PyExc_ValueError, "substring not found");
12610 return NULL;
12611 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012612
Christian Heimes217cfd12007-12-02 14:31:20 +000012613 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012614}
12615
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012616PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012617 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012618\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012619Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012620done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012621
12622static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012623unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012624{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012625 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012626 Py_UCS4 fillchar = ' ';
12627
Victor Stinnere9a29352011-10-01 02:14:59 +020012628 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012629 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012630
Benjamin Petersonbac79492012-01-14 13:34:47 -050012631 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012632 return NULL;
12633
Victor Stinnerc4b49542011-12-11 22:44:26 +010012634 if (PyUnicode_GET_LENGTH(self) >= width)
12635 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012636
Victor Stinnerc4b49542011-12-11 22:44:26 +010012637 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012638}
12639
Alexander Belopolsky40018472011-02-26 01:02:56 +000012640PyObject *
12641PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012642{
12643 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012644
Guido van Rossumd57fd912000-03-10 22:53:23 +000012645 s = PyUnicode_FromObject(s);
12646 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012647 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012648 if (sep != NULL) {
12649 sep = PyUnicode_FromObject(sep);
12650 if (sep == NULL) {
12651 Py_DECREF(s);
12652 return NULL;
12653 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012654 }
12655
Victor Stinner9310abb2011-10-05 00:59:23 +020012656 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012657
12658 Py_DECREF(s);
12659 Py_XDECREF(sep);
12660 return result;
12661}
12662
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012663PyDoc_STRVAR(split__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012664 "S.split(sep=None, maxsplit=-1) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012665\n\
12666Return a list of the words in S, using sep as the\n\
12667delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012668splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012669whitespace string is a separator and empty strings are\n\
12670removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012671
12672static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012673unicode_split(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012674{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012675 static char *kwlist[] = {"sep", "maxsplit", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000012676 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012677 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012678
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012679 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:split",
12680 kwlist, &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012681 return NULL;
12682
12683 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012684 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012685 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012686 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012687 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012688 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012689}
12690
Thomas Wouters477c8d52006-05-27 19:21:47 +000012691PyObject *
12692PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12693{
12694 PyObject* str_obj;
12695 PyObject* sep_obj;
12696 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012697 int kind1, kind2;
12698 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012699 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012700
12701 str_obj = PyUnicode_FromObject(str_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012702 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012703 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012704 sep_obj = PyUnicode_FromObject(sep_in);
Benjamin Peterson22a29702012-01-02 09:00:30 -060012705 if (!sep_obj) {
12706 Py_DECREF(str_obj);
12707 return NULL;
12708 }
12709 if (PyUnicode_READY(sep_obj) == -1 || PyUnicode_READY(str_obj) == -1) {
12710 Py_DECREF(sep_obj);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012711 Py_DECREF(str_obj);
12712 return NULL;
12713 }
12714
Victor Stinner14f8f022011-10-05 20:58:25 +020012715 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012716 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012717 len1 = PyUnicode_GET_LENGTH(str_obj);
12718 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012719 if (kind1 < kind2 || len1 < len2) {
12720 _Py_INCREF_UNICODE_EMPTY();
12721 if (!unicode_empty)
12722 out = NULL;
12723 else {
12724 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12725 Py_DECREF(unicode_empty);
12726 }
12727 Py_DECREF(sep_obj);
12728 Py_DECREF(str_obj);
12729 return out;
12730 }
12731 buf1 = PyUnicode_DATA(str_obj);
12732 buf2 = PyUnicode_DATA(sep_obj);
12733 if (kind2 != kind1) {
12734 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12735 if (!buf2)
12736 goto onError;
12737 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012738
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012739 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012740 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012741 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12742 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12743 else
12744 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012745 break;
12746 case PyUnicode_2BYTE_KIND:
12747 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12748 break;
12749 case PyUnicode_4BYTE_KIND:
12750 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12751 break;
12752 default:
12753 assert(0);
12754 out = 0;
12755 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012756
12757 Py_DECREF(sep_obj);
12758 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012759 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012760 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012761
12762 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012763 onError:
12764 Py_DECREF(sep_obj);
12765 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012766 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012767 PyMem_Free(buf2);
12768 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012769}
12770
12771
12772PyObject *
12773PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12774{
12775 PyObject* str_obj;
12776 PyObject* sep_obj;
12777 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012778 int kind1, kind2;
12779 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012780 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012781
12782 str_obj = PyUnicode_FromObject(str_in);
12783 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012784 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012785 sep_obj = PyUnicode_FromObject(sep_in);
12786 if (!sep_obj) {
12787 Py_DECREF(str_obj);
12788 return NULL;
12789 }
12790
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012791 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012792 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012793 len1 = PyUnicode_GET_LENGTH(str_obj);
12794 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012795 if (kind1 < kind2 || len1 < len2) {
12796 _Py_INCREF_UNICODE_EMPTY();
12797 if (!unicode_empty)
12798 out = NULL;
12799 else {
12800 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
12801 Py_DECREF(unicode_empty);
12802 }
12803 Py_DECREF(sep_obj);
12804 Py_DECREF(str_obj);
12805 return out;
12806 }
12807 buf1 = PyUnicode_DATA(str_obj);
12808 buf2 = PyUnicode_DATA(sep_obj);
12809 if (kind2 != kind1) {
12810 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12811 if (!buf2)
12812 goto onError;
12813 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012814
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012815 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012816 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012817 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12818 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12819 else
12820 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012821 break;
12822 case PyUnicode_2BYTE_KIND:
12823 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12824 break;
12825 case PyUnicode_4BYTE_KIND:
12826 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12827 break;
12828 default:
12829 assert(0);
12830 out = 0;
12831 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012832
12833 Py_DECREF(sep_obj);
12834 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012835 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012836 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012837
12838 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012839 onError:
12840 Py_DECREF(sep_obj);
12841 Py_DECREF(str_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012842 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012843 PyMem_Free(buf2);
12844 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012845}
12846
12847PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012848 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012849\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012850Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012851the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012852found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012853
12854static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012855unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012856{
Victor Stinner9310abb2011-10-05 00:59:23 +020012857 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012858}
12859
12860PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012861 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012862\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012863Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012864the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012865separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012866
12867static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012868unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012869{
Victor Stinner9310abb2011-10-05 00:59:23 +020012870 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012871}
12872
Alexander Belopolsky40018472011-02-26 01:02:56 +000012873PyObject *
12874PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012875{
12876 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012877
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012878 s = PyUnicode_FromObject(s);
12879 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012880 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012881 if (sep != NULL) {
12882 sep = PyUnicode_FromObject(sep);
12883 if (sep == NULL) {
12884 Py_DECREF(s);
12885 return NULL;
12886 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012887 }
12888
Victor Stinner9310abb2011-10-05 00:59:23 +020012889 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012890
12891 Py_DECREF(s);
12892 Py_XDECREF(sep);
12893 return result;
12894}
12895
12896PyDoc_STRVAR(rsplit__doc__,
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012897 "S.rsplit(sep=None, maxsplit=-1) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012898\n\
12899Return a list of the words in S, using sep as the\n\
12900delimiter string, starting at the end of the string and\n\
12901working to the front. If maxsplit is given, at most maxsplit\n\
12902splits are done. If sep is not specified, any whitespace string\n\
12903is a separator.");
12904
12905static PyObject*
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012906unicode_rsplit(PyObject *self, PyObject *args, PyObject *kwds)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012907{
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012908 static char *kwlist[] = {"sep", "maxsplit", 0};
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012909 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012910 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012911
Ezio Melotticda6b6d2012-02-26 09:39:55 +020012912 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|On:rsplit",
12913 kwlist, &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012914 return NULL;
12915
12916 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012917 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012918 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012919 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012920 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012921 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012922}
12923
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012924PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012925 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012926\n\
12927Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012928Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012929is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012930
12931static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012932unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012933{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012934 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012935 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012936
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012937 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12938 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012939 return NULL;
12940
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012941 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012942}
12943
12944static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012945PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012946{
Victor Stinnerc4b49542011-12-11 22:44:26 +010012947 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012948}
12949
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012950PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012951 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012952\n\
12953Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012954and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012955
12956static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012957unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012958{
Benjamin Petersoneea48462012-01-16 14:28:50 -050012959 if (PyUnicode_READY(self) == -1)
12960 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012961 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012962}
12963
Larry Hastings61272b72014-01-07 12:41:53 -080012964/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000012965
Larry Hastings31826802013-10-19 00:09:25 -070012966@staticmethod
12967str.maketrans as unicode_maketrans
12968
12969 x: object
12970
12971 y: unicode=NULL
12972
12973 z: unicode=NULL
12974
12975 /
12976
12977Return a translation table usable for str.translate().
12978
12979If there is only one argument, it must be a dictionary mapping Unicode
12980ordinals (integers) or characters to Unicode ordinals, strings or None.
12981Character keys will be then converted to ordinals.
12982If there are two arguments, they must be strings of equal length, and
12983in the resulting dictionary, each character in x will be mapped to the
12984character at the same position in y. If there is a third argument, it
12985must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080012986[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070012987
Larry Hastings31826802013-10-19 00:09:25 -070012988static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080012989unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030012990/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070012991{
Georg Brandlceee0772007-11-27 23:48:05 +000012992 PyObject *new = NULL, *key, *value;
12993 Py_ssize_t i = 0;
12994 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012995
Georg Brandlceee0772007-11-27 23:48:05 +000012996 new = PyDict_New();
12997 if (!new)
12998 return NULL;
12999 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013000 int x_kind, y_kind, z_kind;
13001 void *x_data, *y_data, *z_data;
13002
Georg Brandlceee0772007-11-27 23:48:05 +000013003 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000013004 if (!PyUnicode_Check(x)) {
13005 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13006 "be a string if there is a second argument");
13007 goto err;
13008 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013009 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013010 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13011 "arguments must have equal length");
13012 goto err;
13013 }
13014 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013015 x_kind = PyUnicode_KIND(x);
13016 y_kind = PyUnicode_KIND(y);
13017 x_data = PyUnicode_DATA(x);
13018 y_data = PyUnicode_DATA(y);
13019 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13020 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013021 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013022 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013023 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013024 if (!value) {
13025 Py_DECREF(key);
13026 goto err;
13027 }
Georg Brandlceee0772007-11-27 23:48:05 +000013028 res = PyDict_SetItem(new, key, value);
13029 Py_DECREF(key);
13030 Py_DECREF(value);
13031 if (res < 0)
13032 goto err;
13033 }
13034 /* create entries for deleting chars in z */
13035 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013036 z_kind = PyUnicode_KIND(z);
13037 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013038 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013039 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013040 if (!key)
13041 goto err;
13042 res = PyDict_SetItem(new, key, Py_None);
13043 Py_DECREF(key);
13044 if (res < 0)
13045 goto err;
13046 }
13047 }
13048 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013049 int kind;
13050 void *data;
13051
Georg Brandlceee0772007-11-27 23:48:05 +000013052 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013053 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013054 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13055 "to maketrans it must be a dict");
13056 goto err;
13057 }
13058 /* copy entries into the new dict, converting string keys to int keys */
13059 while (PyDict_Next(x, &i, &key, &value)) {
13060 if (PyUnicode_Check(key)) {
13061 /* convert string keys to integer keys */
13062 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013063 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013064 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13065 "table must be of length 1");
13066 goto err;
13067 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013068 kind = PyUnicode_KIND(key);
13069 data = PyUnicode_DATA(key);
13070 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013071 if (!newkey)
13072 goto err;
13073 res = PyDict_SetItem(new, newkey, value);
13074 Py_DECREF(newkey);
13075 if (res < 0)
13076 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013077 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013078 /* just keep integer keys */
13079 if (PyDict_SetItem(new, key, value) < 0)
13080 goto err;
13081 } else {
13082 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13083 "be strings or integers");
13084 goto err;
13085 }
13086 }
13087 }
13088 return new;
13089 err:
13090 Py_DECREF(new);
13091 return NULL;
13092}
13093
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013094PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013095 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013096\n\
Zachary Ware79b98df2015-08-05 23:54:15 -050013097Return a copy of the string S in which each character has been mapped\n\
13098through the given translation table. The table must implement\n\
13099lookup/indexing via __getitem__, for instance a dictionary or list,\n\
13100mapping Unicode ordinals to Unicode ordinals, strings, or None. If\n\
13101this operation raises LookupError, the character is left untouched.\n\
13102Characters mapped to None are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013103
13104static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013105unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013106{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013107 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013108}
13109
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013110PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013111 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013112\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013113Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013114
13115static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020013116unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013117{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013118 if (PyUnicode_READY(self) == -1)
13119 return NULL;
13120 if (PyUnicode_IS_ASCII(self))
13121 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013122 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013123}
13124
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013125PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013126 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013127\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000013128Pad a numeric string S with zeros on the left, to fill a field\n\
13129of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013130
13131static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020013132unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013133{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013134 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013135 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013136 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013137 int kind;
13138 void *data;
13139 Py_UCS4 chr;
13140
Martin v. Löwis18e16552006-02-15 17:27:45 +000013141 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000013142 return NULL;
13143
Benjamin Petersonbac79492012-01-14 13:34:47 -050013144 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013145 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013146
Victor Stinnerc4b49542011-12-11 22:44:26 +010013147 if (PyUnicode_GET_LENGTH(self) >= width)
13148 return unicode_result_unchanged(self);
13149
13150 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013151
13152 u = pad(self, fill, 0, '0');
13153
Walter Dörwald068325e2002-04-15 13:36:47 +000013154 if (u == NULL)
13155 return NULL;
13156
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013157 kind = PyUnicode_KIND(u);
13158 data = PyUnicode_DATA(u);
13159 chr = PyUnicode_READ(kind, data, fill);
13160
13161 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013162 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013163 PyUnicode_WRITE(kind, data, 0, chr);
13164 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013165 }
13166
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013167 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013168 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013169}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013170
13171#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013172static PyObject *
13173unicode__decimal2ascii(PyObject *self)
13174{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013175 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013176}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013177#endif
13178
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013179PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013180 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013181\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013182Return True if S starts with the specified prefix, False otherwise.\n\
13183With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013184With optional end, stop comparing S at that position.\n\
13185prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013186
13187static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013188unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013189 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013190{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013191 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013192 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013193 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013194 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013195 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013196
Jesus Ceaac451502011-04-20 17:09:23 +020013197 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013198 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013199 if (PyTuple_Check(subobj)) {
13200 Py_ssize_t i;
13201 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013202 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013203 if (substring == NULL)
13204 return NULL;
13205 result = tailmatch(self, substring, start, end, -1);
13206 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013207 if (result == -1)
13208 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013209 if (result) {
13210 Py_RETURN_TRUE;
13211 }
13212 }
13213 /* nothing matched */
13214 Py_RETURN_FALSE;
13215 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013216 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013217 if (substring == NULL) {
13218 if (PyErr_ExceptionMatches(PyExc_TypeError))
13219 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
13220 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013221 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013222 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013223 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013224 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013225 if (result == -1)
13226 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013227 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013228}
13229
13230
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013231PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013232 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013233\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013234Return True if S ends with the specified suffix, False otherwise.\n\
13235With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013236With optional end, stop comparing S at that position.\n\
13237suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013238
13239static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013240unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013241 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013242{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013243 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013244 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013245 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013246 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013247 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013248
Jesus Ceaac451502011-04-20 17:09:23 +020013249 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013250 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013251 if (PyTuple_Check(subobj)) {
13252 Py_ssize_t i;
13253 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013254 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000013255 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013256 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000013257 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013258 result = tailmatch(self, substring, start, end, +1);
13259 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013260 if (result == -1)
13261 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013262 if (result) {
13263 Py_RETURN_TRUE;
13264 }
13265 }
13266 Py_RETURN_FALSE;
13267 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013268 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030013269 if (substring == NULL) {
13270 if (PyErr_ExceptionMatches(PyExc_TypeError))
13271 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
13272 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013273 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013274 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013275 result = tailmatch(self, substring, start, end, +1);
Christian Heimes305e49e2013-06-29 20:41:06 +020013276 Py_DECREF(substring);
Victor Stinner18aa4472013-01-03 03:18:09 +010013277 if (result == -1)
13278 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013279 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013280}
13281
Victor Stinner202fdca2012-05-07 12:47:02 +020013282Py_LOCAL_INLINE(void)
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013283_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013284{
Victor Stinner8f674cc2013-04-17 23:02:17 +020013285 if (!writer->readonly)
13286 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
13287 else {
13288 /* Copy-on-write mode: set buffer size to 0 so
13289 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13290 * next write. */
13291 writer->size = 0;
13292 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013293 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13294 writer->data = PyUnicode_DATA(writer->buffer);
13295 writer->kind = PyUnicode_KIND(writer->buffer);
13296}
13297
Victor Stinnerd3f08822012-05-29 12:57:52 +020013298void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013299_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013300{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013301 memset(writer, 0, sizeof(*writer));
13302#ifdef Py_DEBUG
13303 writer->kind = 5; /* invalid kind */
13304#endif
Victor Stinner8f674cc2013-04-17 23:02:17 +020013305 writer->min_char = 127;
Victor Stinner202fdca2012-05-07 12:47:02 +020013306}
13307
Victor Stinnerd3f08822012-05-29 12:57:52 +020013308int
13309_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13310 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013311{
Victor Stinner6989ba02013-11-18 21:08:39 +010013312#ifdef MS_WINDOWS
13313 /* On Windows, overallocate by 50% is the best factor */
13314# define OVERALLOCATE_FACTOR 2
13315#else
13316 /* On Linux, overallocate by 25% is the best factor */
13317# define OVERALLOCATE_FACTOR 4
13318#endif
Victor Stinner202fdca2012-05-07 12:47:02 +020013319 Py_ssize_t newlen;
13320 PyObject *newbuffer;
13321
Victor Stinnerd3f08822012-05-29 12:57:52 +020013322 assert(length > 0);
13323
Victor Stinner202fdca2012-05-07 12:47:02 +020013324 if (length > PY_SSIZE_T_MAX - writer->pos) {
13325 PyErr_NoMemory();
13326 return -1;
13327 }
13328 newlen = writer->pos + length;
13329
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013330 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013331
Victor Stinnerd3f08822012-05-29 12:57:52 +020013332 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013333 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013334 if (writer->overallocate
13335 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13336 /* overallocate to limit the number of realloc() */
13337 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013338 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013339 if (newlen < writer->min_length)
13340 newlen = writer->min_length;
13341
Victor Stinnerd3f08822012-05-29 12:57:52 +020013342 writer->buffer = PyUnicode_New(newlen, maxchar);
13343 if (writer->buffer == NULL)
13344 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013345 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013346 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013347 if (writer->overallocate
13348 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13349 /* overallocate to limit the number of realloc() */
13350 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013351 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013352 if (newlen < writer->min_length)
13353 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013354
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013355 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013356 /* resize + widen */
13357 newbuffer = PyUnicode_New(newlen, maxchar);
13358 if (newbuffer == NULL)
13359 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013360 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13361 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013362 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013363 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013364 }
13365 else {
13366 newbuffer = resize_compact(writer->buffer, newlen);
13367 if (newbuffer == NULL)
13368 return -1;
13369 }
13370 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013371 }
13372 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013373 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013374 newbuffer = PyUnicode_New(writer->size, maxchar);
13375 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013376 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013377 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13378 writer->buffer, 0, writer->pos);
13379 Py_DECREF(writer->buffer);
13380 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013381 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013382 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013383 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013384
13385#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013386}
13387
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013388Py_LOCAL_INLINE(int)
13389_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013390{
13391 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13392 return -1;
13393 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13394 writer->pos++;
13395 return 0;
13396}
13397
13398int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013399_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13400{
13401 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13402}
13403
13404int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013405_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13406{
13407 Py_UCS4 maxchar;
13408 Py_ssize_t len;
13409
13410 if (PyUnicode_READY(str) == -1)
13411 return -1;
13412 len = PyUnicode_GET_LENGTH(str);
13413 if (len == 0)
13414 return 0;
13415 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13416 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013417 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013418 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013419 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013420 Py_INCREF(str);
13421 writer->buffer = str;
13422 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013423 writer->pos += len;
13424 return 0;
13425 }
13426 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13427 return -1;
13428 }
13429 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13430 str, 0, len);
13431 writer->pos += len;
13432 return 0;
13433}
13434
Victor Stinnere215d962012-10-06 23:03:36 +020013435int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013436_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13437 Py_ssize_t start, Py_ssize_t end)
13438{
13439 Py_UCS4 maxchar;
13440 Py_ssize_t len;
13441
13442 if (PyUnicode_READY(str) == -1)
13443 return -1;
13444
13445 assert(0 <= start);
13446 assert(end <= PyUnicode_GET_LENGTH(str));
13447 assert(start <= end);
13448
13449 if (end == 0)
13450 return 0;
13451
13452 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13453 return _PyUnicodeWriter_WriteStr(writer, str);
13454
13455 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13456 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13457 else
13458 maxchar = writer->maxchar;
13459 len = end - start;
13460
13461 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13462 return -1;
13463
13464 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13465 str, start, len);
13466 writer->pos += len;
13467 return 0;
13468}
13469
13470int
Victor Stinner4a587072013-11-19 12:54:53 +010013471_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13472 const char *ascii, Py_ssize_t len)
13473{
13474 if (len == -1)
13475 len = strlen(ascii);
13476
13477 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13478
13479 if (writer->buffer == NULL && !writer->overallocate) {
13480 PyObject *str;
13481
13482 str = _PyUnicode_FromASCII(ascii, len);
13483 if (str == NULL)
13484 return -1;
13485
13486 writer->readonly = 1;
13487 writer->buffer = str;
13488 _PyUnicodeWriter_Update(writer);
13489 writer->pos += len;
13490 return 0;
13491 }
13492
13493 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13494 return -1;
13495
13496 switch (writer->kind)
13497 {
13498 case PyUnicode_1BYTE_KIND:
13499 {
13500 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13501 Py_UCS1 *data = writer->data;
13502
13503 Py_MEMCPY(data + writer->pos, str, len);
13504 break;
13505 }
13506 case PyUnicode_2BYTE_KIND:
13507 {
13508 _PyUnicode_CONVERT_BYTES(
13509 Py_UCS1, Py_UCS2,
13510 ascii, ascii + len,
13511 (Py_UCS2 *)writer->data + writer->pos);
13512 break;
13513 }
13514 case PyUnicode_4BYTE_KIND:
13515 {
13516 _PyUnicode_CONVERT_BYTES(
13517 Py_UCS1, Py_UCS4,
13518 ascii, ascii + len,
13519 (Py_UCS4 *)writer->data + writer->pos);
13520 break;
13521 }
13522 default:
13523 assert(0);
13524 }
13525
13526 writer->pos += len;
13527 return 0;
13528}
13529
13530int
13531_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13532 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013533{
13534 Py_UCS4 maxchar;
13535
13536 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13537 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13538 return -1;
13539 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13540 writer->pos += len;
13541 return 0;
13542}
13543
Victor Stinnerd3f08822012-05-29 12:57:52 +020013544PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013545_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013546{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013547 PyObject *str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013548 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013549 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013550 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013551 }
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013552 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013553 str = writer->buffer;
13554 writer->buffer = NULL;
13555 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13556 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013557 }
13558 if (PyUnicode_GET_LENGTH(writer->buffer) != writer->pos) {
13559 PyObject *newbuffer;
13560 newbuffer = resize_compact(writer->buffer, writer->pos);
13561 if (newbuffer == NULL) {
Serhiy Storchakadfe98a12014-02-09 13:46:20 +020013562 Py_CLEAR(writer->buffer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013563 return NULL;
13564 }
13565 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013566 }
Victor Stinner15a0bd32013-07-08 22:29:55 +020013567 str = writer->buffer;
13568 writer->buffer = NULL;
13569 assert(_PyUnicode_CheckConsistency(str, 1));
13570 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013571}
13572
Victor Stinnerd3f08822012-05-29 12:57:52 +020013573void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013574_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013575{
13576 Py_CLEAR(writer->buffer);
13577}
13578
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013579#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013580
13581PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013582 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013583\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013584Return a formatted version of S, using substitutions from args and kwargs.\n\
13585The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013586
Eric Smith27bbca62010-11-04 17:06:58 +000013587PyDoc_STRVAR(format_map__doc__,
13588 "S.format_map(mapping) -> str\n\
13589\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013590Return a formatted version of S, using substitutions from mapping.\n\
13591The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013592
Eric Smith4a7d76d2008-05-30 18:10:19 +000013593static PyObject *
13594unicode__format__(PyObject* self, PyObject* args)
13595{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013596 PyObject *format_spec;
13597 _PyUnicodeWriter writer;
13598 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013599
13600 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
13601 return NULL;
13602
Victor Stinnerd3f08822012-05-29 12:57:52 +020013603 if (PyUnicode_READY(self) == -1)
13604 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013605 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013606 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13607 self, format_spec, 0,
13608 PyUnicode_GET_LENGTH(format_spec));
13609 if (ret == -1) {
13610 _PyUnicodeWriter_Dealloc(&writer);
13611 return NULL;
13612 }
13613 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013614}
13615
Eric Smith8c663262007-08-25 02:26:07 +000013616PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013617 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013618\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013619Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000013620
13621static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013622unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013623{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013624 Py_ssize_t size;
13625
13626 /* If it's a compact object, account for base structure +
13627 character data. */
13628 if (PyUnicode_IS_COMPACT_ASCII(v))
13629 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
13630 else if (PyUnicode_IS_COMPACT(v))
13631 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013632 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013633 else {
13634 /* If it is a two-block object, account for base object, and
13635 for character block if present. */
13636 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013637 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013638 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013639 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013640 }
13641 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013642 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013643 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013644 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013645 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013646 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013647
13648 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013649}
13650
13651PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013652 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013653
13654static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013655unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013656{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013657 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013658 if (!copy)
13659 return NULL;
13660 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013661}
13662
Guido van Rossumd57fd912000-03-10 22:53:23 +000013663static PyMethodDef unicode_methods[] = {
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013664 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013665 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
Ezio Melotticda6b6d2012-02-26 09:39:55 +020013666 {"split", (PyCFunction) unicode_split, METH_VARARGS | METH_KEYWORDS, split__doc__},
13667 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS | METH_KEYWORDS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013668 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13669 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
Benjamin Petersond5890c82012-01-14 13:23:30 -050013670 {"casefold", (PyCFunction) unicode_casefold, METH_NOARGS, casefold__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013671 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13672 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13673 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013674 {"expandtabs", (PyCFunction) unicode_expandtabs,
13675 METH_VARARGS | METH_KEYWORDS, expandtabs__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013676 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013677 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013678 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13679 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13680 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013681 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013682 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13683 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13684 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013685 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013686 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Ezio Melotti745d54d2013-11-16 19:10:57 +020013687 {"splitlines", (PyCFunction) unicode_splitlines,
13688 METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013689 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013690 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13691 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13692 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13693 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13694 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13695 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13696 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13697 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13698 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13699 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13700 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13701 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13702 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13703 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013704 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013705 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013706 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013707 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013708 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013709 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Larry Hastings31826802013-10-19 00:09:25 -070013710 UNICODE_MAKETRANS_METHODDEF
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013711 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013712#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013713 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013714 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013715#endif
13716
Benjamin Peterson14339b62009-01-31 16:36:08 +000013717 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013718 {NULL, NULL}
13719};
13720
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013721static PyObject *
13722unicode_mod(PyObject *v, PyObject *w)
13723{
Brian Curtindfc80e32011-08-10 20:28:54 -050013724 if (!PyUnicode_Check(v))
13725 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013726 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013727}
13728
13729static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013730 0, /*nb_add*/
13731 0, /*nb_subtract*/
13732 0, /*nb_multiply*/
13733 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013734};
13735
Guido van Rossumd57fd912000-03-10 22:53:23 +000013736static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013737 (lenfunc) unicode_length, /* sq_length */
13738 PyUnicode_Concat, /* sq_concat */
13739 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13740 (ssizeargfunc) unicode_getitem, /* sq_item */
13741 0, /* sq_slice */
13742 0, /* sq_ass_item */
13743 0, /* sq_ass_slice */
13744 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013745};
13746
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013747static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013748unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013749{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013750 if (PyUnicode_READY(self) == -1)
13751 return NULL;
13752
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013753 if (PyIndex_Check(item)) {
13754 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013755 if (i == -1 && PyErr_Occurred())
13756 return NULL;
13757 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013758 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013759 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013760 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013761 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013762 PyObject *result;
13763 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013764 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013765 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013766
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013767 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013768 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013769 return NULL;
13770 }
13771
13772 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013773 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013774 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013775 slicelength == PyUnicode_GET_LENGTH(self)) {
13776 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013777 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013778 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013779 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013780 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013781 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013782 src_kind = PyUnicode_KIND(self);
13783 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013784 if (!PyUnicode_IS_ASCII(self)) {
13785 kind_limit = kind_maxchar_limit(src_kind);
13786 max_char = 0;
13787 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13788 ch = PyUnicode_READ(src_kind, src_data, cur);
13789 if (ch > max_char) {
13790 max_char = ch;
13791 if (max_char >= kind_limit)
13792 break;
13793 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013794 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013795 }
Victor Stinner55c99112011-10-13 01:17:06 +020013796 else
13797 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013798 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013799 if (result == NULL)
13800 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013801 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013802 dest_data = PyUnicode_DATA(result);
13803
13804 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013805 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13806 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013807 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013808 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013809 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013810 } else {
13811 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13812 return NULL;
13813 }
13814}
13815
13816static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013817 (lenfunc)unicode_length, /* mp_length */
13818 (binaryfunc)unicode_subscript, /* mp_subscript */
13819 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013820};
13821
Guido van Rossumd57fd912000-03-10 22:53:23 +000013822
Guido van Rossumd57fd912000-03-10 22:53:23 +000013823/* Helpers for PyUnicode_Format() */
13824
Victor Stinnera47082312012-10-04 02:19:54 +020013825struct unicode_formatter_t {
13826 PyObject *args;
13827 int args_owned;
13828 Py_ssize_t arglen, argidx;
13829 PyObject *dict;
13830
13831 enum PyUnicode_Kind fmtkind;
13832 Py_ssize_t fmtcnt, fmtpos;
13833 void *fmtdata;
13834 PyObject *fmtstr;
13835
13836 _PyUnicodeWriter writer;
13837};
13838
13839struct unicode_format_arg_t {
13840 Py_UCS4 ch;
13841 int flags;
13842 Py_ssize_t width;
13843 int prec;
13844 int sign;
13845};
13846
Guido van Rossumd57fd912000-03-10 22:53:23 +000013847static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013848unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013849{
Victor Stinnera47082312012-10-04 02:19:54 +020013850 Py_ssize_t argidx = ctx->argidx;
13851
13852 if (argidx < ctx->arglen) {
13853 ctx->argidx++;
13854 if (ctx->arglen < 0)
13855 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000013856 else
Victor Stinnera47082312012-10-04 02:19:54 +020013857 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013858 }
13859 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013860 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013861 return NULL;
13862}
13863
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013864/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013865
Victor Stinnera47082312012-10-04 02:19:54 +020013866/* Format a float into the writer if the writer is not NULL, or into *p_output
13867 otherwise.
13868
13869 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020013870static int
Victor Stinnera47082312012-10-04 02:19:54 +020013871formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
13872 PyObject **p_output,
13873 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013874{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013875 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013876 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013877 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020013878 int prec;
13879 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000013880
Guido van Rossumd57fd912000-03-10 22:53:23 +000013881 x = PyFloat_AsDouble(v);
13882 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020013883 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013884
Victor Stinnera47082312012-10-04 02:19:54 +020013885 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013886 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013887 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013888
Victor Stinnera47082312012-10-04 02:19:54 +020013889 if (arg->flags & F_ALT)
13890 dtoa_flags = Py_DTSF_ALT;
13891 else
13892 dtoa_flags = 0;
13893 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013894 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020013895 return -1;
13896 len = strlen(p);
13897 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010013898 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020013899 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013900 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020013901 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020013902 }
13903 else
13904 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000013905 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013906 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013907}
13908
Victor Stinnerd0880d52012-04-27 23:40:13 +020013909/* formatlong() emulates the format codes d, u, o, x and X, and
13910 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
13911 * Python's regular ints.
13912 * Return value: a new PyUnicodeObject*, or NULL if error.
13913 * The output string is of the form
13914 * "-"? ("0x" | "0X")? digit+
13915 * "0x"/"0X" are present only for x and X conversions, with F_ALT
13916 * set in flags. The case of hex digits will be correct,
13917 * There will be at least prec digits, zero-filled on the left if
13918 * necessary to get that many.
13919 * val object to be converted
13920 * flags bitmask of format flags; only F_ALT is looked at
13921 * prec minimum number of digits; 0-fill on left if needed
13922 * type a character in [duoxX]; u acts the same as d
13923 *
13924 * CAUTION: o, x and X conversions on regular ints can never
13925 * produce a '-' sign, but can for Python's unbounded ints.
13926 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080013927PyObject *
13928_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000013929{
Victor Stinnerd0880d52012-04-27 23:40:13 +020013930 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013931 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013932 Py_ssize_t i;
13933 int sign; /* 1 if '-', else 0 */
13934 int len; /* number of characters */
13935 Py_ssize_t llen;
13936 int numdigits; /* len == numnondigits + numdigits */
13937 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000013938
Victor Stinnerd0880d52012-04-27 23:40:13 +020013939 /* Avoid exceeding SSIZE_T_MAX */
13940 if (prec > INT_MAX-3) {
13941 PyErr_SetString(PyExc_OverflowError,
13942 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013943 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013944 }
13945
13946 assert(PyLong_Check(val));
13947
13948 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020013949 default:
13950 assert(!"'type' not in [diuoxX]");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013951 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020013952 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020013953 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070013954 /* int and int subclasses should print numerically when a numeric */
13955 /* format code is used (see issue18780) */
13956 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013957 break;
13958 case 'o':
13959 numnondigits = 2;
13960 result = PyNumber_ToBase(val, 8);
13961 break;
13962 case 'x':
13963 case 'X':
13964 numnondigits = 2;
13965 result = PyNumber_ToBase(val, 16);
13966 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020013967 }
13968 if (!result)
13969 return NULL;
13970
13971 assert(unicode_modifiable(result));
13972 assert(PyUnicode_IS_READY(result));
13973 assert(PyUnicode_IS_ASCII(result));
13974
13975 /* To modify the string in-place, there can only be one reference. */
13976 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013977 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013978 PyErr_BadInternalCall();
13979 return NULL;
13980 }
13981 buf = PyUnicode_DATA(result);
13982 llen = PyUnicode_GET_LENGTH(result);
13983 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020013984 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020013985 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080013986 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020013987 return NULL;
13988 }
13989 len = (int)llen;
13990 sign = buf[0] == '-';
13991 numnondigits += sign;
13992 numdigits = len - numnondigits;
13993 assert(numdigits > 0);
13994
13995 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080013996 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020013997 (type == 'o' || type == 'x' || type == 'X'))) {
13998 assert(buf[sign] == '0');
13999 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14000 buf[sign+1] == 'o');
14001 numnondigits -= 2;
14002 buf += 2;
14003 len -= 2;
14004 if (sign)
14005 buf[0] = '-';
14006 assert(len == numnondigits + numdigits);
14007 assert(numdigits > 0);
14008 }
14009
14010 /* Fill with leading zeroes to meet minimum width. */
14011 if (prec > numdigits) {
14012 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14013 numnondigits + prec);
14014 char *b1;
14015 if (!r1) {
14016 Py_DECREF(result);
14017 return NULL;
14018 }
14019 b1 = PyBytes_AS_STRING(r1);
14020 for (i = 0; i < numnondigits; ++i)
14021 *b1++ = *buf++;
14022 for (i = 0; i < prec - numdigits; i++)
14023 *b1++ = '0';
14024 for (i = 0; i < numdigits; i++)
14025 *b1++ = *buf++;
14026 *b1 = '\0';
14027 Py_DECREF(result);
14028 result = r1;
14029 buf = PyBytes_AS_STRING(result);
14030 len = numnondigits + prec;
14031 }
14032
14033 /* Fix up case for hex conversions. */
14034 if (type == 'X') {
14035 /* Need to convert all lower case letters to upper case.
14036 and need to convert 0x to 0X (and -0x to -0X). */
14037 for (i = 0; i < len; i++)
14038 if (buf[i] >= 'a' && buf[i] <= 'x')
14039 buf[i] -= 'a'-'A';
14040 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014041 if (!PyUnicode_Check(result)
14042 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014043 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014044 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014045 Py_DECREF(result);
14046 result = unicode;
14047 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014048 else if (len != PyUnicode_GET_LENGTH(result)) {
14049 if (PyUnicode_Resize(&result, len) < 0)
14050 Py_CLEAR(result);
14051 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014052 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014053}
14054
Ethan Furmandf3ed242014-01-05 06:50:30 -080014055/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014056 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014057 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014058 * -1 and raise an exception on error */
14059static int
Victor Stinnera47082312012-10-04 02:19:54 +020014060mainformatlong(PyObject *v,
14061 struct unicode_format_arg_t *arg,
14062 PyObject **p_output,
14063 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014064{
14065 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014066 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014067
14068 if (!PyNumber_Check(v))
14069 goto wrongtype;
14070
Ethan Furman9ab74802014-03-21 06:38:46 -070014071 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014072 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014073 if (type == 'o' || type == 'x' || type == 'X') {
14074 iobj = PyNumber_Index(v);
14075 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014076 if (PyErr_ExceptionMatches(PyExc_TypeError))
14077 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014078 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014079 }
14080 }
14081 else {
14082 iobj = PyNumber_Long(v);
14083 if (iobj == NULL ) {
14084 if (PyErr_ExceptionMatches(PyExc_TypeError))
14085 goto wrongtype;
14086 return -1;
14087 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014088 }
14089 assert(PyLong_Check(iobj));
14090 }
14091 else {
14092 iobj = v;
14093 Py_INCREF(iobj);
14094 }
14095
14096 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014097 && arg->width == -1 && arg->prec == -1
14098 && !(arg->flags & (F_SIGN | F_BLANK))
14099 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014100 {
14101 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014102 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014103 int base;
14104
Victor Stinnera47082312012-10-04 02:19:54 +020014105 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014106 {
14107 default:
14108 assert(0 && "'type' not in [diuoxX]");
14109 case 'd':
14110 case 'i':
14111 case 'u':
14112 base = 10;
14113 break;
14114 case 'o':
14115 base = 8;
14116 break;
14117 case 'x':
14118 case 'X':
14119 base = 16;
14120 break;
14121 }
14122
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014123 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14124 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014125 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014126 }
14127 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014128 return 1;
14129 }
14130
Ethan Furmanb95b5612015-01-23 20:05:18 -080014131 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014132 Py_DECREF(iobj);
14133 if (res == NULL)
14134 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014135 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014136 return 0;
14137
14138wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014139 switch(type)
14140 {
14141 case 'o':
14142 case 'x':
14143 case 'X':
14144 PyErr_Format(PyExc_TypeError,
14145 "%%%c format: an integer is required, "
14146 "not %.200s",
14147 type, Py_TYPE(v)->tp_name);
14148 break;
14149 default:
14150 PyErr_Format(PyExc_TypeError,
14151 "%%%c format: a number is required, "
14152 "not %.200s",
14153 type, Py_TYPE(v)->tp_name);
14154 break;
14155 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014156 return -1;
14157}
14158
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014159static Py_UCS4
14160formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014161{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014162 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014163 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014164 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014165 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014166 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014167 goto onError;
14168 }
14169 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014170 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014171 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014172 /* make sure number is a type of integer */
14173 if (!PyLong_Check(v)) {
14174 iobj = PyNumber_Index(v);
14175 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014176 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014177 }
14178 v = iobj;
14179 Py_DECREF(iobj);
14180 }
14181 /* Integer input truncated to a character */
Benjamin Peterson29060642009-01-31 22:14:21 +000014182 x = PyLong_AsLong(v);
14183 if (x == -1 && PyErr_Occurred())
14184 goto onError;
14185
Victor Stinner8faf8212011-12-08 22:14:11 +010014186 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014187 PyErr_SetString(PyExc_OverflowError,
14188 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014189 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014190 }
14191
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014192 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014193 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014194
Benjamin Peterson29060642009-01-31 22:14:21 +000014195 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014196 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014197 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014198 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014199}
14200
Victor Stinnera47082312012-10-04 02:19:54 +020014201/* Parse options of an argument: flags, width, precision.
14202 Handle also "%(name)" syntax.
14203
14204 Return 0 if the argument has been formatted into arg->str.
14205 Return 1 if the argument has been written into ctx->writer,
14206 Raise an exception and return -1 on error. */
14207static int
14208unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14209 struct unicode_format_arg_t *arg)
14210{
14211#define FORMAT_READ(ctx) \
14212 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14213
14214 PyObject *v;
14215
Victor Stinnera47082312012-10-04 02:19:54 +020014216 if (arg->ch == '(') {
14217 /* Get argument value from a dictionary. Example: "%(name)s". */
14218 Py_ssize_t keystart;
14219 Py_ssize_t keylen;
14220 PyObject *key;
14221 int pcount = 1;
14222
14223 if (ctx->dict == NULL) {
14224 PyErr_SetString(PyExc_TypeError,
14225 "format requires a mapping");
14226 return -1;
14227 }
14228 ++ctx->fmtpos;
14229 --ctx->fmtcnt;
14230 keystart = ctx->fmtpos;
14231 /* Skip over balanced parentheses */
14232 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14233 arg->ch = FORMAT_READ(ctx);
14234 if (arg->ch == ')')
14235 --pcount;
14236 else if (arg->ch == '(')
14237 ++pcount;
14238 ctx->fmtpos++;
14239 }
14240 keylen = ctx->fmtpos - keystart - 1;
14241 if (ctx->fmtcnt < 0 || pcount > 0) {
14242 PyErr_SetString(PyExc_ValueError,
14243 "incomplete format key");
14244 return -1;
14245 }
14246 key = PyUnicode_Substring(ctx->fmtstr,
14247 keystart, keystart + keylen);
14248 if (key == NULL)
14249 return -1;
14250 if (ctx->args_owned) {
14251 Py_DECREF(ctx->args);
14252 ctx->args_owned = 0;
14253 }
14254 ctx->args = PyObject_GetItem(ctx->dict, key);
14255 Py_DECREF(key);
14256 if (ctx->args == NULL)
14257 return -1;
14258 ctx->args_owned = 1;
14259 ctx->arglen = -1;
14260 ctx->argidx = -2;
14261 }
14262
14263 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014264 while (--ctx->fmtcnt >= 0) {
14265 arg->ch = FORMAT_READ(ctx);
14266 ctx->fmtpos++;
14267 switch (arg->ch) {
14268 case '-': arg->flags |= F_LJUST; continue;
14269 case '+': arg->flags |= F_SIGN; continue;
14270 case ' ': arg->flags |= F_BLANK; continue;
14271 case '#': arg->flags |= F_ALT; continue;
14272 case '0': arg->flags |= F_ZERO; continue;
14273 }
14274 break;
14275 }
14276
14277 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014278 if (arg->ch == '*') {
14279 v = unicode_format_getnextarg(ctx);
14280 if (v == NULL)
14281 return -1;
14282 if (!PyLong_Check(v)) {
14283 PyErr_SetString(PyExc_TypeError,
14284 "* wants int");
14285 return -1;
14286 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014287 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014288 if (arg->width == -1 && PyErr_Occurred())
14289 return -1;
14290 if (arg->width < 0) {
14291 arg->flags |= F_LJUST;
14292 arg->width = -arg->width;
14293 }
14294 if (--ctx->fmtcnt >= 0) {
14295 arg->ch = FORMAT_READ(ctx);
14296 ctx->fmtpos++;
14297 }
14298 }
14299 else if (arg->ch >= '0' && arg->ch <= '9') {
14300 arg->width = arg->ch - '0';
14301 while (--ctx->fmtcnt >= 0) {
14302 arg->ch = FORMAT_READ(ctx);
14303 ctx->fmtpos++;
14304 if (arg->ch < '0' || arg->ch > '9')
14305 break;
14306 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14307 mixing signed and unsigned comparison. Since arg->ch is between
14308 '0' and '9', casting to int is safe. */
14309 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14310 PyErr_SetString(PyExc_ValueError,
14311 "width too big");
14312 return -1;
14313 }
14314 arg->width = arg->width*10 + (arg->ch - '0');
14315 }
14316 }
14317
14318 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014319 if (arg->ch == '.') {
14320 arg->prec = 0;
14321 if (--ctx->fmtcnt >= 0) {
14322 arg->ch = FORMAT_READ(ctx);
14323 ctx->fmtpos++;
14324 }
14325 if (arg->ch == '*') {
14326 v = unicode_format_getnextarg(ctx);
14327 if (v == NULL)
14328 return -1;
14329 if (!PyLong_Check(v)) {
14330 PyErr_SetString(PyExc_TypeError,
14331 "* wants int");
14332 return -1;
14333 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014334 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014335 if (arg->prec == -1 && PyErr_Occurred())
14336 return -1;
14337 if (arg->prec < 0)
14338 arg->prec = 0;
14339 if (--ctx->fmtcnt >= 0) {
14340 arg->ch = FORMAT_READ(ctx);
14341 ctx->fmtpos++;
14342 }
14343 }
14344 else if (arg->ch >= '0' && arg->ch <= '9') {
14345 arg->prec = arg->ch - '0';
14346 while (--ctx->fmtcnt >= 0) {
14347 arg->ch = FORMAT_READ(ctx);
14348 ctx->fmtpos++;
14349 if (arg->ch < '0' || arg->ch > '9')
14350 break;
14351 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14352 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014353 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014354 return -1;
14355 }
14356 arg->prec = arg->prec*10 + (arg->ch - '0');
14357 }
14358 }
14359 }
14360
14361 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14362 if (ctx->fmtcnt >= 0) {
14363 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14364 if (--ctx->fmtcnt >= 0) {
14365 arg->ch = FORMAT_READ(ctx);
14366 ctx->fmtpos++;
14367 }
14368 }
14369 }
14370 if (ctx->fmtcnt < 0) {
14371 PyErr_SetString(PyExc_ValueError,
14372 "incomplete format");
14373 return -1;
14374 }
14375 return 0;
14376
14377#undef FORMAT_READ
14378}
14379
14380/* Format one argument. Supported conversion specifiers:
14381
14382 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014383 - "i", "d", "u": int or float
14384 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014385 - "e", "E", "f", "F", "g", "G": float
14386 - "c": int or str (1 character)
14387
Victor Stinner8dbd4212012-12-04 09:30:24 +010014388 When possible, the output is written directly into the Unicode writer
14389 (ctx->writer). A string is created when padding is required.
14390
Victor Stinnera47082312012-10-04 02:19:54 +020014391 Return 0 if the argument has been formatted into *p_str,
14392 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014393 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014394static int
14395unicode_format_arg_format(struct unicode_formatter_t *ctx,
14396 struct unicode_format_arg_t *arg,
14397 PyObject **p_str)
14398{
14399 PyObject *v;
14400 _PyUnicodeWriter *writer = &ctx->writer;
14401
14402 if (ctx->fmtcnt == 0)
14403 ctx->writer.overallocate = 0;
14404
14405 if (arg->ch == '%') {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014406 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014407 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014408 return 1;
14409 }
14410
14411 v = unicode_format_getnextarg(ctx);
14412 if (v == NULL)
14413 return -1;
14414
Victor Stinnera47082312012-10-04 02:19:54 +020014415
14416 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014417 case 's':
14418 case 'r':
14419 case 'a':
14420 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14421 /* Fast path */
14422 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14423 return -1;
14424 return 1;
14425 }
14426
14427 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14428 *p_str = v;
14429 Py_INCREF(*p_str);
14430 }
14431 else {
14432 if (arg->ch == 's')
14433 *p_str = PyObject_Str(v);
14434 else if (arg->ch == 'r')
14435 *p_str = PyObject_Repr(v);
14436 else
14437 *p_str = PyObject_ASCII(v);
14438 }
14439 break;
14440
14441 case 'i':
14442 case 'd':
14443 case 'u':
14444 case 'o':
14445 case 'x':
14446 case 'X':
14447 {
14448 int ret = mainformatlong(v, arg, p_str, writer);
14449 if (ret != 0)
14450 return ret;
14451 arg->sign = 1;
14452 break;
14453 }
14454
14455 case 'e':
14456 case 'E':
14457 case 'f':
14458 case 'F':
14459 case 'g':
14460 case 'G':
14461 if (arg->width == -1 && arg->prec == -1
14462 && !(arg->flags & (F_SIGN | F_BLANK)))
14463 {
14464 /* Fast path */
14465 if (formatfloat(v, arg, NULL, writer) == -1)
14466 return -1;
14467 return 1;
14468 }
14469
14470 arg->sign = 1;
14471 if (formatfloat(v, arg, p_str, NULL) == -1)
14472 return -1;
14473 break;
14474
14475 case 'c':
14476 {
14477 Py_UCS4 ch = formatchar(v);
14478 if (ch == (Py_UCS4) -1)
14479 return -1;
14480 if (arg->width == -1 && arg->prec == -1) {
14481 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014482 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014483 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014484 return 1;
14485 }
14486 *p_str = PyUnicode_FromOrdinal(ch);
14487 break;
14488 }
14489
14490 default:
14491 PyErr_Format(PyExc_ValueError,
14492 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014493 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014494 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14495 (int)arg->ch,
14496 ctx->fmtpos - 1);
14497 return -1;
14498 }
14499 if (*p_str == NULL)
14500 return -1;
14501 assert (PyUnicode_Check(*p_str));
14502 return 0;
14503}
14504
14505static int
14506unicode_format_arg_output(struct unicode_formatter_t *ctx,
14507 struct unicode_format_arg_t *arg,
14508 PyObject *str)
14509{
14510 Py_ssize_t len;
14511 enum PyUnicode_Kind kind;
14512 void *pbuf;
14513 Py_ssize_t pindex;
14514 Py_UCS4 signchar;
14515 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014516 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014517 Py_ssize_t sublen;
14518 _PyUnicodeWriter *writer = &ctx->writer;
14519 Py_UCS4 fill;
14520
14521 fill = ' ';
14522 if (arg->sign && arg->flags & F_ZERO)
14523 fill = '0';
14524
14525 if (PyUnicode_READY(str) == -1)
14526 return -1;
14527
14528 len = PyUnicode_GET_LENGTH(str);
14529 if ((arg->width == -1 || arg->width <= len)
14530 && (arg->prec == -1 || arg->prec >= len)
14531 && !(arg->flags & (F_SIGN | F_BLANK)))
14532 {
14533 /* Fast path */
14534 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14535 return -1;
14536 return 0;
14537 }
14538
14539 /* Truncate the string for "s", "r" and "a" formats
14540 if the precision is set */
14541 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14542 if (arg->prec >= 0 && len > arg->prec)
14543 len = arg->prec;
14544 }
14545
14546 /* Adjust sign and width */
14547 kind = PyUnicode_KIND(str);
14548 pbuf = PyUnicode_DATA(str);
14549 pindex = 0;
14550 signchar = '\0';
14551 if (arg->sign) {
14552 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14553 if (ch == '-' || ch == '+') {
14554 signchar = ch;
14555 len--;
14556 pindex++;
14557 }
14558 else if (arg->flags & F_SIGN)
14559 signchar = '+';
14560 else if (arg->flags & F_BLANK)
14561 signchar = ' ';
14562 else
14563 arg->sign = 0;
14564 }
14565 if (arg->width < len)
14566 arg->width = len;
14567
14568 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014569 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014570 if (!(arg->flags & F_LJUST)) {
14571 if (arg->sign) {
14572 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014573 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014574 }
14575 else {
14576 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014577 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014578 }
14579 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014580 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14581 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014582 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014583 }
14584
Victor Stinnera47082312012-10-04 02:19:54 +020014585 buflen = arg->width;
14586 if (arg->sign && len == arg->width)
14587 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014588 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014589 return -1;
14590
14591 /* Write the sign if needed */
14592 if (arg->sign) {
14593 if (fill != ' ') {
14594 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14595 writer->pos += 1;
14596 }
14597 if (arg->width > len)
14598 arg->width--;
14599 }
14600
14601 /* Write the numeric prefix for "x", "X" and "o" formats
14602 if the alternate form is used.
14603 For example, write "0x" for the "%#x" format. */
14604 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14605 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14606 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14607 if (fill != ' ') {
14608 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14609 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14610 writer->pos += 2;
14611 pindex += 2;
14612 }
14613 arg->width -= 2;
14614 if (arg->width < 0)
14615 arg->width = 0;
14616 len -= 2;
14617 }
14618
14619 /* Pad left with the fill character if needed */
14620 if (arg->width > len && !(arg->flags & F_LJUST)) {
14621 sublen = arg->width - len;
14622 FILL(writer->kind, writer->data, fill, writer->pos, sublen);
14623 writer->pos += sublen;
14624 arg->width = len;
14625 }
14626
14627 /* If padding with spaces: write sign if needed and/or numeric prefix if
14628 the alternate form is used */
14629 if (fill == ' ') {
14630 if (arg->sign) {
14631 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14632 writer->pos += 1;
14633 }
14634 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14635 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14636 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14637 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14638 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14639 writer->pos += 2;
14640 pindex += 2;
14641 }
14642 }
14643
14644 /* Write characters */
14645 if (len) {
14646 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14647 str, pindex, len);
14648 writer->pos += len;
14649 }
14650
14651 /* Pad right with the fill character if needed */
14652 if (arg->width > len) {
14653 sublen = arg->width - len;
14654 FILL(writer->kind, writer->data, ' ', writer->pos, sublen);
14655 writer->pos += sublen;
14656 }
14657 return 0;
14658}
14659
14660/* Helper of PyUnicode_Format(): format one arg.
14661 Return 0 on success, raise an exception and return -1 on error. */
14662static int
14663unicode_format_arg(struct unicode_formatter_t *ctx)
14664{
14665 struct unicode_format_arg_t arg;
14666 PyObject *str;
14667 int ret;
14668
Victor Stinner8dbd4212012-12-04 09:30:24 +010014669 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
14670 arg.flags = 0;
14671 arg.width = -1;
14672 arg.prec = -1;
14673 arg.sign = 0;
14674 str = NULL;
14675
Victor Stinnera47082312012-10-04 02:19:54 +020014676 ret = unicode_format_arg_parse(ctx, &arg);
14677 if (ret == -1)
14678 return -1;
14679
14680 ret = unicode_format_arg_format(ctx, &arg, &str);
14681 if (ret == -1)
14682 return -1;
14683
14684 if (ret != 1) {
14685 ret = unicode_format_arg_output(ctx, &arg, str);
14686 Py_DECREF(str);
14687 if (ret == -1)
14688 return -1;
14689 }
14690
14691 if (ctx->dict && (ctx->argidx < ctx->arglen) && arg.ch != '%') {
14692 PyErr_SetString(PyExc_TypeError,
14693 "not all arguments converted during string formatting");
14694 return -1;
14695 }
14696 return 0;
14697}
14698
Alexander Belopolsky40018472011-02-26 01:02:56 +000014699PyObject *
14700PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014701{
Victor Stinnera47082312012-10-04 02:19:54 +020014702 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014703
Guido van Rossumd57fd912000-03-10 22:53:23 +000014704 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014705 PyErr_BadInternalCall();
14706 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014707 }
Victor Stinnera47082312012-10-04 02:19:54 +020014708
14709 ctx.fmtstr = PyUnicode_FromObject(format);
14710 if (ctx.fmtstr == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000014711 return NULL;
Victor Stinnera47082312012-10-04 02:19:54 +020014712 if (PyUnicode_READY(ctx.fmtstr) == -1) {
14713 Py_DECREF(ctx.fmtstr);
14714 return NULL;
14715 }
14716 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14717 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14718 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14719 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014720
Victor Stinner8f674cc2013-04-17 23:02:17 +020014721 _PyUnicodeWriter_Init(&ctx.writer);
14722 ctx.writer.min_length = ctx.fmtcnt + 100;
14723 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014724
Guido van Rossumd57fd912000-03-10 22:53:23 +000014725 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014726 ctx.arglen = PyTuple_Size(args);
14727 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014728 }
14729 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014730 ctx.arglen = -1;
14731 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014732 }
Victor Stinnera47082312012-10-04 02:19:54 +020014733 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014734 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014735 ctx.dict = args;
14736 else
14737 ctx.dict = NULL;
14738 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014739
Victor Stinnera47082312012-10-04 02:19:54 +020014740 while (--ctx.fmtcnt >= 0) {
14741 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014742 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014743
14744 nonfmtpos = ctx.fmtpos++;
14745 while (ctx.fmtcnt >= 0 &&
14746 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14747 ctx.fmtpos++;
14748 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014749 }
Victor Stinnera47082312012-10-04 02:19:54 +020014750 if (ctx.fmtcnt < 0) {
14751 ctx.fmtpos--;
14752 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014753 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014754
Victor Stinnercfc4c132013-04-03 01:48:39 +020014755 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14756 nonfmtpos, ctx.fmtpos) < 0)
14757 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014758 }
14759 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014760 ctx.fmtpos++;
14761 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014762 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014763 }
14764 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014765
Victor Stinnera47082312012-10-04 02:19:54 +020014766 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014767 PyErr_SetString(PyExc_TypeError,
14768 "not all arguments converted during string formatting");
14769 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014770 }
14771
Victor Stinnera47082312012-10-04 02:19:54 +020014772 if (ctx.args_owned) {
14773 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014774 }
Victor Stinnera47082312012-10-04 02:19:54 +020014775 Py_DECREF(ctx.fmtstr);
14776 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014777
Benjamin Peterson29060642009-01-31 22:14:21 +000014778 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014779 Py_DECREF(ctx.fmtstr);
14780 _PyUnicodeWriter_Dealloc(&ctx.writer);
14781 if (ctx.args_owned) {
14782 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014783 }
14784 return NULL;
14785}
14786
Jeremy Hylton938ace62002-07-17 16:30:39 +000014787static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014788unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14789
Tim Peters6d6c1a32001-08-02 04:15:00 +000014790static PyObject *
14791unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14792{
Benjamin Peterson29060642009-01-31 22:14:21 +000014793 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014794 static char *kwlist[] = {"object", "encoding", "errors", 0};
14795 char *encoding = NULL;
14796 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014797
Benjamin Peterson14339b62009-01-31 16:36:08 +000014798 if (type != &PyUnicode_Type)
14799 return unicode_subtype_new(type, args, kwds);
14800 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014801 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014802 return NULL;
14803 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014804 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014805 if (encoding == NULL && errors == NULL)
14806 return PyObject_Str(x);
14807 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014808 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014809}
14810
Guido van Rossume023fe02001-08-30 03:12:59 +000014811static PyObject *
14812unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14813{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014814 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014815 Py_ssize_t length, char_size;
14816 int share_wstr, share_utf8;
14817 unsigned int kind;
14818 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014819
Benjamin Peterson14339b62009-01-31 16:36:08 +000014820 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014821
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014822 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014823 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014824 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014825 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014826 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014827 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014828 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014829 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014830
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014831 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014832 if (self == NULL) {
14833 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014834 return NULL;
14835 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014836 kind = PyUnicode_KIND(unicode);
14837 length = PyUnicode_GET_LENGTH(unicode);
14838
14839 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014840#ifdef Py_DEBUG
14841 _PyUnicode_HASH(self) = -1;
14842#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014843 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014844#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014845 _PyUnicode_STATE(self).interned = 0;
14846 _PyUnicode_STATE(self).kind = kind;
14847 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014848 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014849 _PyUnicode_STATE(self).ready = 1;
14850 _PyUnicode_WSTR(self) = NULL;
14851 _PyUnicode_UTF8_LENGTH(self) = 0;
14852 _PyUnicode_UTF8(self) = NULL;
14853 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014854 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014855
14856 share_utf8 = 0;
14857 share_wstr = 0;
14858 if (kind == PyUnicode_1BYTE_KIND) {
14859 char_size = 1;
14860 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
14861 share_utf8 = 1;
14862 }
14863 else if (kind == PyUnicode_2BYTE_KIND) {
14864 char_size = 2;
14865 if (sizeof(wchar_t) == 2)
14866 share_wstr = 1;
14867 }
14868 else {
14869 assert(kind == PyUnicode_4BYTE_KIND);
14870 char_size = 4;
14871 if (sizeof(wchar_t) == 4)
14872 share_wstr = 1;
14873 }
14874
14875 /* Ensure we won't overflow the length. */
14876 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
14877 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014878 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014879 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014880 data = PyObject_MALLOC((length + 1) * char_size);
14881 if (data == NULL) {
14882 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014883 goto onError;
14884 }
14885
Victor Stinnerc3c74152011-10-02 20:39:55 +020014886 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014887 if (share_utf8) {
14888 _PyUnicode_UTF8_LENGTH(self) = length;
14889 _PyUnicode_UTF8(self) = data;
14890 }
14891 if (share_wstr) {
14892 _PyUnicode_WSTR_LENGTH(self) = length;
14893 _PyUnicode_WSTR(self) = (wchar_t *)data;
14894 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014895
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014896 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020014897 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014898 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014899#ifdef Py_DEBUG
14900 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
14901#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020014902 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010014903 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014904
14905onError:
14906 Py_DECREF(unicode);
14907 Py_DECREF(self);
14908 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000014909}
14910
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000014911PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070014912"str(object='') -> str\n\
14913str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000014914\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100014915Create a new string object from the given object. If encoding or\n\
14916errors is specified, then the object must expose a data buffer\n\
14917that will be decoded using the given encoding and error handler.\n\
14918Otherwise, returns the result of object.__str__() (if defined)\n\
14919or repr(object).\n\
14920encoding defaults to sys.getdefaultencoding().\n\
14921errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000014922
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014923static PyObject *unicode_iter(PyObject *seq);
14924
Guido van Rossumd57fd912000-03-10 22:53:23 +000014925PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000014926 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014927 "str", /* tp_name */
14928 sizeof(PyUnicodeObject), /* tp_size */
14929 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014930 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014931 (destructor)unicode_dealloc, /* tp_dealloc */
14932 0, /* tp_print */
14933 0, /* tp_getattr */
14934 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014935 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014936 unicode_repr, /* tp_repr */
14937 &unicode_as_number, /* tp_as_number */
14938 &unicode_as_sequence, /* tp_as_sequence */
14939 &unicode_as_mapping, /* tp_as_mapping */
14940 (hashfunc) unicode_hash, /* tp_hash*/
14941 0, /* tp_call*/
14942 (reprfunc) unicode_str, /* tp_str */
14943 PyObject_GenericGetAttr, /* tp_getattro */
14944 0, /* tp_setattro */
14945 0, /* tp_as_buffer */
14946 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000014947 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014948 unicode_doc, /* tp_doc */
14949 0, /* tp_traverse */
14950 0, /* tp_clear */
14951 PyUnicode_RichCompare, /* tp_richcompare */
14952 0, /* tp_weaklistoffset */
14953 unicode_iter, /* tp_iter */
14954 0, /* tp_iternext */
14955 unicode_methods, /* tp_methods */
14956 0, /* tp_members */
14957 0, /* tp_getset */
14958 &PyBaseObject_Type, /* tp_base */
14959 0, /* tp_dict */
14960 0, /* tp_descr_get */
14961 0, /* tp_descr_set */
14962 0, /* tp_dictoffset */
14963 0, /* tp_init */
14964 0, /* tp_alloc */
14965 unicode_new, /* tp_new */
14966 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014967};
14968
14969/* Initialize the Unicode implementation */
14970
Victor Stinner3a50e702011-10-18 21:21:00 +020014971int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014972{
Thomas Wouters477c8d52006-05-27 19:21:47 +000014973 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014974 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000014975 0x000A, /* LINE FEED */
14976 0x000D, /* CARRIAGE RETURN */
14977 0x001C, /* FILE SEPARATOR */
14978 0x001D, /* GROUP SEPARATOR */
14979 0x001E, /* RECORD SEPARATOR */
14980 0x0085, /* NEXT LINE */
14981 0x2028, /* LINE SEPARATOR */
14982 0x2029, /* PARAGRAPH SEPARATOR */
14983 };
14984
Fred Drakee4315f52000-05-09 19:53:39 +000014985 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020014986 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014987 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014988 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020014989 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014990
Guido van Rossumcacfc072002-05-24 19:01:59 +000014991 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014992 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014993
14994 /* initialize the linebreak bloom filter */
14995 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014996 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014997 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014998
Christian Heimes26532f72013-07-20 14:57:16 +020014999 if (PyType_Ready(&EncodingMapType) < 0)
15000 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020015001
Benjamin Petersonc4311282012-10-30 23:21:10 -040015002 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
15003 Py_FatalError("Can't initialize field name iterator type");
15004
15005 if (PyType_Ready(&PyFormatterIter_Type) < 0)
15006 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040015007
Victor Stinner3a50e702011-10-18 21:21:00 +020015008 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015009}
15010
15011/* Finalize the Unicode implementation */
15012
Christian Heimesa156e092008-02-16 07:38:31 +000015013int
15014PyUnicode_ClearFreeList(void)
15015{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015016 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015017}
15018
Guido van Rossumd57fd912000-03-10 22:53:23 +000015019void
Thomas Wouters78890102000-07-22 19:25:51 +000015020_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015021{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015022 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015023
Serhiy Storchaka05997252013-01-26 12:14:02 +020015024 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015025
Serhiy Storchaka05997252013-01-26 12:14:02 +020015026 for (i = 0; i < 256; i++)
15027 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015028 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015029 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015030}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015031
Walter Dörwald16807132007-05-25 13:52:07 +000015032void
15033PyUnicode_InternInPlace(PyObject **p)
15034{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015035 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015036 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015037#ifdef Py_DEBUG
15038 assert(s != NULL);
15039 assert(_PyUnicode_CHECK(s));
15040#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015041 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015042 return;
15043#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015044 /* If it's a subclass, we don't really know what putting
15045 it in the interned dict might do. */
15046 if (!PyUnicode_CheckExact(s))
15047 return;
15048 if (PyUnicode_CHECK_INTERNED(s))
15049 return;
15050 if (interned == NULL) {
15051 interned = PyDict_New();
15052 if (interned == NULL) {
15053 PyErr_Clear(); /* Don't leave an exception */
15054 return;
15055 }
15056 }
15057 /* It might be that the GetItem call fails even
15058 though the key is present in the dictionary,
15059 namely when this happens during a stack overflow. */
15060 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010015061 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015062 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000015063
Victor Stinnerf0335102013-04-14 19:13:03 +020015064 if (t) {
15065 Py_INCREF(t);
15066 Py_DECREF(*p);
15067 *p = t;
15068 return;
15069 }
Walter Dörwald16807132007-05-25 13:52:07 +000015070
Benjamin Peterson14339b62009-01-31 16:36:08 +000015071 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010015072 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015073 PyErr_Clear();
15074 PyThreadState_GET()->recursion_critical = 0;
15075 return;
15076 }
15077 PyThreadState_GET()->recursion_critical = 0;
15078 /* The two references in interned are not counted by refcnt.
15079 The deallocator will take care of this */
15080 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015081 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015082}
15083
15084void
15085PyUnicode_InternImmortal(PyObject **p)
15086{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015087 PyUnicode_InternInPlace(p);
15088 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015089 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015090 Py_INCREF(*p);
15091 }
Walter Dörwald16807132007-05-25 13:52:07 +000015092}
15093
15094PyObject *
15095PyUnicode_InternFromString(const char *cp)
15096{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015097 PyObject *s = PyUnicode_FromString(cp);
15098 if (s == NULL)
15099 return NULL;
15100 PyUnicode_InternInPlace(&s);
15101 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015102}
15103
Alexander Belopolsky40018472011-02-26 01:02:56 +000015104void
15105_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015106{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015107 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015108 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015109 Py_ssize_t i, n;
15110 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015111
Benjamin Peterson14339b62009-01-31 16:36:08 +000015112 if (interned == NULL || !PyDict_Check(interned))
15113 return;
15114 keys = PyDict_Keys(interned);
15115 if (keys == NULL || !PyList_Check(keys)) {
15116 PyErr_Clear();
15117 return;
15118 }
Walter Dörwald16807132007-05-25 13:52:07 +000015119
Benjamin Peterson14339b62009-01-31 16:36:08 +000015120 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15121 detector, interned unicode strings are not forcibly deallocated;
15122 rather, we give them their stolen references back, and then clear
15123 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015124
Benjamin Peterson14339b62009-01-31 16:36:08 +000015125 n = PyList_GET_SIZE(keys);
15126 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015127 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015128 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015129 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015130 if (PyUnicode_READY(s) == -1) {
15131 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015132 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015133 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015134 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015135 case SSTATE_NOT_INTERNED:
15136 /* XXX Shouldn't happen */
15137 break;
15138 case SSTATE_INTERNED_IMMORTAL:
15139 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015140 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015141 break;
15142 case SSTATE_INTERNED_MORTAL:
15143 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015144 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015145 break;
15146 default:
15147 Py_FatalError("Inconsistent interned string state.");
15148 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015149 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015150 }
15151 fprintf(stderr, "total size of all interned strings: "
15152 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15153 "mortal/immortal\n", mortal_size, immortal_size);
15154 Py_DECREF(keys);
15155 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015156 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015157}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015158
15159
15160/********************* Unicode Iterator **************************/
15161
15162typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015163 PyObject_HEAD
15164 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015165 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015166} unicodeiterobject;
15167
15168static void
15169unicodeiter_dealloc(unicodeiterobject *it)
15170{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015171 _PyObject_GC_UNTRACK(it);
15172 Py_XDECREF(it->it_seq);
15173 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015174}
15175
15176static int
15177unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15178{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015179 Py_VISIT(it->it_seq);
15180 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015181}
15182
15183static PyObject *
15184unicodeiter_next(unicodeiterobject *it)
15185{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015186 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015187
Benjamin Peterson14339b62009-01-31 16:36:08 +000015188 assert(it != NULL);
15189 seq = it->it_seq;
15190 if (seq == NULL)
15191 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015192 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015193
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015194 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15195 int kind = PyUnicode_KIND(seq);
15196 void *data = PyUnicode_DATA(seq);
15197 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15198 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015199 if (item != NULL)
15200 ++it->it_index;
15201 return item;
15202 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015203
Benjamin Peterson14339b62009-01-31 16:36:08 +000015204 Py_DECREF(seq);
15205 it->it_seq = NULL;
15206 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015207}
15208
15209static PyObject *
15210unicodeiter_len(unicodeiterobject *it)
15211{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015212 Py_ssize_t len = 0;
15213 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015214 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015215 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015216}
15217
15218PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15219
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015220static PyObject *
15221unicodeiter_reduce(unicodeiterobject *it)
15222{
15223 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015224 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015225 it->it_seq, it->it_index);
15226 } else {
15227 PyObject *u = PyUnicode_FromUnicode(NULL, 0);
15228 if (u == NULL)
15229 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015230 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015231 }
15232}
15233
15234PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15235
15236static PyObject *
15237unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15238{
15239 Py_ssize_t index = PyLong_AsSsize_t(state);
15240 if (index == -1 && PyErr_Occurred())
15241 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015242 if (it->it_seq != NULL) {
15243 if (index < 0)
15244 index = 0;
15245 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15246 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15247 it->it_index = index;
15248 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015249 Py_RETURN_NONE;
15250}
15251
15252PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15253
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015254static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015255 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015256 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015257 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15258 reduce_doc},
15259 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15260 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015261 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015262};
15263
15264PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015265 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15266 "str_iterator", /* tp_name */
15267 sizeof(unicodeiterobject), /* tp_basicsize */
15268 0, /* tp_itemsize */
15269 /* methods */
15270 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15271 0, /* tp_print */
15272 0, /* tp_getattr */
15273 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015274 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015275 0, /* tp_repr */
15276 0, /* tp_as_number */
15277 0, /* tp_as_sequence */
15278 0, /* tp_as_mapping */
15279 0, /* tp_hash */
15280 0, /* tp_call */
15281 0, /* tp_str */
15282 PyObject_GenericGetAttr, /* tp_getattro */
15283 0, /* tp_setattro */
15284 0, /* tp_as_buffer */
15285 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15286 0, /* tp_doc */
15287 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15288 0, /* tp_clear */
15289 0, /* tp_richcompare */
15290 0, /* tp_weaklistoffset */
15291 PyObject_SelfIter, /* tp_iter */
15292 (iternextfunc)unicodeiter_next, /* tp_iternext */
15293 unicodeiter_methods, /* tp_methods */
15294 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015295};
15296
15297static PyObject *
15298unicode_iter(PyObject *seq)
15299{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015300 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015301
Benjamin Peterson14339b62009-01-31 16:36:08 +000015302 if (!PyUnicode_Check(seq)) {
15303 PyErr_BadInternalCall();
15304 return NULL;
15305 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015306 if (PyUnicode_READY(seq) == -1)
15307 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015308 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15309 if (it == NULL)
15310 return NULL;
15311 it->it_index = 0;
15312 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015313 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015314 _PyObject_GC_TRACK(it);
15315 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015316}
15317
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015318
15319size_t
15320Py_UNICODE_strlen(const Py_UNICODE *u)
15321{
15322 int res = 0;
15323 while(*u++)
15324 res++;
15325 return res;
15326}
15327
15328Py_UNICODE*
15329Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15330{
15331 Py_UNICODE *u = s1;
15332 while ((*u++ = *s2++));
15333 return s1;
15334}
15335
15336Py_UNICODE*
15337Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15338{
15339 Py_UNICODE *u = s1;
15340 while ((*u++ = *s2++))
15341 if (n-- == 0)
15342 break;
15343 return s1;
15344}
15345
15346Py_UNICODE*
15347Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15348{
15349 Py_UNICODE *u1 = s1;
15350 u1 += Py_UNICODE_strlen(u1);
15351 Py_UNICODE_strcpy(u1, s2);
15352 return s1;
15353}
15354
15355int
15356Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15357{
15358 while (*s1 && *s2 && *s1 == *s2)
15359 s1++, s2++;
15360 if (*s1 && *s2)
15361 return (*s1 < *s2) ? -1 : +1;
15362 if (*s1)
15363 return 1;
15364 if (*s2)
15365 return -1;
15366 return 0;
15367}
15368
15369int
15370Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15371{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015372 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015373 for (; n != 0; n--) {
15374 u1 = *s1;
15375 u2 = *s2;
15376 if (u1 != u2)
15377 return (u1 < u2) ? -1 : +1;
15378 if (u1 == '\0')
15379 return 0;
15380 s1++;
15381 s2++;
15382 }
15383 return 0;
15384}
15385
15386Py_UNICODE*
15387Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15388{
15389 const Py_UNICODE *p;
15390 for (p = s; *p; p++)
15391 if (*p == c)
15392 return (Py_UNICODE*)p;
15393 return NULL;
15394}
15395
15396Py_UNICODE*
15397Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15398{
15399 const Py_UNICODE *p;
15400 p = s + Py_UNICODE_strlen(s);
15401 while (p != s) {
15402 p--;
15403 if (*p == c)
15404 return (Py_UNICODE*)p;
15405 }
15406 return NULL;
15407}
Victor Stinner331ea922010-08-10 16:37:20 +000015408
Victor Stinner71133ff2010-09-01 23:43:53 +000015409Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015410PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015411{
Victor Stinner577db2c2011-10-11 22:12:48 +020015412 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015413 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015414
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015415 if (!PyUnicode_Check(unicode)) {
15416 PyErr_BadArgument();
15417 return NULL;
15418 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015419 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015420 if (u == NULL)
15421 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015422 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015423 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015424 PyErr_NoMemory();
15425 return NULL;
15426 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015427 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015428 size *= sizeof(Py_UNICODE);
15429 copy = PyMem_Malloc(size);
15430 if (copy == NULL) {
15431 PyErr_NoMemory();
15432 return NULL;
15433 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015434 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015435 return copy;
15436}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015437
Georg Brandl66c221e2010-10-14 07:04:07 +000015438/* A _string module, to export formatter_parser and formatter_field_name_split
15439 to the string.Formatter class implemented in Python. */
15440
15441static PyMethodDef _string_methods[] = {
15442 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15443 METH_O, PyDoc_STR("split the argument as a field name")},
15444 {"formatter_parser", (PyCFunction) formatter_parser,
15445 METH_O, PyDoc_STR("parse the argument as a format string")},
15446 {NULL, NULL}
15447};
15448
15449static struct PyModuleDef _string_module = {
15450 PyModuleDef_HEAD_INIT,
15451 "_string",
15452 PyDoc_STR("string helper module"),
15453 0,
15454 _string_methods,
15455 NULL,
15456 NULL,
15457 NULL,
15458 NULL
15459};
15460
15461PyMODINIT_FUNC
15462PyInit__string(void)
15463{
15464 return PyModule_Create(&_string_module);
15465}
15466
15467
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015468#ifdef __cplusplus
15469}
15470#endif