/*
Unicode implementation based on original code by Fredrik Lundh,
modified by Marc-Andre Lemburg <mal@lemburg.com> according to the
Unicode Integration Proposal (see file Misc/unicode.txt).
Copyright (c) Corporation for National Research Initiatives.
--------------------------------------------------------------------
The original string type implementation is:
Copyright (c) 1999 by Secret Labs AB
Copyright (c) 1999 by Fredrik Lundh
By obtaining, using, and/or copying this software and/or its
associated documentation, you agree that you have read, understood,
and will comply with the following terms and conditions:
Permission to use, copy, modify, and distribute this software and its
associated documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appears in all
copies, and that both that copyright notice and this permission notice
appear in supporting documentation, and that the name of Secret Labs
AB or the author not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.
SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "Python.h"
#include "unicodeobject.h"
#include "ucnhash.h"
#ifdef MS_WINDOWS
#include <windows.h>
#endif
/* Limit for the Unicode object free list */
#define MAX_UNICODE_FREELIST_SIZE 1024
/* Limit for the Unicode object free list stay alive optimization.
The implementation will keep allocated Unicode memory intact for
all objects on the free list having a size less than this
limit. This reduces malloc() overhead for small Unicode objects.
At worst this will result in MAX_UNICODE_FREELIST_SIZE *
(sizeof(PyUnicodeObject) + KEEPALIVE_SIZE_LIMIT +
malloc()-overhead) bytes of unused garbage.
Setting the limit to 0 effectively turns the feature off.
Note: This is an experimental feature ! If you get core dumps when
using Unicode objects, turn this feature off.
#define KEEPALIVE_SIZE_LIMIT 9
/* Endianness switches; defaults to little endian */
#ifdef WORDS_BIGENDIAN
# define BYTEORDER_IS_BIG_ENDIAN
#else
# define BYTEORDER_IS_LITTLE_ENDIAN
/* --- Globals ------------------------------------------------------------
The globals are initialized by the _PyUnicode_Init() API and should
not be used before calling that API.
/* Free list for Unicode objects */
static PyUnicodeObject *unicode_freelist;
static int unicode_freelist_size;
/* The empty Unicode object is shared to improve performance. */
static PyUnicodeObject *unicode_empty;
/* Single character Unicode strings in the Latin-1 range are being
shared as well. */
static PyUnicodeObject *unicode_latin1[256];
/* Default encoding to use and assume when NULL is passed as encoding
parameter; it is initialized by _PyUnicode_Init().
Always use the PyUnicode_SetDefaultEncoding() and
PyUnicode_GetDefaultEncoding() APIs to access this global.
static char unicode_default_encoding[100];
Py_UNICODE
PyUnicode_GetMax(void)
{
#ifdef Py_UNICODE_WIDE
return 0x10FFFF;
/* This is actually an illegal character, so it should
not be passed to unichr. */
return 0xFFFF;
}
/* --- Unicode Object ----------------------------------------------------- */
static
int unicode_resize(register PyUnicodeObject *unicode,
int length)
void *oldstr;
/* Shortcut if there's nothing much to do. */
if (unicode->length == length)
goto reset;
/* Resizing shared object (unicode_empty or single character
objects) in-place is not allowed. Use PyUnicode_Resize()
instead ! */
if (unicode == unicode_empty ||
(unicode->length == 1 &&
/* MvL said unicode->str[] may be signed. Python generally assumes
* an int contains at least 32 bits, and we don't use more than
* 32 bits even in a UCS4 build, so casting to unsigned int should
* be correct.
(unsigned int)unicode->str[0] < 256U &&
unicode_latin1[unicode->str[0]] == unicode)) {
PyErr_SetString(PyExc_SystemError,
"can't resize shared unicode objects");
return -1;
/* We allocate one more byte to make sure the string is
Ux0000 terminated -- XXX is this needed ? */
oldstr = unicode->str;
PyMem_RESIZE(unicode->str, Py_UNICODE, length + 1);
if (!unicode->str) {
unicode->str = oldstr;
PyErr_NoMemory();
unicode->str[length] = 0;
unicode->length = length;
reset:
/* Reset the object caches */
if (unicode->defenc) {
Py_DECREF(unicode->defenc);
unicode->defenc = NULL;
unicode->hash = -1;
return 0;
Ux0000 terminated -- XXX is this needed ?
XXX This allocator could further be enhanced by assuring that the
free list never reduces its size below 1.
PyUnicodeObject *_PyUnicode_New(int length)
register PyUnicodeObject *unicode;
/* Optimization fo empty strings */
if (length == 0 && unicode_empty != NULL) {
Py_INCREF(unicode_empty);
return unicode_empty;
/* Unicode freelist & memory allocation */
if (unicode_freelist) {
unicode = unicode_freelist;
unicode_freelist = *(PyUnicodeObject **)unicode;
unicode_freelist_size--;
if (unicode->str) {
/* Keep-Alive optimization: we only upsize the buffer,
never downsize it. */
if ((unicode->length < length) &&
unicode_resize(unicode, length) < 0) {
PyMem_DEL(unicode->str);
goto onError;
else {
unicode->str = PyMem_NEW(Py_UNICODE, length + 1);
PyObject_INIT(unicode, &PyUnicode_Type);
unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
if (unicode == NULL)
return NULL;
/* Initialize the first element to guard against cases where
* the caller fails before initializing str -- unicode_resize()
* reads str[0], and the Keep-Alive optimization can keep memory
* allocated for str alive across a call to unicode_dealloc(unicode).
* We don't want unicode_resize to read uninitialized memory in
* that case.
unicode->str[0] = 0;
return unicode;
onError:
_Py_ForgetReference((PyObject *)unicode);
PyObject_Del(unicode);
void unicode_dealloc(register PyUnicodeObject *unicode)
if (PyUnicode_CheckExact(unicode) &&
unicode_freelist_size < MAX_UNICODE_FREELIST_SIZE) {
/* Keep-Alive optimization */
if (unicode->length >= KEEPALIVE_SIZE_LIMIT) {
unicode->str = NULL;
unicode->length = 0;
/* Add to free list */
*(PyUnicodeObject **)unicode = unicode_freelist;
unicode_freelist = unicode;
unicode_freelist_size++;
Py_XDECREF(unicode->defenc);
unicode->ob_type->tp_free((PyObject *)unicode);
int PyUnicode_Resize(PyObject **unicode, int length)
register PyUnicodeObject *v;
/* Argument checks */
if (unicode == NULL) {
PyErr_BadInternalCall();
v = (PyUnicodeObject *)*unicode;
if (v == NULL || !PyUnicode_Check(v) || v->ob_refcnt != 1 || length < 0) {
/* Resizing unicode_empty and single character objects is not
possible since these are being shared. We simply return a fresh
copy with the same Unicode content. */
if (v->length != length &&
(v == unicode_empty || v->length == 1)) {
PyUnicodeObject *w = _PyUnicode_New(length);
if (w == NULL)
Py_UNICODE_COPY(w->str, v->str,
length < v->length ? length : v->length);
Py_DECREF(*unicode);
*unicode = (PyObject *)w;
/* Note that we don't have to modify *unicode for unshared Unicode
objects, since we can modify them in-place. */
return unicode_resize(v, length);
/* Internal API for use in unicodeobject.c only ! */
#define _PyUnicode_Resize(unicodevar, length) \
PyUnicode_Resize(((PyObject **)(unicodevar)), length)
PyObject *PyUnicode_FromUnicode(const Py_UNICODE *u,
int size)
PyUnicodeObject *unicode;
/* If the Unicode data is known at construction time, we can apply
some optimizations which share commonly used objects. */
if (u != NULL) {
/* Optimization for empty strings */
if (size == 0 && unicode_empty != NULL) {
return (PyObject *)unicode_empty;
/* Single character Unicode objects in the Latin-1 range are
shared when using this constructor */
if (size == 1 && *u < 256) {
unicode = unicode_latin1[*u];
if (!unicode) {
unicode = _PyUnicode_New(1);
if (!unicode)
unicode->str[0] = *u;
unicode_latin1[*u] = unicode;
Py_INCREF(unicode);
return (PyObject *)unicode;
unicode = _PyUnicode_New(size);
/* Copy the Unicode data into the new object */
if (u != NULL)
Py_UNICODE_COPY(unicode->str, u, size);
#ifdef HAVE_WCHAR_H
PyObject *PyUnicode_FromWideChar(register const wchar_t *w,
if (w == NULL) {
/* Copy the wchar_t data into the new object */
#ifdef HAVE_USABLE_WCHAR_T
memcpy(unicode->str, w, size * sizeof(wchar_t));
register Py_UNICODE *u;
register int i;
u = PyUnicode_AS_UNICODE(unicode);
for (i = size; i >= 0; i--)
*u++ = *w++;
int PyUnicode_AsWideChar(PyUnicodeObject *unicode,
register wchar_t *w,
if (size > PyUnicode_GET_SIZE(unicode))
size = PyUnicode_GET_SIZE(unicode);
memcpy(w, unicode->str, size * sizeof(wchar_t));
*w++ = *u++;
return size;
PyObject *PyUnicode_FromOrdinal(int ordinal)
Py_UNICODE s[1];
if (ordinal < 0 || ordinal > 0x10ffff) {
PyErr_SetString(PyExc_ValueError,
"unichr() arg not in range(0x110000) "
"(wide Python build)");
if (ordinal < 0 || ordinal > 0xffff) {
"unichr() arg not in range(0x10000) "
"(narrow Python build)");
s[0] = (Py_UNICODE)ordinal;
return PyUnicode_FromUnicode(s, 1);
PyObject *PyUnicode_FromObject(register PyObject *obj)
/* XXX Perhaps we should make this API an alias of
PyObject_Unicode() instead ?! */
if (PyUnicode_CheckExact(obj)) {
Py_INCREF(obj);
return obj;
if (PyUnicode_Check(obj)) {
/* For a Unicode subtype that's not a Unicode object,
return a true Unicode object with the same data. */
return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(obj),
PyUnicode_GET_SIZE(obj));
return PyUnicode_FromEncodedObject(obj, NULL, "strict");
PyObject *PyUnicode_FromEncodedObject(register PyObject *obj,
const char *encoding,
const char *errors)
const char *s = NULL;
int len;
PyObject *v;
if (obj == NULL) {
#if 0
/* For b/w compatibility we also accept Unicode objects provided
that no encodings is given and then redirect to
PyObject_Unicode() which then applies the additional logic for
Unicode subclasses.
NOTE: This API should really only be used for object which
represent *encoded* Unicode !
if (encoding) {
PyErr_SetString(PyExc_TypeError,
"decoding Unicode is not supported");
return PyObject_Unicode(obj);
/* Coerce object */
if (PyString_Check(obj)) {
s = PyString_AS_STRING(obj);
len = PyString_GET_SIZE(obj);
else if (PyObject_AsCharBuffer(obj, &s, &len)) {
/* Overwrite the error message with something more useful in
case of a TypeError. */
if (PyErr_ExceptionMatches(PyExc_TypeError))
PyErr_Format(PyExc_TypeError,
"coercing to Unicode: need string or buffer, "
"%.80s found",
obj->ob_type->tp_name);
/* Convert to Unicode */
if (len == 0) {
v = (PyObject *)unicode_empty;
else
v = PyUnicode_Decode(s, len, encoding, errors);
return v;
PyObject *PyUnicode_Decode(const char *s,
int size,
PyObject *buffer = NULL, *unicode;
if (encoding == NULL)
encoding = PyUnicode_GetDefaultEncoding();
/* Shortcuts for common default encodings */
if (strcmp(encoding, "utf-8") == 0)
return PyUnicode_DecodeUTF8(s, size, errors);
else if (strcmp(encoding, "latin-1") == 0)
return PyUnicode_DecodeLatin1(s, size, errors);
#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
else if (strcmp(encoding, "mbcs") == 0)
return PyUnicode_DecodeMBCS(s, size, errors);
else if (strcmp(encoding, "ascii") == 0)
return PyUnicode_DecodeASCII(s, size, errors);
/* Decode via the codec registry */
buffer = PyBuffer_FromMemory((void *)s, size);
if (buffer == NULL)
unicode = PyCodec_Decode(buffer, encoding, errors);
if (!PyUnicode_Check(unicode)) {
"decoder did not return an unicode object (type=%.400s)",
unicode->ob_type->tp_name);
Py_DECREF(unicode);
Py_DECREF(buffer);
Py_XDECREF(buffer);
PyObject *PyUnicode_AsDecodedObject(PyObject *unicode,
PyErr_BadArgument();
v = PyCodec_Decode(unicode, encoding, errors);
if (v == NULL)
PyObject *PyUnicode_Encode(const Py_UNICODE *s,
PyObject *v, *unicode;
unicode = PyUnicode_FromUnicode(s, size);
v = PyUnicode_AsEncodedString(unicode, encoding, errors);
PyObject *PyUnicode_AsEncodedObject(PyObject *unicode,
/* Encode via the codec registry */
v = PyCodec_Encode(unicode, encoding, errors);
PyObject *PyUnicode_AsEncodedString(PyObject *unicode,
if (errors == NULL) {
return PyUnicode_AsUTF8String(unicode);
return PyUnicode_AsLatin1String(unicode);
return PyUnicode_AsMBCSString(unicode);
return PyUnicode_AsASCIIString(unicode);
if (!PyString_Check(v)) {
"encoder did not return a string object (type=%.400s)",
v->ob_type->tp_name);
Py_DECREF(v);
PyObject *_PyUnicode_AsDefaultEncodedString(PyObject *unicode,
PyObject *v = ((PyUnicodeObject *)unicode)->defenc;
if (v)
v = PyUnicode_AsEncodedString(unicode, NULL, errors);
if (v && errors == NULL)
((PyUnicodeObject *)unicode)->defenc = v;
Py_UNICODE *PyUnicode_AsUnicode(PyObject *unicode)
return PyUnicode_AS_UNICODE(unicode);
int PyUnicode_GetSize(PyObject *unicode)
return PyUnicode_GET_SIZE(unicode);
const char *PyUnicode_GetDefaultEncoding(void)
return unicode_default_encoding;
int PyUnicode_SetDefaultEncoding(const char *encoding)
/* Make sure the encoding is valid. As side effect, this also
loads the encoding into the codec registry cache. */
v = _PyCodec_Lookup(encoding);
strncpy(unicode_default_encoding,
encoding,
sizeof(unicode_default_encoding));
/* error handling callback helper:
build arguments, call the callback and check the arguments,
if no exception occured, copy the replacement to the output
and adjust various state variables.
return 0 on success, -1 on error
int unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
const char *encoding, const char *reason,
const char *input, int insize, int *startinpos, int *endinpos, PyObject **exceptionObject, const char **inptr,
PyObject **output, int *outpos, Py_UNICODE **outptr)
static char *argparse = "O!i;decoding error handler must return (unicode, int) tuple";
PyObject *restuple = NULL;
PyObject *repunicode = NULL;
int outsize = PyUnicode_GET_SIZE(*output);
int requiredsize;
int newpos;
Py_UNICODE *repptr;
int repsize;
int res = -1;
if (*errorHandler == NULL) {
*errorHandler = PyCodec_LookupError(errors);
if (*errorHandler == NULL)
if (*exceptionObject == NULL) {
*exceptionObject = PyUnicodeDecodeError_Create(
encoding, input, insize, *startinpos, *endinpos, reason);
if (*exceptionObject == NULL)
if (PyUnicodeDecodeError_SetStart(*exceptionObject, *startinpos))
if (PyUnicodeDecodeError_SetEnd(*exceptionObject, *endinpos))
if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
if (restuple == NULL)
if (!PyTuple_Check(restuple)) {
PyErr_Format(PyExc_TypeError, &argparse[4]);
if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
if (newpos<0)
newpos = insize+newpos;
if (newpos<0 || newpos>insize) {
PyErr_Format(PyExc_IndexError, "position %d from error handler out of bounds", newpos);
/* need more space? (at least enough for what we
have+the replacement+the rest of the string (starting
at the new input position), so we won't have to check space
when there are no errors in the rest of the string) */
repptr = PyUnicode_AS_UNICODE(repunicode);
repsize = PyUnicode_GET_SIZE(repunicode);
requiredsize = *outpos + repsize + insize-newpos;
if (requiredsize > outsize) {
if (requiredsize<2*outsize)
requiredsize = 2*outsize;
if (PyUnicode_Resize(output, requiredsize) < 0)
*outptr = PyUnicode_AS_UNICODE(*output) + *outpos;
*endinpos = newpos;
*inptr = input + newpos;
Py_UNICODE_COPY(*outptr, repptr, repsize);
*outptr += repsize;
*outpos += repsize;
/* we made it! */
res = 0;
Py_XDECREF(restuple);
return res;
/* --- UTF-7 Codec -------------------------------------------------------- */
/* see RFC2152 for details */
char utf7_special[128] = {
/* indicate whether a UTF-7 character is special i.e. cannot be directly
encoded:
0 - not special
1 - special
2 - whitespace (optional)
3 - RFC2152 Set O (optional) */
1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 2, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2, 3, 3, 3, 3, 3, 3, 0, 0, 0, 3, 1, 0, 0, 0, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 0,
3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 1, 3, 3, 3,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 1, 1,
};
#define SPECIAL(c, encodeO, encodeWS) \
(((c)>127 || utf7_special[(c)] == 1) || \
(encodeWS && (utf7_special[(c)] == 2)) || \
(encodeO && (utf7_special[(c)] == 3)))
#define B64(n) ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
#define B64CHAR(c) (isalnum(c) || (c) == '+' || (c) == '/')
#define UB64(c) ((c) == '+' ? 62 : (c) == '/' ? 63 : (c) >= 'a' ? \
(c) - 71 : (c) >= 'A' ? (c) - 65 : (c) + 4)
#define ENCODE(out, ch, bits) \
while (bits >= 6) { \
*out++ = B64(ch >> (bits-6)); \
bits -= 6; \
#define DECODE(out, ch, bits, surrogate) \
while (bits >= 16) { \
Py_UNICODE outCh = (Py_UNICODE) ((ch >> (bits-16)) & 0xffff); \
bits -= 16; \
if (surrogate) { \
/* We have already generated an error for the high surrogate
so let's not bother seeing if the low surrogate is correct or not */\
surrogate = 0; \
} else if (0xDC00 <= outCh && outCh <= 0xDFFF) { \
/* This is a surrogate pair. Unfortunately we can't represent \
it in a 16-bit character */ \
surrogate = 1; \
errmsg = "code pairs are not supported"; \
goto utf7Error; \
} else { \
*out++ = outCh; \
} \
PyObject *PyUnicode_DecodeUTF7(const char *s,
const char *starts = s;
int startinpos;
int endinpos;
int outpos;
const char *e;
Py_UNICODE *p;
const char *errmsg = "";
int inShift = 0;
unsigned int bitsleft = 0;
unsigned long charsleft = 0;
int surrogate = 0;
PyObject *errorHandler = NULL;
PyObject *exc = NULL;
if (size == 0)
p = unicode->str;
e = s + size;
while (s < e) {
Py_UNICODE ch;
restart:
ch = *s;
if (inShift) {
if ((ch == '-') || !B64CHAR(ch)) {
inShift = 0;
s++;
/* p, charsleft, bitsleft, surrogate = */ DECODE(p, charsleft, bitsleft, surrogate);
if (bitsleft >= 6) {
/* The shift sequence has a partial character in it. If
bitsleft < 6 then we could just classify it as padding
but that is not the case here */
errmsg = "partial character in shift sequence";
goto utf7Error;
/* According to RFC2152 the remaining bits should be zero. We
choose to signal an error/insert a replacement character
here so indicate the potential of a misencoded character. */
/* On x86, a << b == a << (b%32) so make sure that bitsleft != 0 */
if (bitsleft && charsleft << (sizeof(charsleft) * 8 - bitsleft)) {
errmsg = "non-zero padding bits in shift sequence";
if (ch == '-') {
if ((s < e) && (*(s) == '-')) {
*p++ = '-';
inShift = 1;
} else if (SPECIAL(ch,0,0)) {
errmsg = "unexpected special character";
} else {
*p++ = ch;
charsleft = (charsleft << 6) | UB64(ch);
bitsleft += 6;
else if ( ch == '+' ) {
startinpos = s-starts;
if (s < e && *s == '-') {
*p++ = '+';
} else
bitsleft = 0;
else if (SPECIAL(ch,0,0)) {
continue;
utf7Error:
outpos = p-PyUnicode_AS_UNICODE(unicode);
endinpos = s-starts;
if (unicode_decode_call_errorhandler(
errors, &errorHandler,
"utf7", errmsg,
starts, size, &startinpos, &endinpos, &exc, &s,
(PyObject **)&unicode, &outpos, &p))
endinpos = size;
"utf7", "unterminated shift sequence",
if (s < e)
goto restart;
if (_PyUnicode_Resize(&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Py_XDECREF(errorHandler);
Py_XDECREF(exc);
PyObject *PyUnicode_EncodeUTF7(const Py_UNICODE *s,
int encodeSetO,
int encodeWhiteSpace,
/* It might be possible to tighten this worst case */
unsigned int cbAllocated = 5 * size;
int i = 0;
char * out;
char * start;
return PyString_FromStringAndSize(NULL, 0);
v = PyString_FromStringAndSize(NULL, cbAllocated);
start = out = PyString_AS_STRING(v);
for (;i < size; ++i) {
Py_UNICODE ch = s[i];
if (!inShift) {
if (ch == '+') {
*out++ = '+';
*out++ = '-';
} else if (SPECIAL(ch, encodeSetO, encodeWhiteSpace)) {
charsleft = ch;
bitsleft = 16;
/* out, charsleft, bitsleft = */ ENCODE(out, charsleft, bitsleft);
inShift = bitsleft > 0;
*out++ = (char) ch;
if (!SPECIAL(ch, encodeSetO, encodeWhiteSpace)) {
*out++ = B64(charsleft << (6-bitsleft));
charsleft = 0;
/* Characters not in the BASE64 set implicitly unshift the sequence
so no '-' is required, except if the character is itself a '-' */
if (B64CHAR(ch) || ch == '-') {
bitsleft += 16;
charsleft = (charsleft << 16) | ch;
/* If the next character is special then we dont' need to terminate
the shift sequence. If the next character is not a BASE64 character
or '-' then the shift sequence will be terminated implicitly and we
don't have to insert a '-'. */
if (bitsleft == 0) {
if (i + 1 < size) {
Py_UNICODE ch2 = s[i+1];
if (SPECIAL(ch2, encodeSetO, encodeWhiteSpace)) {
} else if (B64CHAR(ch2) || ch2 == '-') {
if (bitsleft) {
*out++= B64(charsleft << (6-bitsleft) );
_PyString_Resize(&v, out - start);
#undef SPECIAL
#undef B64
#undef B64CHAR
#undef UB64
#undef ENCODE
#undef DECODE
/* --- UTF-8 Codec -------------------------------------------------------- */
char utf8_code_length[256] = {
/* Map UTF-8 encoded prefix byte to sequence length. zero means
illegal prefix. see RFC 2279 for details */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 0, 0
PyObject *PyUnicode_DecodeUTF8(const char *s,
int n;
/* Note: size will always be longer than the resulting Unicode
character count */
/* Unpack UTF-8 encoded data */
Py_UCS4 ch = (unsigned char)*s;
if (ch < 0x80) {
*p++ = (Py_UNICODE)ch;
n = utf8_code_length[ch];
if (s + n > e) {
errmsg = "unexpected end of data";
goto utf8Error;
switch (n) {
case 0:
errmsg = "unexpected code byte";
endinpos = startinpos+1;
case 1:
errmsg = "internal error";
case 2:
if ((s[1] & 0xc0) != 0x80) {
errmsg = "invalid data";
endinpos = startinpos+2;
ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
errmsg = "illegal encoding";
break;
case 3:
if ((s[1] & 0xc0) != 0x80 ||
(s[2] & 0xc0) != 0x80) {
endinpos = startinpos+3;
ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
if (ch < 0x0800) {
/* Note: UTF-8 encodings of surrogates are considered
legal UTF-8 sequences;
XXX For wide builds (UCS-4) we should probably try
to recombine the surrogates into a single code
unit.
case 4:
(s[2] & 0xc0) != 0x80 ||
(s[3] & 0xc0) != 0x80) {
endinpos = startinpos+4;
ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
/* validate and convert to UTF-16 */
if ((ch < 0x10000) /* minimum value allowed for 4
byte encoding */
|| (ch > 0x10ffff)) /* maximum value allowed for
UTF-16 */
/* compute and append the two surrogates: */
/* translate from 10000..10FFFF to 0..FFFF */
ch -= 0x10000;
/* high surrogate = top 10 bits added to D800 */
*p++ = (Py_UNICODE)(0xD800 + (ch >> 10));
/* low surrogate = bottom 10 bits added to DC00 */
*p++ = (Py_UNICODE)(0xDC00 + (ch & 0x03FF));
default:
/* Other sizes are only needed for UCS-4 */
errmsg = "unsupported Unicode code range";
endinpos = startinpos+n;
s += n;
utf8Error:
"utf8", errmsg,
/* Adjust length */
if (_PyUnicode_Resize(&unicode, p - unicode->str) < 0)
/* Allocation strategy: if the string is short, convert into a stack buffer
and allocate exactly as much space needed at the end. Else allocate the
maximum possible needed (4 result bytes per Unicode character), and return
the excess memory at the end.
PyObject *
PyUnicode_EncodeUTF8(const Py_UNICODE *s,
#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
int i; /* index into s of next input byte */
PyObject *v; /* result string object */
char *p; /* next free byte in output buffer */
int nallocated; /* number of result bytes allocated */
int nneeded; /* number of result bytes needed */
char stackbuf[MAX_SHORT_UNICHARS * 4];
assert(s != NULL);
assert(size >= 0);
if (size <= MAX_SHORT_UNICHARS) {
/* Write into the stack buffer; nallocated can't overflow.
* At the end, we'll allocate exactly as much heap space as it
* turns out we need.
nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
v = NULL; /* will allocate after we're done */
p = stackbuf;
/* Overallocate on the heap, and give the excess back at the end. */
nallocated = size * 4;
if (nallocated / 4 != size) /* overflow! */
return PyErr_NoMemory();
v = PyString_FromStringAndSize(NULL, nallocated);
p = PyString_AS_STRING(v);
for (i = 0; i < size;) {
Py_UCS4 ch = s[i++];
if (ch < 0x80)
/* Encode ASCII */
*p++ = (char) ch;
else if (ch < 0x0800) {
/* Encode Latin-1 */
*p++ = (char)(0xc0 | (ch >> 6));
*p++ = (char)(0x80 | (ch & 0x3f));
/* Encode UCS2 Unicode ordinals */
if (ch < 0x10000) {
/* Special case: check for high surrogate */
if (0xD800 <= ch && ch <= 0xDBFF && i != size) {
Py_UCS4 ch2 = s[i];
/* Check for low surrogate and combine the two to
form a UCS4 value */
if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
ch = ((ch - 0xD800) << 10 | (ch2 - 0xDC00)) + 0x10000;
i++;
goto encodeUCS4;
/* Fall through: handles isolated high surrogates */
*p++ = (char)(0xe0 | (ch >> 12));
*p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
encodeUCS4:
/* Encode UCS4 Unicode ordinals */
*p++ = (char)(0xf0 | (ch >> 18));
*p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
if (v == NULL) {
/* This was stack allocated. */
nneeded = Py_SAFE_DOWNCAST(p - stackbuf, long, int);
assert(nneeded <= nallocated);
v = PyString_FromStringAndSize(stackbuf, nneeded);
/* Cut back to size actually needed. */
nneeded = Py_SAFE_DOWNCAST(p - PyString_AS_STRING(v), long, int);
_PyString_Resize(&v, nneeded);
#undef MAX_SHORT_UNICHARS
PyObject *PyUnicode_AsUTF8String(PyObject *unicode)
return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
PyUnicode_GET_SIZE(unicode),
NULL);
/* --- UTF-16 Codec ------------------------------------------------------- */
PyUnicode_DecodeUTF16(const char *s,
const char *errors,
int *byteorder)
const unsigned char *q, *e;
int bo = 0; /* assume native ordering by default */
/* Offsets from q for retrieving byte pairs in the right order. */
#ifdef BYTEORDER_IS_LITTLE_ENDIAN
int ihi = 1, ilo = 0;
int ihi = 0, ilo = 1;
/* Unpack UTF-16 encoded data */
q = (unsigned char *)s;
e = q + size;
if (byteorder)
bo = *byteorder;
/* Check for BOM marks (U+FEFF) in the input and adjust current
byte order setting accordingly. In native mode, the leading BOM
mark is skipped, in all other modes, it is copied to the output
stream as-is (giving a ZWNBSP character). */
if (bo == 0) {
const Py_UNICODE bom = (q[ihi] << 8) | q[ilo];
if (bom == 0xFEFF) {
q += 2;
bo = -1;
else if (bom == 0xFFFE) {
bo = 1;
if (bo == -1) {
/* force LE */
ihi = 1;
ilo = 0;
else if (bo == 1) {
/* force BE */
ihi = 0;
ilo = 1;
while (q < e) {
/* remaing bytes at the end? (size should be even) */
if (e-q<2) {
errmsg = "truncated data";
startinpos = ((const char *)q)-starts;
endinpos = ((const char *)e)-starts;
goto utf16Error;
/* The remaining input chars are ignored if the callback
chooses to skip the input */
ch = (q[ihi] << 8) | q[ilo];
if (ch < 0xD800 || ch > 0xDFFF) {
/* UTF-16 code pair: */
if (q >= e) {
startinpos = (((const char *)q)-2)-starts;
if (0xD800 <= ch && ch <= 0xDBFF) {
Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo];
#ifndef Py_UNICODE_WIDE
*p++ = ch2;
*p++ = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
errmsg = "illegal UTF-16 surrogate";
startinpos = (((const char *)q)-4)-starts;
/* Fall through to report the error */
utf16Error:
"utf16", errmsg,
starts, size, &startinpos, &endinpos, &exc, (const char **)&q,
*byteorder = bo;
PyUnicode_EncodeUTF16(const Py_UNICODE *s,
int byteorder)
unsigned char *p;
int i, pairs;
const int pairs = 0;
/* Offsets from p for storing byte pairs in the right order. */
#define STORECHAR(CH) \
do { \
p[ihi] = ((CH) >> 8) & 0xff; \
p[ilo] = (CH) & 0xff; \
p += 2; \
} while(0)
for (i = pairs = 0; i < size; i++)
if (s[i] >= 0x10000)
pairs++;
v = PyString_FromStringAndSize(NULL,
2 * (size + pairs + (byteorder == 0)));
p = (unsigned char *)PyString_AS_STRING(v);
if (byteorder == 0)
STORECHAR(0xFEFF);
if (byteorder == -1) {
else if (byteorder == 1) {
while (size-- > 0) {
Py_UNICODE ch = *s++;
Py_UNICODE ch2 = 0;
if (ch >= 0x10000) {
ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
ch = 0xD800 | ((ch-0x10000) >> 10);
STORECHAR(ch);
if (ch2)
STORECHAR(ch2);
#undef STORECHAR
PyObject *PyUnicode_AsUTF16String(PyObject *unicode)
return PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(unicode),
NULL,
0);
/* --- Unicode Escape Codec ----------------------------------------------- */
static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
PyObject *PyUnicode_DecodeUnicodeEscape(const char *s,
int i;
PyUnicodeObject *v;
const char *end;
char* message;
Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
/* Escaped strings will always be longer than the resulting
Unicode string, so we start with size here and then reduce the
length after conversion to the true value.
(but if the error callback returns a long replacement string
we'll have to allocate more space) */
v = _PyUnicode_New(size);
return (PyObject *)v;
p = PyUnicode_AS_UNICODE(v);
end = s + size;
while (s < end) {
unsigned char c;
Py_UNICODE x;
int digits;
/* Non-escape characters are interpreted as Unicode ordinals */
if (*s != '\\') {
*p++ = (unsigned char) *s++;
/* \ - Escapes */
switch (*s++) {
/* \x escapes */
case '\n': break;
case '\\': *p++ = '\\'; break;
case '\'': *p++ = '\''; break;
case '\"': *p++ = '\"'; break;
case 'b': *p++ = '\b'; break;
case 'f': *p++ = '\014'; break; /* FF */
case 't': *p++ = '\t'; break;
case 'n': *p++ = '\n'; break;
case 'r': *p++ = '\r'; break;
case 'v': *p++ = '\013'; break; /* VT */
case 'a': *p++ = '\007'; break; /* BEL, not classic C */
/* \OOO (octal) escapes */
case '0': case '1': case '2': case '3':
case '4': case '5': case '6': case '7':
x = s[-1] - '0';
if ('0' <= *s && *s <= '7') {
x = (x<<3) + *s++ - '0';
if ('0' <= *s && *s <= '7')
*p++ = x;
/* hex escapes */
/* \xXX */
case 'x':
digits = 2;
message = "truncated \\xXX escape";
goto hexescape;
/* \uXXXX */
case 'u':
digits = 4;
message = "truncated \\uXXXX escape";
/* \UXXXXXXXX */
case 'U':
digits = 8;
message = "truncated \\UXXXXXXXX escape";
hexescape:
chr = 0;
outpos = p-PyUnicode_AS_UNICODE(v);
if (s+digits>end) {
"unicodeescape", "end of string in escape sequence",
(PyObject **)&v, &outpos, &p))
goto nextByte;
for (i = 0; i < digits; ++i) {
c = (unsigned char) s[i];
if (!isxdigit(c)) {
endinpos = (s+i+1)-starts;
"unicodeescape", message,
chr = (chr<<4) & ~0xF;
if (c >= '0' && c <= '9')
chr += c - '0';
else if (c >= 'a' && c <= 'f')
chr += 10 + c - 'a';
chr += 10 + c - 'A';
s += i;
if (chr == 0xffffffff && PyErr_Occurred())
/* _decoding_error will have already written into the
target buffer. */
store:
/* when we get here, chr is a 32-bit unicode character */
if (chr <= 0xffff)
/* UCS-2 character */
*p++ = (Py_UNICODE) chr;
else if (chr <= 0x10ffff) {
/* UCS-4 character. Either store directly, or as
surrogate pair. */
*p++ = chr;
chr -= 0x10000L;
*p++ = 0xD800 + (Py_UNICODE) (chr >> 10);
*p++ = 0xDC00 + (Py_UNICODE) (chr & 0x03FF);
"unicodeescape", "illegal Unicode character",
/* \N{name} */
case 'N':
message = "malformed \\N character escape";
if (ucnhash_CAPI == NULL) {
/* load the unicode data module */
PyObject *m, *v;
m = PyImport_ImportModule("unicodedata");
if (m == NULL)
goto ucnhashError;
v = PyObject_GetAttrString(m, "ucnhash_CAPI");
Py_DECREF(m);
ucnhash_CAPI = PyCObject_AsVoidPtr(v);
if (ucnhash_CAPI == NULL)
if (*s == '{') {
const char *start = s+1;
/* look for the closing brace */
while (*s != '}' && s < end)
if (s > start && s < end && *s == '}') {
/* found a name. look it up in the unicode database */
message = "unknown Unicode character name";
if (ucnhash_CAPI->getcode(start, s-start-1, &chr))
goto store;
if (s > end) {
message = "\\ at end of string";
s--;
*p++ = '\\';
*p++ = (unsigned char)s[-1];
nextByte:
;
if (_PyUnicode_Resize(&v, (int)(p - PyUnicode_AS_UNICODE(v))) < 0)
ucnhashError:
PyErr_SetString(
PyExc_UnicodeError,
"\\N escapes not supported (can't load unicodedata module)"
);
Py_XDECREF(v);
/* Return a Unicode-Escape string version of the Unicode object.
If quotes is true, the string is enclosed in u"" or u'' quotes as
appropriate.
static const Py_UNICODE *findchar(const Py_UNICODE *s,
Py_UNICODE ch);
PyObject *unicodeescape_string(const Py_UNICODE *s,
int quotes)
PyObject *repr;
char *p;
static const char *hexdigit = "0123456789abcdef";
repr = PyString_FromStringAndSize(NULL, 2 + 6*size + 1);
if (repr == NULL)
p = PyString_AS_STRING(repr);
if (quotes) {
*p++ = 'u';
*p++ = (findchar(s, size, '\'') &&
!findchar(s, size, '"')) ? '"' : '\'';
/* Escape quotes */
if (quotes &&
(ch == (Py_UNICODE) PyString_AS_STRING(repr)[1] || ch == '\\')) {
/* Map 21-bit characters to '\U00xxxxxx' */
else if (ch >= 0x10000) {
int offset = p - PyString_AS_STRING(repr);
/* Resize the string if necessary */
if (offset + 12 > PyString_GET_SIZE(repr)) {
if (_PyString_Resize(&repr, PyString_GET_SIZE(repr) + 100))
p = PyString_AS_STRING(repr) + offset;
*p++ = 'U';
*p++ = hexdigit[(ch >> 28) & 0x0000000F];
*p++ = hexdigit[(ch >> 24) & 0x0000000F];
*p++ = hexdigit[(ch >> 20) & 0x0000000F];
*p++ = hexdigit[(ch >> 16) & 0x0000000F];
*p++ = hexdigit[(ch >> 12) & 0x0000000F];
*p++ = hexdigit[(ch >> 8) & 0x0000000F];
*p++ = hexdigit[(ch >> 4) & 0x0000000F];
*p++ = hexdigit[ch & 0x0000000F];
/* Map UTF-16 surrogate pairs to Unicode \UXXXXXXXX escapes */
else if (ch >= 0xD800 && ch < 0xDC00) {
Py_UNICODE ch2;
Py_UCS4 ucs;
ch2 = *s++;
size--;
if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
*p++ = hexdigit[(ucs >> 28) & 0x0000000F];
*p++ = hexdigit[(ucs >> 24) & 0x0000000F];
*p++ = hexdigit[(ucs >> 20) & 0x0000000F];
*p++ = hexdigit[(ucs >> 16) & 0x0000000F];
*p++ = hexdigit[(ucs >> 12) & 0x0000000F];
*p++ = hexdigit[(ucs >> 8) & 0x0000000F];
*p++ = hexdigit[(ucs >> 4) & 0x0000000F];
*p++ = hexdigit[ucs & 0x0000000F];
/* Fall through: isolated surrogates are copied as-is */
size++;
/* Map 16-bit characters to '\uxxxx' */
if (ch >= 256) {
*p++ = hexdigit[(ch >> 12) & 0x000F];
*p++ = hexdigit[(ch >> 8) & 0x000F];
*p++ = hexdigit[(ch >> 4) & 0x000F];
*p++ = hexdigit[ch & 0x000F];
/* Map special whitespace to '\t', \n', '\r' */
else if (ch == '\t') {
*p++ = 't';
else if (ch == '\n') {
*p++ = 'n';
else if (ch == '\r') {
*p++ = 'r';
/* Map non-printable US ASCII to '\xhh' */
else if (ch < ' ' || ch >= 0x7F) {
*p++ = 'x';
/* Copy everything else as-is */
if (quotes)
*p++ = PyString_AS_STRING(repr)[1];
*p = '\0';
_PyString_Resize(&repr, p - PyString_AS_STRING(repr));
return repr;
PyObject *PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
return unicodeescape_string(s, size, 0);
PyObject *PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
return PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
PyUnicode_GET_SIZE(unicode));
/* --- Raw Unicode Escape Codec ------------------------------------------- */
PyObject *PyUnicode_DecodeRawUnicodeEscape(const char *s,
const char *bs;
length after conversion to the true value. (But decoding error
handler might have to resize the string) */
Py_UCS4 x;
int count;
*p++ = (unsigned char)*s++;
/* \u-escapes are only interpreted iff the number of leading
backslashes if odd */
bs = s;
for (;s < end;) {
if (*s != '\\')
if (((s - bs) & 1) == 0 ||
s >= end ||
(*s != 'u' && *s != 'U')) {
p--;
count = *s=='u' ? 4 : 8;
/* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
for (x = 0, i = 0; i < count; ++i, ++s) {
c = (unsigned char)*s;
"rawunicodeescape", "truncated \\uXXXX",
x = (x<<4) & ~0xF;
x += c - '0';
x += 10 + c - 'a';
x += 10 + c - 'A';
if (x > 0x10000) {
"rawunicodeescape", "\\Uxxxxxxxx out of range",
PyObject *PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
char *q;
repr = PyString_FromStringAndSize(NULL, 10 * size);
repr = PyString_FromStringAndSize(NULL, 6 * size);
p = q = PyString_AS_STRING(repr);
/* Map 32-bit characters to '\Uxxxxxxxx' */
*p++ = hexdigit[(ch >> 28) & 0xf];
*p++ = hexdigit[(ch >> 24) & 0xf];
*p++ = hexdigit[(ch >> 20) & 0xf];
*p++ = hexdigit[(ch >> 16) & 0xf];
*p++ = hexdigit[(ch >> 12) & 0xf];
*p++ = hexdigit[(ch >> 8) & 0xf];
*p++ = hexdigit[(ch >> 4) & 0xf];
*p++ = hexdigit[ch & 15];
_PyString_Resize(&repr, p - q);
PyObject *PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
return PyUnicode_EncodeRawUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
/* --- Latin-1 Codec ------------------------------------------------------ */
PyObject *PyUnicode_DecodeLatin1(const char *s,
/* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
if (size == 1) {
Py_UNICODE r = *(unsigned char*)s;
return PyUnicode_FromUnicode(&r, 1);
while (size-- > 0)
/* create or adjust a UnicodeEncodeError */
static void make_encode_exception(PyObject **exceptionObject,
const Py_UNICODE *unicode, int size,
int startpos, int endpos,
const char *reason)
*exceptionObject = PyUnicodeEncodeError_Create(
encoding, unicode, size, startpos, endpos, reason);
if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
return;
Py_DECREF(*exceptionObject);
*exceptionObject = NULL;
/* raises a UnicodeEncodeError */
static void raise_encode_exception(PyObject **exceptionObject,
make_encode_exception(exceptionObject,
if (*exceptionObject != NULL)
PyCodec_StrictErrors(*exceptionObject);
put the result into newpos and return the replacement string, which
has to be freed by the caller */
static PyObject *unicode_encode_call_errorhandler(const char *errors,
PyObject **errorHandler,
const Py_UNICODE *unicode, int size, PyObject **exceptionObject,
int *newpos)
static char *argparse = "O!i;encoding error handler must return (unicode, int) tuple";
PyObject *restuple;
PyObject *resunicode;
restuple = PyObject_CallFunctionObjArgs(
*errorHandler, *exceptionObject, NULL);
Py_DECREF(restuple);
if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
&resunicode, newpos)) {
if (*newpos<0)
*newpos = size+*newpos;
if (*newpos<0 || *newpos>size) {
PyErr_Format(PyExc_IndexError, "position %d from error handler out of bounds", *newpos);
Py_INCREF(resunicode);
return resunicode;
static PyObject *unicode_encode_ucs1(const Py_UNICODE *p,
int limit)
/* output object */
PyObject *res;
/* pointers to the beginning and end+1 of input */
const Py_UNICODE *startp = p;
const Py_UNICODE *endp = p + size;
/* pointer to the beginning of the unencodable characters */
/* const Py_UNICODE *badp = NULL; */
/* pointer into the output */
char *str;
/* current output position */
int respos = 0;
int ressize;
char *encoding = (limit == 256) ? "latin-1" : "ascii";
char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
/* the following variable is used for caching string comparisons
* -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
int known_errorHandler = -1;
/* allocate enough for a simple encoding without
replacements, if we need more, we'll resize */
res = PyString_FromStringAndSize(NULL, size);
if (res == NULL)
str = PyString_AS_STRING(res);
ressize = size;
while (p<endp) {
Py_UNICODE c = *p;
/* can we encode this? */
if (c<limit) {
/* no overflow check, because we know that the space is enough */
*str++ = (char)c;
++p;
int unicodepos = p-startp;
PyObject *repunicode;
int respos;
Py_UNICODE *uni2;
/* startpos for collecting unencodable chars */
const Py_UNICODE *collstart = p;
const Py_UNICODE *collend = p;
/* find all unecodable characters */
while ((collend < endp) && ((*collend)>=limit))
++collend;
/* cache callback name lookup (if not done yet, i.e. it's the first error) */
if (known_errorHandler==-1) {
if ((errors==NULL) || (!strcmp(errors, "strict")))
known_errorHandler = 1;
else if (!strcmp(errors, "replace"))
known_errorHandler = 2;
else if (!strcmp(errors, "ignore"))
known_errorHandler = 3;
else if (!strcmp(errors, "xmlcharrefreplace"))
known_errorHandler = 4;
known_errorHandler = 0;
switch (known_errorHandler) {
case 1: /* strict */
raise_encode_exception(&exc, encoding, startp, size, collstart-startp, collend-startp, reason);
case 2: /* replace */
while (collstart++<collend)
*str++ = '?'; /* fall through */
case 3: /* ignore */
p = collend;
case 4: /* xmlcharrefreplace */
respos = str-PyString_AS_STRING(res);
/* determine replacement size (temporarily (mis)uses p) */
for (p = collstart, repsize = 0; p < collend; ++p) {
if (*p<10)
repsize += 2+1+1;
else if (*p<100)
repsize += 2+2+1;
else if (*p<1000)
repsize += 2+3+1;
else if (*p<10000)
repsize += 2+4+1;
repsize += 2+5+1;
else if (*p<100000)
else if (*p<1000000)
repsize += 2+6+1;
repsize += 2+7+1;
requiredsize = respos+repsize+(endp-collend);
if (requiredsize > ressize) {
if (requiredsize<2*ressize)
requiredsize = 2*ressize;
if (_PyString_Resize(&res, requiredsize))
str = PyString_AS_STRING(res) + respos;
ressize = requiredsize;
/* generate replacement (temporarily (mis)uses p) */
for (p = collstart; p < collend; ++p) {
str += sprintf(str, "&#%d;", (int)*p);
repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
encoding, reason, startp, size, &exc,
collstart-startp, collend-startp, &newpos);
if (repunicode == NULL)
have+the replacement+the rest of the string, so
we won't have to check space for encodable characters) */
if (_PyString_Resize(&res, requiredsize)) {
Py_DECREF(repunicode);
/* check if there is anything unencodable in the replacement
and copy it to the output */
for (uni2 = PyUnicode_AS_UNICODE(repunicode);repsize-->0; ++uni2, ++str) {
c = *uni2;
if (c >= limit) {
raise_encode_exception(&exc, encoding, startp, size,
unicodepos, unicodepos+1, reason);
*str = (char)c;
p = startp + newpos;
/* Resize if we allocated to much */
if (respos<ressize)
/* If this falls res will be NULL */
_PyString_Resize(&res, respos);
Py_XDECREF(res);
PyObject *PyUnicode_EncodeLatin1(const Py_UNICODE *p,
return unicode_encode_ucs1(p, size, errors, 256);
PyObject *PyUnicode_AsLatin1String(PyObject *unicode)
return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(unicode),
/* --- 7-bit ASCII Codec -------------------------------------------------- */
PyObject *PyUnicode_DecodeASCII(const char *s,
/* ASCII is equivalent to the first 128 ordinals in Unicode. */
if (size == 1 && *(unsigned char*)s < 128) {
register unsigned char c = (unsigned char)*s;
if (c < 128) {
*p++ = c;
++s;
endinpos = startinpos + 1;
outpos = p - (Py_UNICODE *)PyUnicode_AS_UNICODE(v);
"ascii", "ordinal not in range(128)",
if (p - PyUnicode_AS_UNICODE(v) < PyString_GET_SIZE(v))
PyObject *PyUnicode_EncodeASCII(const Py_UNICODE *p,
return unicode_encode_ucs1(p, size, errors, 128);
PyObject *PyUnicode_AsASCIIString(PyObject *unicode)
return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
/* --- MBCS codecs for Windows -------------------------------------------- */
PyObject *PyUnicode_DecodeMBCS(const char *s,
/* First get the size of the result */
DWORD usize = MultiByteToWideChar(CP_ACP, 0, s, size, NULL, 0);
if (size > 0 && usize==0)
return PyErr_SetFromWindowsErrWithFilename(0, NULL);
v = _PyUnicode_New(usize);
if (usize == 0)
if (0 == MultiByteToWideChar(CP_ACP, 0, s, size, p, usize)) {
PyObject *PyUnicode_EncodeMBCS(const Py_UNICODE *p,
char *s;
DWORD mbcssize;
/* If there are no characters, bail now! */
if (size==0)
return PyString_FromString("");
mbcssize = WideCharToMultiByte(CP_ACP, 0, p, size, NULL, 0, NULL, NULL);
if (mbcssize==0)
repr = PyString_FromStringAndSize(NULL, mbcssize);
if (mbcssize == 0)
/* Do the conversion */
s = PyString_AS_STRING(repr);
if (0 == WideCharToMultiByte(CP_ACP, 0, p, size, s, mbcssize, NULL, NULL)) {
Py_DECREF(repr);
PyObject *PyUnicode_AsMBCSString(PyObject *unicode)
return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
#endif /* MS_WINDOWS */
/* --- Character Mapping Codec -------------------------------------------- */
PyObject *PyUnicode_DecodeCharmap(const char *s,
PyObject *mapping,
int extrachars = 0;
/* Default to Latin-1 */
if (mapping == NULL)
unsigned char ch = *s;
PyObject *w, *x;
/* Get mapping (char ordinal -> integer, Unicode char or None) */
w = PyInt_FromLong((long)ch);
x = PyObject_GetItem(mapping, w);
Py_DECREF(w);
if (x == NULL) {
if (PyErr_ExceptionMatches(PyExc_LookupError)) {
/* No mapping found means: mapping is undefined. */
PyErr_Clear();
x = Py_None;
Py_INCREF(x);
/* Apply mapping */
if (PyInt_Check(x)) {
long value = PyInt_AS_LONG(x);
if (value < 0 || value > 65535) {
"character mapping must be in range(65536)");
Py_DECREF(x);
*p++ = (Py_UNICODE)value;
else if (x == Py_None) {
/* undefined mapping */
"charmap", "character maps to <undefined>",
(PyObject **)&v, &outpos, &p)) {
else if (PyUnicode_Check(x)) {
int targetsize = PyUnicode_GET_SIZE(x);
if (targetsize == 1)
/* 1-1 mapping */
*p++ = *PyUnicode_AS_UNICODE(x);
else if (targetsize > 1) {
/* 1-n mapping */
if (targetsize > extrachars) {
/* resize first */
int oldpos = (int)(p - PyUnicode_AS_UNICODE(v));
int needed = (targetsize - extrachars) + \
(targetsize << 2);
extrachars += needed;
if (_PyUnicode_Resize(&v,
PyUnicode_GET_SIZE(v) + needed) < 0) {
p = PyUnicode_AS_UNICODE(v) + oldpos;
Py_UNICODE_COPY(p,
PyUnicode_AS_UNICODE(x),
targetsize);
p += targetsize;
extrachars -= targetsize;
/* 1-0 mapping: skip the character */
/* wrong return value */
"character mapping must return integer, None or unicode");
if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
/* Lookup the character ch in the mapping. If the character
can't be found, Py_None is returned (or NULL, if another
error occured). */
static PyObject *charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
PyObject *w = PyInt_FromLong((long)c);
PyObject *x;
return x;
else if (x == Py_None)
else if (PyInt_Check(x)) {
if (value < 0 || value > 255) {
"character mapping must be in range(256)");
else if (PyString_Check(x))
"character mapping must return integer, None or str");
/* lookup the character, put the result in the output string and adjust
various state variables. Reallocate the output string if not enough
space is available. Return a new reference to the object that
was put in the output buffer, or Py_None, if the mapping was undefined
(in which case no character was written) or NULL, if a
reallocation error ocurred. The called must decref the result */
PyObject *charmapencode_output(Py_UNICODE c, PyObject *mapping,
PyObject **outobj, int *outpos)
PyObject *rep = charmapencode_lookup(c, mapping);
if (rep==NULL)
else if (rep==Py_None)
return rep;
char *outstart = PyString_AS_STRING(*outobj);
int outsize = PyString_GET_SIZE(*outobj);
if (PyInt_Check(rep)) {
int requiredsize = *outpos+1;
if (outsize<requiredsize) {
/* exponentially overallocate to minimize reallocations */
if (requiredsize < 2*outsize)
if (_PyString_Resize(outobj, requiredsize)) {
Py_DECREF(rep);
outstart = PyString_AS_STRING(*outobj);
outstart[(*outpos)++] = (char)PyInt_AS_LONG(rep);
const char *repchars = PyString_AS_STRING(rep);
int repsize = PyString_GET_SIZE(rep);
int requiredsize = *outpos+repsize;
memcpy(outstart + *outpos, repchars, repsize);
/* handle an error in PyUnicode_EncodeCharmap
Return 0 on success, -1 on error */
int charmap_encoding_error(
const Py_UNICODE *p, int size, int *inpos, PyObject *mapping,
PyObject **exceptionObject,
int *known_errorHandler, PyObject **errorHandler, const char *errors,
PyObject **res, int *respos)
PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
int collstartpos = *inpos;
int collendpos = *inpos+1;
int collpos;
char *encoding = "charmap";
char *reason = "character maps to <undefined>";
/* find all unencodable characters */
while (collendpos < size) {
x = charmapencode_lookup(p[collendpos], mapping);
if (x==NULL)
else if (x!=Py_None) {
++collendpos;
/* cache callback name lookup
* (if not done yet, i.e. it's the first error) */
if (*known_errorHandler==-1) {
*known_errorHandler = 1;
*known_errorHandler = 2;
*known_errorHandler = 3;
*known_errorHandler = 4;
*known_errorHandler = 0;
switch (*known_errorHandler) {
raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
for (collpos = collstartpos; collpos<collendpos; ++collpos) {
x = charmapencode_output('?', mapping, res, respos);
if (x==NULL) {
else if (x==Py_None) {
/* fall through */
*inpos = collendpos;
for (collpos = collstartpos; collpos < collendpos; ++collpos) {
char buffer[2+29+1+1];
char *cp;
sprintf(buffer, "&#%d;", (int)p[collpos]);
for (cp = buffer; *cp; ++cp) {
x = charmapencode_output(*cp, mapping, res, respos);
repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
encoding, reason, p, size, exceptionObject,
collstartpos, collendpos, &newpos);
/* generate replacement */
for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
x = charmapencode_output(*uni2, mapping, res, respos);
*inpos = newpos;
PyObject *PyUnicode_EncodeCharmap(const Py_UNICODE *p,
PyObject *res = NULL;
/* current input position */
int inpos = 0;
* -1=not initialized, 0=unknown, 1=strict, 2=replace,
* 3=ignore, 4=xmlcharrefreplace */
return PyUnicode_EncodeLatin1(p, size, errors);
while (inpos<size) {
/* try to encode it */
PyObject *x = charmapencode_output(p[inpos], mapping, &res, &respos);
if (x==NULL) /* error */
if (x==Py_None) { /* unencodable character */
if (charmap_encoding_error(p, size, &inpos, mapping,
&exc,
&known_errorHandler, &errorHandler, errors,
&res, &respos)) {
/* done with this character => adjust input position */
++inpos;
if (respos<PyString_GET_SIZE(res)) {
if (_PyString_Resize(&res, respos))
PyObject *PyUnicode_AsCharmapString(PyObject *unicode,
PyObject *mapping)
if (!PyUnicode_Check(unicode) || mapping == NULL) {
return PyUnicode_EncodeCharmap(PyUnicode_AS_UNICODE(unicode),
mapping,
/* create or adjust a UnicodeTranslateError */
static void make_translate_exception(PyObject **exceptionObject,
*exceptionObject = PyUnicodeTranslateError_Create(
unicode, size, startpos, endpos, reason);
if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
/* raises a UnicodeTranslateError */
static void raise_translate_exception(PyObject **exceptionObject,
make_translate_exception(exceptionObject,
static PyObject *unicode_translate_call_errorhandler(const char *errors,
const char *reason,
static char *argparse = "O!i;translating error handler must return (unicode, int) tuple";
/* Lookup the character ch in the mapping and put the result in result,
which must be decrefed by the caller.
int charmaptranslate_lookup(Py_UNICODE c, PyObject *mapping, PyObject **result)
/* No mapping found means: use 1:1 mapping. */
*result = NULL;
*result = x;
long max = PyUnicode_GetMax();
if (value < 0 || value > max) {
"character mapping must be in range(0x%lx)", max+1);
/* ensure that *outobj is at least requiredsize characters long,
if not reallocate and adjust various state variables.
int charmaptranslate_makespace(PyObject **outobj, Py_UNICODE **outp,
int requiredsize)
int oldsize = PyUnicode_GET_SIZE(*outobj);
if (requiredsize > oldsize) {
/* remember old output position */
int outpos = *outp-PyUnicode_AS_UNICODE(*outobj);
if (requiredsize < 2 * oldsize)
requiredsize = 2 * oldsize;
if (_PyUnicode_Resize(outobj, requiredsize) < 0)
*outp = PyUnicode_AS_UNICODE(*outobj) + outpos;
various state variables. Return a new reference to the object that
was put in the output buffer in *result, or Py_None, if the mapping was
undefined (in which case no character was written).
The called must decref result.
Return 0 on success, -1 on error. */
int charmaptranslate_output(const Py_UNICODE *startinp, const Py_UNICODE *curinp,
int insize, PyObject *mapping, PyObject **outobj, Py_UNICODE **outp,
PyObject **res)
if (charmaptranslate_lookup(*curinp, mapping, res))
if (*res==NULL) {
/* not found => default to 1:1 mapping */
*(*outp)++ = *curinp;
else if (*res==Py_None)
else if (PyInt_Check(*res)) {
*(*outp)++ = (Py_UNICODE)PyInt_AS_LONG(*res);
else if (PyUnicode_Check(*res)) {
int repsize = PyUnicode_GET_SIZE(*res);
if (repsize==1) {
*(*outp)++ = *PyUnicode_AS_UNICODE(*res);
else if (repsize!=0) {
/* more than one character */
int requiredsize = (*outp-PyUnicode_AS_UNICODE(*outobj)) +
(insize - (curinp-startinp)) +
repsize - 1;
if (charmaptranslate_makespace(outobj, outp, requiredsize))
memcpy(*outp, PyUnicode_AS_UNICODE(*res), sizeof(Py_UNICODE)*repsize);
*outp += repsize;
PyObject *PyUnicode_TranslateCharmap(const Py_UNICODE *p,
Py_UNICODE *str;
if (mapping == NULL) {
/* allocate enough for a simple 1:1 translation without
res = PyUnicode_FromUnicode(NULL, size);
str = PyUnicode_AS_UNICODE(res);
PyObject *x = NULL;
if (charmaptranslate_output(startp, p, size, mapping, &res, &str, &x)) {
Py_XDECREF(x);
if (x!=Py_None) /* it worked => adjust input pointer */
else { /* untranslatable character */
/* startpos for collecting untranslatable chars */
const Py_UNICODE *collend = p+1;
const Py_UNICODE *coll;
/* find all untranslatable characters */
while (collend < endp) {
if (charmaptranslate_lookup(*collend, mapping, &x))
if (x!=Py_None)
raise_translate_exception(&exc, startp, size, collstart-startp, collend-startp, reason);
/* No need to check for space, this is a 1:1 replacement */
for (coll = collstart; coll<collend; ++coll)
*str++ = '?';
sprintf(buffer, "&#%d;", (int)*p);
if (charmaptranslate_makespace(&res, &str,
(str-PyUnicode_AS_UNICODE(res))+strlen(buffer)+(endp-collend)))
for (cp = buffer; *cp; ++cp)
*str++ = *cp;
repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
reason, startp, size, &exc,
(str-PyUnicode_AS_UNICODE(res))+repsize+(endp-collend))) {
for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2)
*str++ = *uni2;
respos = str-PyUnicode_AS_UNICODE(res);
if (respos<PyUnicode_GET_SIZE(res)) {
if (_PyUnicode_Resize(&res, respos) < 0)
PyObject *PyUnicode_Translate(PyObject *str,
PyObject *result;
str = PyUnicode_FromObject(str);
if (str == NULL)
result = PyUnicode_TranslateCharmap(PyUnicode_AS_UNICODE(str),
PyUnicode_GET_SIZE(str),
errors);
Py_DECREF(str);
return result;
Py_XDECREF(str);
/* --- Decimal Encoder ---------------------------------------------------- */
int PyUnicode_EncodeDecimal(Py_UNICODE *s,
int length,
char *output,
Py_UNICODE *p, *end;
const char *encoding = "decimal";
const char *reason = "invalid decimal Unicode string";
if (output == NULL) {
p = s;
end = s + length;
while (p < end) {
register Py_UNICODE ch = *p;
int decimal;
Py_UNICODE *collstart;
Py_UNICODE *collend;
if (Py_UNICODE_ISSPACE(ch)) {
*output++ = ' ';
decimal = Py_UNICODE_TODECIMAL(ch);
if (decimal >= 0) {
*output++ = '0' + decimal;
if (0 < ch && ch < 256) {
*output++ = (char)ch;
/* All other characters are considered unencodable */
collstart = p;
collend = p+1;
while (collend < end) {
if ((0 < *collend && *collend < 256) ||
!Py_UNICODE_ISSPACE(*collend) ||
Py_UNICODE_TODECIMAL(*collend))
raise_encode_exception(&exc, encoding, s, length, collstart-s, collend-s, reason);
for (p = collstart; p < collend; ++p)
*output++ = '?';
output += sprintf(output, "&#%d;", (int)*p);
encoding, reason, s, length, &exc,
collstart-s, collend-s, &newpos);
Py_UNICODE ch = *uni2;
if (Py_UNICODE_ISSPACE(ch))
if (decimal >= 0)
else if (0 < ch && ch < 256)
raise_encode_exception(&exc, encoding,
s, length, collstart-s, collend-s, reason);
p = s + newpos;
/* 0-terminate the output string */
*output++ = '\0';
/* --- Helpers ------------------------------------------------------------ */
int count(PyUnicodeObject *self,
int start,
int end,
PyUnicodeObject *substring)
int count = 0;
if (start < 0)
start += self->length;
start = 0;
if (end > self->length)
end = self->length;
if (end < 0)
end += self->length;
end = 0;
if (substring->length == 0)
return (end - start + 1);
end -= substring->length;
while (start <= end)
if (Py_UNICODE_MATCH(self, start, substring)) {
count++;
start += substring->length;
start++;
return count;
int PyUnicode_Count(PyObject *str,
PyObject *substr,
int end)
int result;
substr = PyUnicode_FromObject(substr);
if (substr == NULL) {
result = count((PyUnicodeObject *)str,
start, end,
(PyUnicodeObject *)substr);
Py_DECREF(substr);
int findstring(PyUnicodeObject *self,
PyUnicodeObject *substring,
int direction)
return (direction > 0) ? start : end;
if (direction < 0) {
for (; end >= start; end--)
if (Py_UNICODE_MATCH(self, end, substring))
return end;
for (; start <= end; start++)
if (Py_UNICODE_MATCH(self, start, substring))
return start;
int PyUnicode_Find(PyObject *str,
return -2;
result = findstring((PyUnicodeObject *)str,
(PyUnicodeObject *)substr,
start, end, direction);
int tailmatch(PyUnicodeObject *self,
return 1;
if (end < start)
if (direction > 0) {
int PyUnicode_Tailmatch(PyObject *str,
result = tailmatch((PyUnicodeObject *)str,
const Py_UNICODE *findchar(const Py_UNICODE *s,
Py_UNICODE ch)
/* like wcschr, but doesn't stop at NULL characters */
if (*s == ch)
return s;
/* Apply fixfct filter to the Unicode object self and return a
reference to the modified object */
PyObject *fixup(PyUnicodeObject *self,
int (*fixfct)(PyUnicodeObject *s))
PyUnicodeObject *u;
u = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, self->length);
if (u == NULL)
Py_UNICODE_COPY(u->str, self->str, self->length);
if (!fixfct(u) && PyUnicode_CheckExact(self)) {
/* fixfct should return TRUE if it modified the buffer. If
FALSE, return a reference to the original buffer instead
(to save space, not time) */
Py_INCREF(self);
Py_DECREF(u);
return (PyObject*) self;
return (PyObject*) u;
int fixupper(PyUnicodeObject *self)
int len = self->length;
Py_UNICODE *s = self->str;
int status = 0;
while (len-- > 0) {
register Py_UNICODE ch;
ch = Py_UNICODE_TOUPPER(*s);
if (ch != *s) {
status = 1;
*s = ch;
return status;
int fixlower(PyUnicodeObject *self)
ch = Py_UNICODE_TOLOWER(*s);
int fixswapcase(PyUnicodeObject *self)
if (Py_UNICODE_ISUPPER(*s)) {
*s = Py_UNICODE_TOLOWER(*s);
} else if (Py_UNICODE_ISLOWER(*s)) {
*s = Py_UNICODE_TOUPPER(*s);
int fixcapitalize(PyUnicodeObject *self)
if (len == 0)
if (Py_UNICODE_ISLOWER(*s)) {
while (--len > 0) {
int fixtitle(PyUnicodeObject *self)
register Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
register Py_UNICODE *e;
int previous_is_cased;
/* Shortcut for single character strings */
if (PyUnicode_GET_SIZE(self) == 1) {
Py_UNICODE ch = Py_UNICODE_TOTITLE(*p);
if (*p != ch) {
*p = ch;
e = p + PyUnicode_GET_SIZE(self);
previous_is_cased = 0;
for (; p < e; p++) {
register const Py_UNICODE ch = *p;
if (previous_is_cased)
*p = Py_UNICODE_TOLOWER(ch);
*p = Py_UNICODE_TOTITLE(ch);
if (Py_UNICODE_ISLOWER(ch) ||
Py_UNICODE_ISUPPER(ch) ||
Py_UNICODE_ISTITLE(ch))
previous_is_cased = 1;
PyObject *PyUnicode_Join(PyObject *separator,
PyObject *seq)
Py_UNICODE *sep;
int seplen;
PyUnicodeObject *res = NULL;
int reslen = 0;
int sz = 100;
PyObject *it;
it = PyObject_GetIter(seq);
if (it == NULL)
if (separator == NULL) {
Py_UNICODE blank = ' ';
sep = ␣
seplen = 1;
separator = PyUnicode_FromObject(separator);
if (separator == NULL)
sep = PyUnicode_AS_UNICODE(separator);
seplen = PyUnicode_GET_SIZE(separator);
res = _PyUnicode_New(sz);
p = PyUnicode_AS_UNICODE(res);
reslen = 0;
for (i = 0; ; ++i) {
int itemlen;
PyObject *item = PyIter_Next(it);
if (item == NULL) {
if (PyErr_Occurred())
if (!PyUnicode_Check(item)) {
if (!PyString_Check(item)) {
"sequence item %i: expected string or Unicode,"
" %.80s found",
i, item->ob_type->tp_name);
Py_DECREF(item);
v = PyUnicode_FromObject(item);
item = v;
if (item == NULL)
itemlen = PyUnicode_GET_SIZE(item);
while (reslen + itemlen + seplen >= sz) {
if (_PyUnicode_Resize(&res, sz*2) < 0) {
sz *= 2;
p = PyUnicode_AS_UNICODE(res) + reslen;
if (i > 0) {
Py_UNICODE_COPY(p, sep, seplen);
p += seplen;
reslen += seplen;
Py_UNICODE_COPY(p, PyUnicode_AS_UNICODE(item), itemlen);
p += itemlen;
reslen += itemlen;
if (_PyUnicode_Resize(&res, reslen) < 0)
Py_XDECREF(separator);
Py_DECREF(it);
return (PyObject *)res;
PyUnicodeObject *pad(PyUnicodeObject *self,
int left,
int right,
Py_UNICODE fill)
if (left < 0)
left = 0;
if (right < 0)
right = 0;
if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
return self;
u = _PyUnicode_New(left + self->length + right);
if (u) {
if (left)
Py_UNICODE_FILL(u->str, fill, left);
Py_UNICODE_COPY(u->str + left, self->str, self->length);
if (right)
Py_UNICODE_FILL(u->str + left + self->length, fill, right);
return u;
#define SPLIT_APPEND(data, left, right) \
str = PyUnicode_FromUnicode((data) + (left), (right) - (left)); \
if (!str) \
goto onError; \
if (PyList_Append(list, str)) { \
Py_DECREF(str); \
else \
#define SPLIT_INSERT(data, left, right) \
if (PyList_Insert(list, 0, str)) { \
PyObject *split_whitespace(PyUnicodeObject *self,
PyObject *list,
int maxcount)
register int j;
PyObject *str;
for (i = j = 0; i < len; ) {
/* find a token */
while (i < len && Py_UNICODE_ISSPACE(self->str[i]))
j = i;
while (i < len && !Py_UNICODE_ISSPACE(self->str[i]))
if (j < i) {
if (maxcount-- <= 0)
SPLIT_APPEND(self->str, j, i);
if (j < len) {
SPLIT_APPEND(self->str, j, len);
return list;
Py_DECREF(list);
PyObject *PyUnicode_Splitlines(PyObject *string,
int keepends)
PyObject *list;
Py_UNICODE *data;
string = PyUnicode_FromObject(string);
if (string == NULL)
data = PyUnicode_AS_UNICODE(string);
len = PyUnicode_GET_SIZE(string);
list = PyList_New(0);
if (!list)
int eol;
/* Find a line and append it */
while (i < len && !Py_UNICODE_ISLINEBREAK(data[i]))
/* Skip the line break reading CRLF as one line break */
eol = i;
if (i < len) {
if (data[i] == '\r' && i + 1 < len &&
data[i+1] == '\n')
i += 2;
if (keepends)
SPLIT_APPEND(data, j, eol);
SPLIT_APPEND(data, j, len);
Py_DECREF(string);
PyObject *split_char(PyUnicodeObject *self,
Py_UNICODE ch,
if (self->str[i] == ch) {
i = j = i + 1;
if (j <= len) {
PyObject *split_substring(PyUnicodeObject *self,
int sublen = substring->length;
for (i = j = 0; i <= len - sublen; ) {
if (Py_UNICODE_MATCH(self, i, substring)) {
i = j = i + sublen;
PyObject *rsplit_whitespace(PyUnicodeObject *self,
for (i = j = len - 1; i >= 0; ) {
while (i >= 0 && Py_UNICODE_ISSPACE(self->str[i]))
i--;
while (i >= 0 && !Py_UNICODE_ISSPACE(self->str[i]))
if (j > i) {
SPLIT_INSERT(self->str, i + 1, j + 1);
if (j >= 0) {
SPLIT_INSERT(self->str, 0, j + 1);
PyObject *rsplit_char(PyUnicodeObject *self,
j = i = i - 1;
if (j >= -1) {
PyObject *rsplit_substring(PyUnicodeObject *self,
for (i = len - sublen, j = len; i >= 0; ) {
SPLIT_INSERT(self->str, i + sublen, j);
i -= sublen;
SPLIT_INSERT(self->str, 0, j);
#undef SPLIT_APPEND
#undef SPLIT_INSERT
PyObject *split(PyUnicodeObject *self,
if (maxcount < 0)
maxcount = INT_MAX;
if (substring == NULL)
return split_whitespace(self,list,maxcount);
else if (substring->length == 1)
return split_char(self,list,substring->str[0],maxcount);
else if (substring->length == 0) {
PyErr_SetString(PyExc_ValueError, "empty separator");
return split_substring(self,list,substring,maxcount);
PyObject *rsplit(PyUnicodeObject *self,
return rsplit_whitespace(self,list,maxcount);
return rsplit_char(self,list,substring->str[0],maxcount);
return rsplit_substring(self,list,substring,maxcount);
PyObject *replace(PyUnicodeObject *self,
PyUnicodeObject *str1,
PyUnicodeObject *str2,
if (str1->length == 1 && str2->length == 1) {
/* replace characters */
if (!findchar(self->str, self->length, str1->str[0]) &&
PyUnicode_CheckExact(self)) {
/* nothing to replace, return original string */
u = self;
Py_UNICODE u1 = str1->str[0];
Py_UNICODE u2 = str2->str[0];
u = (PyUnicodeObject*) PyUnicode_FromUnicode(
self->length
Py_UNICODE_COPY(u->str, self->str,
self->length);
for (i = 0; i < u->length; i++)
if (u->str[i] == u1) {
if (--maxcount < 0)
u->str[i] = u2;
int n, i;
/* replace strings */
n = count(self, 0, self->length, str1);
if (n > maxcount)
n = maxcount;
if (n == 0) {
if (PyUnicode_CheckExact(self)) {
u = (PyUnicodeObject *)
PyUnicode_FromUnicode(self->str, self->length);
u = _PyUnicode_New(
self->length + n * (str2->length - str1->length));
i = 0;
p = u->str;
if (str1->length > 0) {
while (i <= self->length - str1->length)
if (Py_UNICODE_MATCH(self, i, str1)) {
/* replace string segment */
Py_UNICODE_COPY(p, str2->str, str2->length);
p += str2->length;
i += str1->length;
if (--n <= 0) {
/* copy remaining part */
Py_UNICODE_COPY(p, self->str+i, self->length-i);
*p++ = self->str[i++];
while (n > 0) {
if (--n <= 0)
return (PyObject *) u;
/* --- Unicode Object Methods --------------------------------------------- */
PyDoc_STRVAR(title__doc__,
"S.title() -> unicode\n\
\n\
Return a titlecased version of S, i.e. words start with title case\n\
characters, all remaining cased characters have lower case.");
static PyObject*
unicode_title(PyUnicodeObject *self)
return fixup(self, fixtitle);
PyDoc_STRVAR(capitalize__doc__,
"S.capitalize() -> unicode\n\
Return a capitalized version of S, i.e. make the first character\n\
have upper case.");
unicode_capitalize(PyUnicodeObject *self)
return fixup(self, fixcapitalize);
PyDoc_STRVAR(capwords__doc__,
"S.capwords() -> unicode\n\
Apply .capitalize() to all words in S and return the result with\n\
normalized whitespace (all whitespace strings are replaced by ' ').");
unicode_capwords(PyUnicodeObject *self)
PyObject *item;
/* Split into words */
list = split(self, NULL, -1);
/* Capitalize each word */
for (i = 0; i < PyList_GET_SIZE(list); i++) {
item = fixup((PyUnicodeObject *)PyList_GET_ITEM(list, i),
fixcapitalize);
Py_DECREF(PyList_GET_ITEM(list, i));
PyList_SET_ITEM(list, i, item);
/* Join the words to form a new string */
item = PyUnicode_Join(NULL, list);
return (PyObject *)item;
/* Argument converter. Coerces to a single unicode character */
static int
convert_uc(PyObject *obj, void *addr)
Py_UNICODE *fillcharloc = (Py_UNICODE *)addr;
PyObject *uniobj;
Py_UNICODE *unistr;
uniobj = PyUnicode_FromObject(obj);
if (uniobj == NULL) {
"The fill character cannot be converted to Unicode");
if (PyUnicode_GET_SIZE(uniobj) != 1) {
"The fill character must be exactly one character long");
Py_DECREF(uniobj);
unistr = PyUnicode_AS_UNICODE(uniobj);
*fillcharloc = unistr[0];
PyDoc_STRVAR(center__doc__,
"S.center(width[, fillchar]) -> unicode\n\
Return S centered in a Unicode string of length width. Padding is\n\
done using the specified fill character (default is a space)");
static PyObject *
unicode_center(PyUnicodeObject *self, PyObject *args)
int marg, left;
int width;
Py_UNICODE fillchar = ' ';
if (!PyArg_ParseTuple(args, "i|O&:center", &width, convert_uc, &fillchar))
if (self->length >= width && PyUnicode_CheckExact(self)) {
marg = width - self->length;
left = marg / 2 + (marg & width & 1);
return (PyObject*) pad(self, left, marg - left, fillchar);
/* This code should go into some future Unicode collation support
module. The basic comparison should compare ordinals on a naive
basis (this is what Java does and thus JPython too). */
/* speedy UTF-16 code point order comparison */
/* gleaned from: */
/* http://www-4.ibm.com/software/developer/library/utf16.html?dwzone=unicode */
static short utf16Fixup[32] =
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0x2000, -0x800, -0x800, -0x800, -0x800
unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
int len1, len2;
Py_UNICODE *s1 = str1->str;
Py_UNICODE *s2 = str2->str;
len1 = str1->length;
len2 = str2->length;
while (len1 > 0 && len2 > 0) {
Py_UNICODE c1, c2;
c1 = *s1++;
c2 = *s2++;
if (c1 > (1<<11) * 26)
c1 += utf16Fixup[c1>>11];
if (c2 > (1<<11) * 26)
c2 += utf16Fixup[c2>>11];
/* now c1 and c2 are in UTF-32-compatible order */
if (c1 != c2)
return (c1 < c2) ? -1 : 1;
len1--; len2--;
return (len1 < len2) ? -1 : (len1 != len2);
register int len1, len2;
int PyUnicode_Compare(PyObject *left,
PyObject *right)
PyUnicodeObject *u = NULL, *v = NULL;
/* Coerce the two arguments */
u = (PyUnicodeObject *)PyUnicode_FromObject(left);
v = (PyUnicodeObject *)PyUnicode_FromObject(right);
/* Shortcut for empty or interned objects */
if (v == u) {
result = unicode_compare(u, v);
Py_XDECREF(u);
int PyUnicode_Contains(PyObject *container,
PyObject *element)
int result, size;
register const Py_UNICODE *lhs, *end, *rhs;
v = (PyUnicodeObject *)PyUnicode_FromObject(element);
"'in <string>' requires string as left operand");
u = (PyUnicodeObject *)PyUnicode_FromObject(container);
size = PyUnicode_GET_SIZE(v);
rhs = PyUnicode_AS_UNICODE(v);
lhs = PyUnicode_AS_UNICODE(u);
result = 0;
end = lhs + PyUnicode_GET_SIZE(u);
while (lhs < end) {
if (*lhs++ == *rhs) {
result = 1;
end = lhs + (PyUnicode_GET_SIZE(u) - size);
while (lhs <= end) {
if (memcmp(lhs++, rhs, size * sizeof(Py_UNICODE)) == 0) {
/* Concat to string or Unicode object giving a new Unicode object. */
PyObject *PyUnicode_Concat(PyObject *left,
PyUnicodeObject *u = NULL, *v = NULL, *w;
/* Shortcuts */
if (v == unicode_empty) {
return (PyObject *)u;
if (u == unicode_empty) {
/* Concat the two Unicode strings */
w = _PyUnicode_New(u->length + v->length);
Py_UNICODE_COPY(w->str, u->str, u->length);
Py_UNICODE_COPY(w->str + u->length, v->str, v->length);
return (PyObject *)w;
PyDoc_STRVAR(count__doc__,
"S.count(sub[, start[, end]]) -> int\n\
Return the number of occurrences of substring sub in Unicode string\n\
S[start:end]. Optional arguments start and end are\n\
interpreted as in slice notation.");
unicode_count(PyUnicodeObject *self, PyObject *args)
PyUnicodeObject *substring;
int start = 0;
int end = INT_MAX;
if (!PyArg_ParseTuple(args, "O|O&O&:count", &substring,
_PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
substring = (PyUnicodeObject *)PyUnicode_FromObject(
(PyObject *)substring);
result = PyInt_FromLong((long) count(self, start, end, substring));
Py_DECREF(substring);
PyDoc_STRVAR(encode__doc__,
"S.encode([encoding[,errors]]) -> string or unicode\n\
Encodes S using the codec registered for encoding. encoding defaults\n\
to the default encoding. errors may be given to set a different error\n\
handling scheme. Default is 'strict' meaning that encoding errors raise\n\
a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
'xmlcharrefreplace' as well as any other name registered with\n\
codecs.register_error that can handle UnicodeEncodeErrors.");
unicode_encode(PyUnicodeObject *self, PyObject *args)
char *encoding = NULL;
char *errors = NULL;
if (!PyArg_ParseTuple(args, "|ss:encode", &encoding, &errors))
v = PyUnicode_AsEncodedObject((PyObject *)self, encoding, errors);
if (!PyString_Check(v) && !PyUnicode_Check(v)) {
"encoder did not return a string/unicode object "
"(type=%.400s)",
PyDoc_STRVAR(decode__doc__,
"S.decode([encoding[,errors]]) -> string or unicode\n\
Decodes S using the codec registered for encoding. encoding defaults\n\
a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'\n\
as well as any other name registerd with codecs.register_error that is\n\
able to handle UnicodeDecodeErrors.");
unicode_decode(PyUnicodeObject *self, PyObject *args)
if (!PyArg_ParseTuple(args, "|ss:decode", &encoding, &errors))
v = PyUnicode_AsDecodedObject((PyObject *)self, encoding, errors);
"decoder did not return a string/unicode object "
PyDoc_STRVAR(expandtabs__doc__,
"S.expandtabs([tabsize]) -> unicode\n\
Return a copy of S where all tab characters are expanded using spaces.\n\
If tabsize is not given, a tab size of 8 characters is assumed.");
unicode_expandtabs(PyUnicodeObject *self, PyObject *args)
Py_UNICODE *e;
Py_UNICODE *q;
int i, j;
int tabsize = 8;
if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
/* First pass: determine size of output string */
i = j = 0;
e = self->str + self->length;
for (p = self->str; p < e; p++)
if (*p == '\t') {
if (tabsize > 0)
j += tabsize - (j % tabsize);
j++;
if (*p == '\n' || *p == '\r') {
i += j;
j = 0;
/* Second pass: create output string and fill it */
u = _PyUnicode_New(i + j);
if (!u)
q = u->str;
if (tabsize > 0) {
i = tabsize - (j % tabsize);
j += i;
while (i--)
*q++ = ' ';
*q++ = *p;
if (*p == '\n' || *p == '\r')
PyDoc_STRVAR(find__doc__,
"S.find(sub [,start [,end]]) -> int\n\
Return the lowest index in S where substring sub is found,\n\
such that sub is contained within s[start,end]. Optional\n\
arguments start and end are interpreted as in slice notation.\n\
Return -1 on failure.");
unicode_find(PyUnicodeObject *self, PyObject *args)
if (!PyArg_ParseTuple(args, "O|O&O&:find", &substring,
result = PyInt_FromLong(findstring(self, substring, start, end, 1));
unicode_getitem(PyUnicodeObject *self, int index)
if (index < 0 || index >= self->length) {
PyErr_SetString(PyExc_IndexError, "string index out of range");
return (PyObject*) PyUnicode_FromUnicode(&self->str[index], 1);
static long
unicode_hash(PyUnicodeObject *self)
/* Since Unicode objects compare equal to their ASCII string
counterparts, they should use the individual character values
as basis for their hash value. This is needed to assure that
strings and Unicode objects behave in the same way as
dictionary keys. */
register int len;
register Py_UNICODE *p;
register long x;
if (self->hash != -1)
return self->hash;
len = PyUnicode_GET_SIZE(self);
p = PyUnicode_AS_UNICODE(self);
x = *p << 7;
while (--len >= 0)
x = (1000003*x) ^ *p++;
x ^= PyUnicode_GET_SIZE(self);
if (x == -1)
x = -2;
self->hash = x;
PyDoc_STRVAR(index__doc__,
"S.index(sub [,start [,end]]) -> int\n\
Like S.find() but raise ValueError when the substring is not found.");
unicode_index(PyUnicodeObject *self, PyObject *args)
if (!PyArg_ParseTuple(args, "O|O&O&:index", &substring,
result = findstring(self, substring, start, end, 1);
if (result < 0) {
PyErr_SetString(PyExc_ValueError, "substring not found");
return PyInt_FromLong(result);
PyDoc_STRVAR(islower__doc__,
"S.islower() -> bool\n\
Return True if all cased characters in S are lowercase and there is\n\
at least one cased character in S, False otherwise.");
unicode_islower(PyUnicodeObject *self)
register const Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
register const Py_UNICODE *e;
int cased;
if (PyUnicode_GET_SIZE(self) == 1)
return PyBool_FromLong(Py_UNICODE_ISLOWER(*p));
/* Special case for empty strings */
if (PyString_GET_SIZE(self) == 0)
return PyBool_FromLong(0);
cased = 0;
if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
else if (!cased && Py_UNICODE_ISLOWER(ch))
cased = 1;
return PyBool_FromLong(cased);
PyDoc_STRVAR(isupper__doc__,
"S.isupper() -> bool\n\
Return True if all cased characters in S are uppercase and there is\n\
unicode_isupper(PyUnicodeObject *self)
return PyBool_FromLong(Py_UNICODE_ISUPPER(*p) != 0);
if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
else if (!cased && Py_UNICODE_ISUPPER(ch))
PyDoc_STRVAR(istitle__doc__,
"S.istitle() -> bool\n\
Return True if S is a titlecased string and there is at least one\n\
character in S, i.e. upper- and titlecase characters may only\n\
follow uncased characters and lowercase characters only cased ones.\n\
Return False otherwise.");
unicode_istitle(PyUnicodeObject *self)
int cased, previous_is_cased;
return PyBool_FromLong((Py_UNICODE_ISTITLE(*p) != 0) ||
(Py_UNICODE_ISUPPER(*p) != 0));
if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
else if (Py_UNICODE_ISLOWER(ch)) {
if (!previous_is_cased)
PyDoc_STRVAR(isspace__doc__,
"S.isspace() -> bool\n\
Return True if all characters in S are whitespace\n\
and there is at least one character in S, False otherwise.");
unicode_isspace(PyUnicodeObject *self)
if (PyUnicode_GET_SIZE(self) == 1 &&
Py_UNICODE_ISSPACE(*p))
return PyBool_FromLong(1);
if (!Py_UNICODE_ISSPACE(*p))
PyDoc_STRVAR(isalpha__doc__,
"S.isalpha() -> bool\n\
Return True if all characters in S are alphabetic\n\
unicode_isalpha(PyUnicodeObject *self)
Py_UNICODE_ISALPHA(*p))
if (!Py_UNICODE_ISALPHA(*p))
PyDoc_STRVAR(isalnum__doc__,
"S.isalnum() -> bool\n\
Return True if all characters in S are alphanumeric\n\
unicode_isalnum(PyUnicodeObject *self)
Py_UNICODE_ISALNUM(*p))
if (!Py_UNICODE_ISALNUM(*p))
PyDoc_STRVAR(isdecimal__doc__,
"S.isdecimal() -> bool\n\
Return True if there are only decimal characters in S,\n\
False otherwise.");
unicode_isdecimal(PyUnicodeObject *self)
Py_UNICODE_ISDECIMAL(*p))
if (!Py_UNICODE_ISDECIMAL(*p))
PyDoc_STRVAR(isdigit__doc__,
"S.isdigit() -> bool\n\
Return True if all characters in S are digits\n\
unicode_isdigit(PyUnicodeObject *self)
Py_UNICODE_ISDIGIT(*p))
if (!Py_UNICODE_ISDIGIT(*p))
PyDoc_STRVAR(isnumeric__doc__,
"S.isnumeric() -> bool\n\
Return True if there are only numeric characters in S,\n\
unicode_isnumeric(PyUnicodeObject *self)
Py_UNICODE_ISNUMERIC(*p))
if (!Py_UNICODE_ISNUMERIC(*p))
PyDoc_STRVAR(join__doc__,
"S.join(sequence) -> unicode\n\
Return a string which is the concatenation of the strings in the\n\
sequence. The separator between elements is S.");
unicode_join(PyObject *self, PyObject *data)
return PyUnicode_Join(self, data);
unicode_length(PyUnicodeObject *self)
return self->length;
PyDoc_STRVAR(ljust__doc__,
"S.ljust(width[, fillchar]) -> int\n\
Return S left justified in a Unicode string of length width. Padding is\n\
done using the specified fill character (default is a space).");
unicode_ljust(PyUnicodeObject *self, PyObject *args)
if (!PyArg_ParseTuple(args, "i|O&:ljust", &width, convert_uc, &fillchar))
return (PyObject*) pad(self, 0, width - self->length, fillchar);
PyDoc_STRVAR(lower__doc__,
"S.lower() -> unicode\n\
Return a copy of the string S converted to lowercase.");
unicode_lower(PyUnicodeObject *self)
return fixup(self, fixlower);
#define LEFTSTRIP 0
#define RIGHTSTRIP 1
#define BOTHSTRIP 2
/* Arrays indexed by above */
static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
#define STRIPNAME(i) (stripformat[i]+3)
static const Py_UNICODE *
unicode_memchr(const Py_UNICODE *s, Py_UNICODE c, size_t n)
size_t i;
for (i = 0; i < n; ++i)
if (s[i] == c)
return s+i;
/* externally visible for str.strip(unicode) */
_PyUnicode_XStrip(PyUnicodeObject *self, int striptype, PyObject *sepobj)
Py_UNICODE *s = PyUnicode_AS_UNICODE(self);
int len = PyUnicode_GET_SIZE(self);
Py_UNICODE *sep = PyUnicode_AS_UNICODE(sepobj);
int seplen = PyUnicode_GET_SIZE(sepobj);
if (striptype != RIGHTSTRIP) {
while (i < len && unicode_memchr(sep, s[i], seplen)) {
j = len;
if (striptype != LEFTSTRIP) {
do {
j--;
} while (j >= i && unicode_memchr(sep, s[j], seplen));
if (i == 0 && j == len && PyUnicode_CheckExact(self)) {
return (PyObject*)self;
return PyUnicode_FromUnicode(s+i, j-i);
do_strip(PyUnicodeObject *self, int striptype)
int len = PyUnicode_GET_SIZE(self), i, j;
while (i < len && Py_UNICODE_ISSPACE(s[i])) {
} while (j >= i && Py_UNICODE_ISSPACE(s[j]));
do_argstrip(PyUnicodeObject *self, int striptype, PyObject *args)
PyObject *sep = NULL;
if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
if (sep != NULL && sep != Py_None) {
if (PyUnicode_Check(sep))
return _PyUnicode_XStrip(self, striptype, sep);
else if (PyString_Check(sep)) {
sep = PyUnicode_FromObject(sep);
if (sep==NULL)
res = _PyUnicode_XStrip(self, striptype, sep);
Py_DECREF(sep);
"%s arg must be None, unicode or str",
STRIPNAME(striptype));
return do_strip(self, striptype);
PyDoc_STRVAR(strip__doc__,
"S.strip([chars]) -> unicode\n\
Return a copy of the string S with leading and trailing\n\
whitespace removed.\n\
If chars is given and not None, remove characters in chars instead.\n\
If chars is a str, it will be converted to unicode before stripping");
unicode_strip(PyUnicodeObject *self, PyObject *args)
if (PyTuple_GET_SIZE(args) == 0)
return do_strip(self, BOTHSTRIP); /* Common case */
return do_argstrip(self, BOTHSTRIP, args);
PyDoc_STRVAR(lstrip__doc__,
"S.lstrip([chars]) -> unicode\n\
Return a copy of the string S with leading whitespace removed.\n\
unicode_lstrip(PyUnicodeObject *self, PyObject *args)
return do_strip(self, LEFTSTRIP); /* Common case */
return do_argstrip(self, LEFTSTRIP, args);
PyDoc_STRVAR(rstrip__doc__,
"S.rstrip([chars]) -> unicode\n\
Return a copy of the string S with trailing whitespace removed.\n\
unicode_rstrip(PyUnicodeObject *self, PyObject *args)
return do_strip(self, RIGHTSTRIP); /* Common case */
return do_argstrip(self, RIGHTSTRIP, args);
unicode_repeat(PyUnicodeObject *str, int len)
int nchars;
size_t nbytes;
if (len < 0)
len = 0;
if (len == 1 && PyUnicode_CheckExact(str)) {
/* no repeat, return original string */
Py_INCREF(str);
return (PyObject*) str;
/* ensure # of chars needed doesn't overflow int and # of bytes
* needed doesn't overflow size_t
nchars = len * str->length;
if (len && nchars / len != str->length) {
PyErr_SetString(PyExc_OverflowError,
"repeated string is too long");
nbytes = (nchars + 1) * sizeof(Py_UNICODE);
if (nbytes / sizeof(Py_UNICODE) != (size_t)(nchars + 1)) {
u = _PyUnicode_New(nchars);
Py_UNICODE_COPY(p, str->str, str->length);
p += str->length;
PyObject *PyUnicode_Replace(PyObject *obj,
PyObject *subobj,
PyObject *replobj,
PyObject *self;
PyObject *str1;
PyObject *str2;
self = PyUnicode_FromObject(obj);
if (self == NULL)
str1 = PyUnicode_FromObject(subobj);
if (str1 == NULL) {
Py_DECREF(self);
str2 = PyUnicode_FromObject(replobj);
if (str2 == NULL) {
Py_DECREF(str1);
result = replace((PyUnicodeObject *)self,
(PyUnicodeObject *)str1,
(PyUnicodeObject *)str2,
maxcount);
Py_DECREF(str2);
PyDoc_STRVAR(replace__doc__,
"S.replace (old, new[, maxsplit]) -> unicode\n\
Return a copy of S with all occurrences of substring\n\
old replaced by new. If the optional argument maxsplit is\n\
given, only the first maxsplit occurrences are replaced.");
unicode_replace(PyUnicodeObject *self, PyObject *args)
PyUnicodeObject *str1;
PyUnicodeObject *str2;
int maxcount = -1;
if (!PyArg_ParseTuple(args, "OO|i:replace", &str1, &str2, &maxcount))
str1 = (PyUnicodeObject *)PyUnicode_FromObject((PyObject *)str1);
if (str1 == NULL)
str2 = (PyUnicodeObject *)PyUnicode_FromObject((PyObject *)str2);
result = replace(self, str1, str2, maxcount);
PyObject *unicode_repr(PyObject *unicode)
return unicodeescape_string(PyUnicode_AS_UNICODE(unicode),
1);
PyDoc_STRVAR(rfind__doc__,
"S.rfind(sub [,start [,end]]) -> int\n\
Return the highest index in S where substring sub is found,\n\
unicode_rfind(PyUnicodeObject *self, PyObject *args)
if (!PyArg_ParseTuple(args, "O|O&O&:rfind", &substring,
result = PyInt_FromLong(findstring(self, substring, start, end, -1));
PyDoc_STRVAR(rindex__doc__,
"S.rindex(sub [,start [,end]]) -> int\n\
Like S.rfind() but raise ValueError when the substring is not found.");
unicode_rindex(PyUnicodeObject *self, PyObject *args)
if (!PyArg_ParseTuple(args, "O|O&O&:rindex", &substring,
result = findstring(self, substring, start, end, -1);
PyDoc_STRVAR(rjust__doc__,
"S.rjust(width[, fillchar]) -> unicode\n\
Return S right justified in a Unicode string of length width. Padding is\n\
unicode_rjust(PyUnicodeObject *self, PyObject *args)
if (!PyArg_ParseTuple(args, "i|O&:rjust", &width, convert_uc, &fillchar))
return (PyObject*) pad(self, width - self->length, 0, fillchar);
unicode_slice(PyUnicodeObject *self, int start, int end)
/* standard clamping */
if (start == 0 && end == self->length && PyUnicode_CheckExact(self)) {
/* full slice, return original string */
if (start > end)
start = end;
/* copy slice */
return (PyObject*) PyUnicode_FromUnicode(self->str + start,
end - start);
PyObject *PyUnicode_Split(PyObject *s,
PyObject *sep,
int maxsplit)
s = PyUnicode_FromObject(s);
if (s == NULL)
if (sep != NULL) {
if (sep == NULL) {
Py_DECREF(s);
result = split((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
Py_XDECREF(sep);
PyDoc_STRVAR(split__doc__,
"S.split([sep [,maxsplit]]) -> list of strings\n\
Return a list of the words in S, using sep as the\n\
delimiter string. If maxsplit is given, at most maxsplit\n\
splits are done. If sep is not specified, any whitespace string\n\
is a separator.");
unicode_split(PyUnicodeObject *self, PyObject *args)
PyObject *substring = Py_None;
if (!PyArg_ParseTuple(args, "|Oi:split", &substring, &maxcount))
if (substring == Py_None)
return split(self, NULL, maxcount);
else if (PyUnicode_Check(substring))
return split(self, (PyUnicodeObject *)substring, maxcount);
return PyUnicode_Split((PyObject *)self, substring, maxcount);
PyObject *PyUnicode_RSplit(PyObject *s,
result = rsplit((PyUnicodeObject *)s, (PyUnicodeObject *)sep, maxsplit);
PyDoc_STRVAR(rsplit__doc__,
"S.rsplit([sep [,maxsplit]]) -> list of strings\n\
delimiter string, starting at the end of the string and\n\
working to the front. If maxsplit is given, at most maxsplit\n\
unicode_rsplit(PyUnicodeObject *self, PyObject *args)
if (!PyArg_ParseTuple(args, "|Oi:rsplit", &substring, &maxcount))
return rsplit(self, NULL, maxcount);
return rsplit(self, (PyUnicodeObject *)substring, maxcount);
return PyUnicode_RSplit((PyObject *)self, substring, maxcount);
PyDoc_STRVAR(splitlines__doc__,
"S.splitlines([keepends]]) -> list of strings\n\
Return a list of the lines in S, breaking at line boundaries.\n\
Line breaks are not included in the resulting list unless keepends\n\
is given and true.");
unicode_splitlines(PyUnicodeObject *self, PyObject *args)
int keepends = 0;
if (!PyArg_ParseTuple(args, "|i:splitlines", &keepends))
return PyUnicode_Splitlines((PyObject *)self, keepends);
PyObject *unicode_str(PyUnicodeObject *self)
return PyUnicode_AsEncodedString((PyObject *)self, NULL, NULL);
PyDoc_STRVAR(swapcase__doc__,
"S.swapcase() -> unicode\n\
Return a copy of S with uppercase characters converted to lowercase\n\
and vice versa.");
unicode_swapcase(PyUnicodeObject *self)
return fixup(self, fixswapcase);
PyDoc_STRVAR(translate__doc__,
"S.translate(table) -> unicode\n\
Return a copy of the string S, where all characters have been mapped\n\
through the given translation table, which must be a mapping of\n\
Unicode ordinals to Unicode ordinals, Unicode strings or None.\n\
Unmapped characters are left untouched. Characters mapped to None\n\
are deleted.");
unicode_translate(PyUnicodeObject *self, PyObject *table)
return PyUnicode_TranslateCharmap(self->str,
self->length,
table,
"ignore");
PyDoc_STRVAR(upper__doc__,
"S.upper() -> unicode\n\
Return a copy of S converted to uppercase.");
unicode_upper(PyUnicodeObject *self)
return fixup(self, fixupper);
PyDoc_STRVAR(zfill__doc__,
"S.zfill(width) -> unicode\n\
Pad a numeric string x with zeros on the left, to fill a field\n\
of the specified width. The string x is never truncated.");
unicode_zfill(PyUnicodeObject *self, PyObject *args)
int fill;
if (!PyArg_ParseTuple(args, "i:zfill", &width))
if (self->length >= width) {
return PyUnicode_FromUnicode(
PyUnicode_AS_UNICODE(self),
PyUnicode_GET_SIZE(self)
fill = width - self->length;
u = pad(self, fill, 0, '0');
if (u->str[fill] == '+' || u->str[fill] == '-') {
/* move sign to beginning of string */
u->str[0] = u->str[fill];
u->str[fill] = '0';
unicode_freelistsize(PyUnicodeObject *self)
return PyInt_FromLong(unicode_freelist_size);
PyDoc_STRVAR(startswith__doc__,
"S.startswith(prefix[, start[, end]]) -> bool\n\
Return True if S starts with the specified prefix, False otherwise.\n\
With optional start, test S beginning at that position.\n\
With optional end, stop comparing S at that position.");
unicode_startswith(PyUnicodeObject *self,
PyObject *args)
if (!PyArg_ParseTuple(args, "O|O&O&:startswith", &substring,
result = PyBool_FromLong(tailmatch(self, substring, start, end, -1));
PyDoc_STRVAR(endswith__doc__,
"S.endswith(suffix[, start[, end]]) -> bool\n\
Return True if S ends with the specified suffix, False otherwise.\n\
unicode_endswith(PyUnicodeObject *self,
if (!PyArg_ParseTuple(args, "O|O&O&:endswith", &substring,
result = PyBool_FromLong(tailmatch(self, substring, start, end, +1));
unicode_getnewargs(PyUnicodeObject *v)
return Py_BuildValue("(u#)", v->str, v->length);
static PyMethodDef unicode_methods[] = {
/* Order is according to common usage: often used methods should
appear first, since lookup is done sequentially. */
{"encode", (PyCFunction) unicode_encode, METH_VARARGS, encode__doc__},
{"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
{"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
{"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
{"join", (PyCFunction) unicode_join, METH_O, join__doc__},
{"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
{"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
{"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
{"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
{"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
{"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
{"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
{"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
{"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
{"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
{"decode", (PyCFunction) unicode_decode, METH_VARARGS, decode__doc__},
/* {"maketrans", (PyCFunction) unicode_maketrans, METH_VARARGS, maketrans__doc__}, */
{"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
{"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
{"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
{"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
{"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS, splitlines__doc__},
{"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
{"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
{"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
{"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
{"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
{"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
{"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
{"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
{"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
{"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
{"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
{"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
{"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
{"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
{"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
{"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
{"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
/* This one is just used for debugging the implementation. */
{"freelistsize", (PyCFunction) unicode_freelistsize, METH_NOARGS},
{"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
{NULL, NULL}
unicode_mod(PyObject *v, PyObject *w)
if (!PyUnicode_Check(v)) {
Py_INCREF(Py_NotImplemented);
return Py_NotImplemented;
return PyUnicode_Format(v, w);
static PyNumberMethods unicode_as_number = {
0, /*nb_add*/
0, /*nb_subtract*/
0, /*nb_multiply*/
0, /*nb_divide*/
unicode_mod, /*nb_remainder*/
static PySequenceMethods unicode_as_sequence = {
(inquiry) unicode_length, /* sq_length */
(binaryfunc) PyUnicode_Concat, /* sq_concat */
(intargfunc) unicode_repeat, /* sq_repeat */
(intargfunc) unicode_getitem, /* sq_item */
(intintargfunc) unicode_slice, /* sq_slice */
0, /* sq_ass_item */
0, /* sq_ass_slice */
(objobjproc)PyUnicode_Contains, /*sq_contains*/
unicode_subscript(PyUnicodeObject* self, PyObject* item)
if (PyInt_Check(item)) {
long i = PyInt_AS_LONG(item);
if (i < 0)
i += PyString_GET_SIZE(self);
return unicode_getitem(self, i);
} else if (PyLong_Check(item)) {
long i = PyLong_AsLong(item);
if (i == -1 && PyErr_Occurred())
} else if (PySlice_Check(item)) {
int start, stop, step, slicelength, cur, i;
Py_UNICODE* source_buf;
Py_UNICODE* result_buf;
PyObject* result;
if (PySlice_GetIndicesEx((PySliceObject*)item, PyString_GET_SIZE(self),
&start, &stop, &step, &slicelength) < 0) {
if (slicelength <= 0) {
return PyUnicode_FromUnicode(NULL, 0);
source_buf = PyUnicode_AS_UNICODE((PyObject*)self);
result_buf = PyMem_MALLOC(slicelength*sizeof(Py_UNICODE));
for (cur = start, i = 0; i < slicelength; cur += step, i++) {
result_buf[i] = source_buf[cur];
result = PyUnicode_FromUnicode(result_buf, slicelength);
PyMem_FREE(result_buf);
PyErr_SetString(PyExc_TypeError, "string indices must be integers");
static PyMappingMethods unicode_as_mapping = {
(inquiry)unicode_length, /* mp_length */
(binaryfunc)unicode_subscript, /* mp_subscript */
(objobjargproc)0, /* mp_ass_subscript */
unicode_buffer_getreadbuf(PyUnicodeObject *self,
int index,
const void **ptr)
if (index != 0) {
"accessing non-existent unicode segment");
*ptr = (void *) self->str;
return PyUnicode_GET_DATA_SIZE(self);
unicode_buffer_getwritebuf(PyUnicodeObject *self, int index,
"cannot use unicode as modifiable buffer");
unicode_buffer_getsegcount(PyUnicodeObject *self,
int *lenp)
if (lenp)
*lenp = PyUnicode_GET_DATA_SIZE(self);
unicode_buffer_getcharbuf(PyUnicodeObject *self,
str = _PyUnicode_AsDefaultEncodedString((PyObject *)self, NULL);
*ptr = (void *) PyString_AS_STRING(str);
return PyString_GET_SIZE(str);
/* Helpers for PyUnicode_Format() */
getnextarg(PyObject *args, int arglen, int *p_argidx)
int argidx = *p_argidx;
if (argidx < arglen) {
(*p_argidx)++;
if (arglen < 0)
return args;
return PyTuple_GetItem(args, argidx);
"not enough arguments for format string");
#define F_LJUST (1<<0)
#define F_SIGN (1<<1)
#define F_BLANK (1<<2)
#define F_ALT (1<<3)
#define F_ZERO (1<<4)
int usprintf(register Py_UNICODE *buffer, char *format, ...)
va_list va;
char *charbuffer;
va_start(va, format);
/* First, format the string as char array, then expand to Py_UNICODE
array. */
charbuffer = (char *)buffer;
len = vsprintf(charbuffer, format, va);
for (i = len - 1; i >= 0; i--)
buffer[i] = (Py_UNICODE) charbuffer[i];
va_end(va);
return len;
/* XXX To save some code duplication, formatfloat/long/int could have been
shared with stringobject.c, converting from 8-bit to Unicode after the
formatting is done. */
formatfloat(Py_UNICODE *buf,
size_t buflen,
int flags,
int prec,
int type,
PyObject *v)
/* fmt = '%#.' + `prec` + `type`
worst case length = 3 + 10 (len of INT_MAX) + 1 = 14 (use 20)*/
char fmt[20];
double x;
x = PyFloat_AsDouble(v);
if (x == -1.0 && PyErr_Occurred())
if (prec < 0)
prec = 6;
if (type == 'f' && (fabs(x) / 1e25) >= 1e25)
type = 'g';
/* Worst case length calc to ensure no buffer overrun:
'g' formats:
fmt = %#.<prec>g
buf = '-' + [0-9]*prec + '.' + 'e+' + (longest exp
for any double rep.)
len = 1 + prec + 1 + 2 + 5 = 9 + prec
'f' formats:
buf = '-' + [0-9]*x + '.' + [0-9]*prec (with x < 50)
len = 1 + 50 + 1 + prec = 52 + prec
If prec=0 the effective precision is 1 (the leading digit is
always given), therefore increase the length by one.
if ((type == 'g' && buflen <= (size_t)10 + (size_t)prec) ||
(type == 'f' && buflen <= (size_t)53 + (size_t)prec)) {
"formatted float is too long (precision too large?)");
PyOS_snprintf(fmt, sizeof(fmt), "%%%s.%d%c",
(flags&F_ALT) ? "#" : "",
prec, type);
return usprintf(buf, fmt, x);
formatlong(PyObject *val, int flags, int prec, int type)
char *buf;
int i, len;
PyObject *str; /* temporary string object. */
PyUnicodeObject *result;
str = _PyString_FormatLong(val, flags, prec, type, &buf, &len);
if (!str)
result = _PyUnicode_New(len);
for (i = 0; i < len; i++)
result->str[i] = buf[i];
result->str[len] = 0;
return (PyObject*)result;
formatint(Py_UNICODE *buf,
/* fmt = '%#.' + `prec` + 'l' + `type`
* worst case length = 3 + 19 (worst len of INT_MAX on 64-bit machine)
* + 1 + 1
* = 24
char fmt[64]; /* plenty big enough! */
char *sign;
long x;
x = PyInt_AsLong(v);
if (x == -1 && PyErr_Occurred())
if (x < 0 && type == 'u') {
type = 'd';
if (x < 0 && (type == 'x' || type == 'X' || type == 'o'))
sign = "-";
sign = "";
prec = 1;
/* buf = '+'/'-'/'' + '0'/'0x'/'' + '[0-9]'*max(prec, len(x in octal))
* worst case buf = '-0x' + [0-9]*prec, where prec >= 11
if (buflen <= 14 || buflen <= (size_t)3 + (size_t)prec) {
"formatted integer is too long (precision too large?)");
if ((flags & F_ALT) &&
(type == 'x' || type == 'X')) {
/* When converting under %#x or %#X, there are a number
* of issues that cause pain:
* - when 0 is being converted, the C standard leaves off
* the '0x' or '0X', which is inconsistent with other
* %#x/%#X conversions and inconsistent with Python's
* hex() function
* - there are platforms that violate the standard and
* convert 0 with the '0x' or '0X'
* (Metrowerks, Compaq Tru64)
* - there are platforms that give '0x' when converting
* under %#X, but convert 0 in accordance with the
* standard (OS/2 EMX)
*
* We can achieve the desired consistency by inserting our
* own '0x' or '0X' prefix, and substituting %x/%X in place
* of %#x/%#X.
* Note that this is the same approach as used in
* formatint() in stringobject.c
PyOS_snprintf(fmt, sizeof(fmt), "%s0%c%%.%dl%c",
sign, type, prec, type);
PyOS_snprintf(fmt, sizeof(fmt), "%s%%%s.%dl%c",
sign, (flags&F_ALT) ? "#" : "",
if (sign[0])
return usprintf(buf, fmt, -x);
formatchar(Py_UNICODE *buf,
/* presume that the buffer is at least 2 characters long */
if (PyUnicode_Check(v)) {
if (PyUnicode_GET_SIZE(v) != 1)
buf[0] = PyUnicode_AS_UNICODE(v)[0];
else if (PyString_Check(v)) {
if (PyString_GET_SIZE(v) != 1)
buf[0] = (Py_UNICODE)PyString_AS_STRING(v)[0];
/* Integer input truncated to a character */
if (x < 0 || x > 0x10ffff) {
"%c arg not in range(0x110000) "
if (x < 0 || x > 0xffff) {
"%c arg not in range(0x10000) "
buf[0] = (Py_UNICODE) x;
buf[1] = '\0';
"%c requires int or char");
/* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...)
FORMATBUFLEN is the length of the buffer in which the floats, ints, &
chars are formatted. XXX This is a magic number. Each formatting
routine does bounds checking to ensure no overflow, but a better
solution may be to malloc a buffer of appropriate size for each
format. For now, the current solution is sufficient.
#define FORMATBUFLEN (size_t)120
PyObject *PyUnicode_Format(PyObject *format,
Py_UNICODE *fmt, *res;
int fmtcnt, rescnt, reslen, arglen, argidx;
int args_owned = 0;
PyUnicodeObject *result = NULL;
PyObject *dict = NULL;
PyObject *uformat;
if (format == NULL || args == NULL) {
uformat = PyUnicode_FromObject(format);
if (uformat == NULL)
fmt = PyUnicode_AS_UNICODE(uformat);
fmtcnt = PyUnicode_GET_SIZE(uformat);
reslen = rescnt = fmtcnt + 100;
result = _PyUnicode_New(reslen);
if (result == NULL)
res = PyUnicode_AS_UNICODE(result);
if (PyTuple_Check(args)) {
arglen = PyTuple_Size(args);
argidx = 0;
arglen = -1;
argidx = -2;
if (args->ob_type->tp_as_mapping && !PyTuple_Check(args) &&
!PyObject_TypeCheck(args, &PyBaseString_Type))
dict = args;
while (--fmtcnt >= 0) {
if (*fmt != '%') {
if (--rescnt < 0) {
rescnt = fmtcnt + 100;
reslen += rescnt;
if (_PyUnicode_Resize(&result, reslen) < 0)
res = PyUnicode_AS_UNICODE(result) + reslen - rescnt;
--rescnt;
*res++ = *fmt++;
/* Got a format specifier */
int flags = 0;
int width = -1;
int prec = -1;
Py_UNICODE c = '\0';
Py_UNICODE fill;
PyObject *v = NULL;
PyObject *temp = NULL;
Py_UNICODE *pbuf;
Py_UNICODE sign;
Py_UNICODE formatbuf[FORMATBUFLEN]; /* For format{float,int,char}() */
fmt++;
if (*fmt == '(') {
Py_UNICODE *keystart;
int keylen;
PyObject *key;
int pcount = 1;
if (dict == NULL) {
"format requires a mapping");
++fmt;
--fmtcnt;
keystart = fmt;
/* Skip over balanced parentheses */
while (pcount > 0 && --fmtcnt >= 0) {
if (*fmt == ')')
--pcount;
else if (*fmt == '(')
++pcount;
keylen = fmt - keystart - 1;
if (fmtcnt < 0 || pcount > 0) {
"incomplete format key");
/* keys are converted to strings using UTF-8 and
then looked up since Python uses strings to hold
variables names etc. in its namespaces and we
wouldn't want to break common idioms. */
key = PyUnicode_EncodeUTF8(keystart,
keylen,
key = PyUnicode_FromUnicode(keystart, keylen);
if (key == NULL)
if (args_owned) {
Py_DECREF(args);
args_owned = 0;
args = PyObject_GetItem(dict, key);
Py_DECREF(key);
if (args == NULL) {
args_owned = 1;
switch (c = *fmt++) {
case '-': flags |= F_LJUST; continue;
case '+': flags |= F_SIGN; continue;
case ' ': flags |= F_BLANK; continue;
case '#': flags |= F_ALT; continue;
case '0': flags |= F_ZERO; continue;
if (c == '*') {
v = getnextarg(args, arglen, &argidx);
if (!PyInt_Check(v)) {
"* wants int");
width = PyInt_AsLong(v);
if (width < 0) {
flags |= F_LJUST;
width = -width;
if (--fmtcnt >= 0)
c = *fmt++;
else if (c >= '0' && c <= '9') {
width = c - '0';
if (c < '0' || c > '9')
if ((width*10) / 10 != width) {
"width too big");
width = width*10 + (c - '0');
if (c == '.') {
prec = 0;
prec = PyInt_AsLong(v);
prec = c - '0';
c = Py_CHARMASK(*fmt++);
if ((prec*10) / 10 != prec) {
"prec too big");
prec = prec*10 + (c - '0');
} /* prec */
if (fmtcnt >= 0) {
if (c == 'h' || c == 'l' || c == 'L') {
if (fmtcnt < 0) {
"incomplete format");
if (c != '%') {
sign = 0;
fill = ' ';
switch (c) {
case '%':
pbuf = formatbuf;
/* presume that buffer length is at least 1 */
pbuf[0] = '%';
len = 1;
case 's':
case 'r':
if (PyUnicode_Check(v) && c == 's') {
temp = v;
Py_INCREF(temp);
PyObject *unicode;
if (c == 's')
temp = PyObject_Unicode(v);
temp = PyObject_Repr(v);
if (temp == NULL)
if (PyUnicode_Check(temp))
/* nothing to do */;
else if (PyString_Check(temp)) {
/* convert to string to Unicode */
unicode = PyUnicode_Decode(PyString_AS_STRING(temp),
PyString_GET_SIZE(temp),
"strict");
Py_DECREF(temp);
temp = unicode;
"%s argument has non-string str()");
pbuf = PyUnicode_AS_UNICODE(temp);
len = PyUnicode_GET_SIZE(temp);
if (prec >= 0 && len > prec)
len = prec;
case 'i':
case 'd':
case 'o':
case 'X':
if (c == 'i')
c = 'd';
if (PyLong_Check(v)) {
temp = formatlong(v, flags, prec, c);
if (!temp)
sign = 1;
len = formatint(pbuf, sizeof(formatbuf)/sizeof(Py_UNICODE),
flags, prec, c, v);
if (flags & F_ZERO)
fill = '0';
case 'e':
case 'E':
case 'f':
case 'F':
case 'g':
case 'G':
if (c == 'F')
c = 'f';
len = formatfloat(pbuf, sizeof(formatbuf)/sizeof(Py_UNICODE),
case 'c':
len = formatchar(pbuf, sizeof(formatbuf)/sizeof(Py_UNICODE), v);
PyErr_Format(PyExc_ValueError,
"unsupported format character '%c' (0x%x) "
"at index %i",
(31<=c && c<=126) ? (char)c : '?',
(int)c,
(int)(fmt -1 - PyUnicode_AS_UNICODE(uformat)));
if (sign) {
if (*pbuf == '-' || *pbuf == '+') {
sign = *pbuf++;
len--;
else if (flags & F_SIGN)
sign = '+';
else if (flags & F_BLANK)
sign = ' ';
if (width < len)
width = len;
if (rescnt - (sign != 0) < width) {
reslen -= rescnt;
rescnt = width + fmtcnt + 100;
if (reslen < 0) {
Py_DECREF(result);
res = PyUnicode_AS_UNICODE(result)
+ reslen - rescnt;
if (fill != ' ')
*res++ = sign;
rescnt--;
if (width > len)
width--;
if ((flags & F_ALT) && (c == 'x' || c == 'X')) {
assert(pbuf[0] == '0');
assert(pbuf[1] == c);
if (fill != ' ') {
*res++ = *pbuf++;
rescnt -= 2;
width -= 2;
if (width < 0)
width = 0;
len -= 2;
if (width > len && !(flags & F_LJUST)) {
*res++ = fill;
} while (--width > len);
if (fill == ' ') {
if (sign)
Py_UNICODE_COPY(res, pbuf, len);
res += len;
rescnt -= len;
while (--width >= len) {
*res++ = ' ';
if (dict && (argidx < arglen) && c != '%') {
"not all arguments converted during string formatting");
Py_XDECREF(temp);
} /* '%' */
} /* until end */
if (argidx < arglen && !dict) {
Py_DECREF(uformat);
if (_PyUnicode_Resize(&result, reslen - rescnt) < 0)
return (PyObject *)result;
Py_XDECREF(result);
static PyBufferProcs unicode_as_buffer = {
(getreadbufferproc) unicode_buffer_getreadbuf,
(getwritebufferproc) unicode_buffer_getwritebuf,
(getsegcountproc) unicode_buffer_getsegcount,
(getcharbufferproc) unicode_buffer_getcharbuf,
unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
static char *kwlist[] = {"string", "encoding", "errors", 0};
if (type != &PyUnicode_Type)
return unicode_subtype_new(type, args, kwds);
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:unicode",
kwlist, &x, &encoding, &errors))
if (x == NULL)
return (PyObject *)_PyUnicode_New(0);
if (encoding == NULL && errors == NULL)
return PyObject_Unicode(x);
return PyUnicode_FromEncodedObject(x, encoding, errors);
unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
PyUnicodeObject *tmp, *pnew;
assert(PyType_IsSubtype(type, &PyUnicode_Type));
tmp = (PyUnicodeObject *)unicode_new(&PyUnicode_Type, args, kwds);
if (tmp == NULL)
assert(PyUnicode_Check(tmp));
pnew = (PyUnicodeObject *) type->tp_alloc(type, n = tmp->length);
if (pnew == NULL) {
Py_DECREF(tmp);
pnew->str = PyMem_NEW(Py_UNICODE, n+1);
if (pnew->str == NULL) {
_Py_ForgetReference((PyObject *)pnew);
PyObject_Del(pnew);
Py_UNICODE_COPY(pnew->str, tmp->str, n+1);
pnew->length = n;
pnew->hash = tmp->hash;
return (PyObject *)pnew;
PyDoc_STRVAR(unicode_doc,
"unicode(string [, encoding[, errors]]) -> object\n\
Create a new Unicode object from the given encoded string.\n\
encoding defaults to the current default string encoding.\n\
errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
PyTypeObject PyUnicode_Type = {
PyObject_HEAD_INIT(&PyType_Type)
0, /* ob_size */
"unicode", /* tp_name */
sizeof(PyUnicodeObject), /* tp_size */
0, /* tp_itemsize */
/* Slots */
(destructor)unicode_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
(cmpfunc) unicode_compare, /* tp_compare */
(reprfunc) unicode_repr, /* tp_repr */
&unicode_as_number, /* tp_as_number */
&unicode_as_sequence, /* tp_as_sequence */
&unicode_as_mapping, /* tp_as_mapping */
(hashfunc) unicode_hash, /* tp_hash*/
0, /* tp_call*/
(reprfunc) unicode_str, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
&unicode_as_buffer, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
Py_TPFLAGS_BASETYPE, /* tp_flags */
unicode_doc, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
unicode_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
&PyBaseString_Type, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
unicode_new, /* tp_new */
PyObject_Del, /* tp_free */
/* Initialize the Unicode implementation */
void _PyUnicode_Init(void)
/* Init the implementation */
unicode_freelist = NULL;
unicode_freelist_size = 0;
unicode_empty = _PyUnicode_New(0);
strcpy(unicode_default_encoding, "ascii");
for (i = 0; i < 256; i++)
unicode_latin1[i] = NULL;
if (PyType_Ready(&PyUnicode_Type) < 0)
Py_FatalError("Can't initialize 'unicode'");
/* Finalize the Unicode implementation */
void
_PyUnicode_Fini(void)
Py_XDECREF(unicode_empty);
unicode_empty = NULL;
for (i = 0; i < 256; i++) {
if (unicode_latin1[i]) {
Py_DECREF(unicode_latin1[i]);
for (u = unicode_freelist; u != NULL;) {
PyUnicodeObject *v = u;
u = *(PyUnicodeObject **)u;
if (v->str)
PyMem_DEL(v->str);
Py_XDECREF(v->defenc);
PyObject_Del(v);
Local variables:
c-basic-offset: 4
indent-tabs-mode: nil
End: