Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Include/internal/pycore_unicodeobject.h
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,9 @@ extern PyObject* _PyUnicode_FromASCII(
const char *buffer,
Py_ssize_t size);

/* Scan actual code points, including in a partially constructed string. */
extern Py_UCS4 _PyUnicode_ScanMaxChar(PyObject *unicode, Py_ssize_t start,
Py_ssize_t end);
/* Compute the maximum character of the substring unicode[start:end].
Return 127 for an empty string. */
extern Py_UCS4 _PyUnicode_FindMaxChar (
Expand Down
39 changes: 39 additions & 0 deletions Lib/test/test_str.py
Original file line number Diff line number Diff line change
Expand Up @@ -1946,6 +1946,10 @@ def test_utf8_decode_valid_sequences(self):
for seq, res in sequences:
self.assertEqual(seq.decode('utf-8'), res)

for repeats in (1, 8):
text = "àéîöαβγδ日本語です🙂abcd" * repeats
data = memoryview(b"." + text.encode())[1:]
self.assertEqual(str(data, "utf-8"), text)

def test_utf8_decode_invalid_sequences(self):
# continuation bytes in a sequence of 2, 3, or 4 bytes
Expand Down Expand Up @@ -1994,6 +1998,29 @@ def test_utf8_decode_invalid_sequences(self):
self.assertRaises(UnicodeDecodeError,
(b'\xF4'+cb+b'\xBF\xBF').decode, 'utf-8')

for char, bad in (("α", b"\xc0\x80"), ("日", b"\xe0\x80\x80"),
("日", b"\xed\xa0\x80")):
with self.subTest(bad=bad):
prefix = char.encode() * 17
with self.assertRaises(UnicodeDecodeError) as cm:
(prefix + bad + prefix).decode()
self.assertEqual((cm.exception.start, cm.exception.end),
(len(prefix), len(prefix) + 1))

@support.cpython_only
def test_utf8_decode_singleton_after_ignoring_errors(self):
data = b"\xf4\x90" * 64 + "é".encode()
self.assertIs(data.decode(errors="ignore"), chr(0xe9))

@support.cpython_only
@support.thread_unsafe("temporarily replaces the strict error handler")
def test_utf8_decode_with_replaced_strict_handler(self):
original = codecs.lookup_error("strict")
self.addCleanup(codecs.register_error, "strict", original)
codecs.register_error("strict", self.fail)
with self.assertRaises(UnicodeDecodeError):
b"\xff".decode("utf-8", "strict")

def test_issue127903(self):
# gh-127903: ``_copy_characters`` crashes on DEBUG builds when
# there is nothing to copy.
Expand Down Expand Up @@ -2121,6 +2148,13 @@ def test_invalid_start_byte(self):
self.assertCorrectUTF8Decoding(bytes([byte]), '\ufffd',
'invalid start byte')

# A partial character followed by stray bytes, then valid input.
data = b"\xe1\x80" + b"\xff\x80" * 64 + b"!"
self.assertEqual(data.decode(errors="replace"), "\ufffd" * 129 + "!")
self.assertEqual(data.decode(errors="ignore"), "!")
self.assertEqual(data.decode(errors="surrogateescape").encode(
errors="surrogateescape"), data)

def test_unexpected_end_of_data(self):
"""
Test that an 'unexpected end of data' error is raised when the string
Expand All @@ -2147,6 +2181,11 @@ def test_unexpected_end_of_data(self):
self.assertCorrectUTF8Decoding(bytes.fromhex(seq), '\ufffd',
'unexpected end of data')

prefix = "a" * 80
data = prefix.encode() + b"\xf0"
self.assertEqual(codecs.utf_8_decode(data), (prefix, len(prefix)))
self.assertEqual(data.decode(errors="replace"), prefix + "\ufffd")

def test_invalid_cb_for_2bytes_seq(self):
"""
Test that an 'invalid continuation byte' error is raised when the
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Speed up UTF-8 decoding for short non-ASCII strings and for long runs of
two-byte or three-byte characters.
200 changes: 137 additions & 63 deletions Objects/stringlib/codecs.h
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,81 @@

#include "pycore_bitutils.h" // _Py_bswap32()

/* Mask to quickly check whether a C 'size_t' contains a
non-ASCII, UTF8-encoded char. */
#if (SIZEOF_SIZE_T == 8)
# define ASCII_CHAR_MASK 0x8080808080808080ULL
#elif (SIZEOF_SIZE_T == 4)
# define ASCII_CHAR_MASK 0x80808080U
#else
# error C 'size_t' size should be either 4 or 8!
#endif
/* High bit of every byte in a 64-bit word. */
#define ASCII_CHAR_MASK UINT64_C(0x8080808080808080)

/* 10xxxxxx */
#define IS_CONTINUATION_BYTE(ch) ((ch) >= 0x80 && (ch) < 0xC0)

/* Shared by all character widths that instantiate this header. */
#ifndef STRINGLIB_UTF8_GROUPS_DEFINED
#define STRINGLIB_UTF8_GROUPS_DEFINED

#define UTF8_LANES16(x) (UINT64_C(0x0001000100010001) * (x))
#define UTF8_LANES24(x) (UINT64_C(0x0000000001000001) * (x))
#define UTF8_LANES32(x) (UINT64_C(0x0000000100000001) * (x))

#if PY_LITTLE_ENDIAN
/* Test complete UTF-8 groups in a little-endian integer. */
static inline int
utf8_four_pairs(uint64_t v, int latin1)
{
if (latin1) {
return (v & UTF8_LANES16(0xc0fe)) == UTF8_LANES16(0x80c2);
}
uint64_t leads = (v & UTF8_LANES16(0x1e)) + UTF8_LANES16(0x1e);
return (v & UTF8_LANES16(0xc0e0)) == UTF8_LANES16(0x80c0) &&
(leads & UTF8_LANES16(0x20)) == UTF8_LANES16(0x20);
}

static inline int
utf8_two_triples(uint64_t v)
{
if ((v & UTF8_LANES24(0xc0c0f0)) != UTF8_LANES24(0x8080e0)) {
return 0;
}
/* Combine the low lead nibble and bit 5 of the second byte. Zero
denotes an overlong E0 sequence and 0x1d a surrogate. */
uint64_t key = (v & UTF8_LANES24(0x0f)) | ((v >> 9) & UTF8_LANES24(0x10));
uint64_t ok = (key + UTF8_LANES24(0x7f)) &
((key ^ UTF8_LANES24(0x1d)) + UTF8_LANES24(0x7f));
return (ok & UTF8_LANES24(0x80)) == UTF8_LANES24(0x80);
}
#endif /* PY_LITTLE_ENDIAN */
#endif /* STRINGLIB_UTF8_GROUPS_DEFINED */

/* Widen four ASCII bytes to the destination character width. */
Py_LOCAL_INLINE(void)
STRINGLIB(utf8_ascii4)(STRINGLIB_CHAR *dest, uint32_t v)
{
#if STRINGLIB_SIZEOF_CHAR == 1
memcpy(dest, &v, sizeof(v));
#elif defined(UTF8_USE_SSE2)
__m128i zero = _mm_setzero_si128();
__m128i words = _mm_unpacklo_epi8(_mm_cvtsi32_si128((int)v), zero);
# if STRINGLIB_SIZEOF_CHAR == 2
_mm_storel_epi64((__m128i *)dest, words);
# else
_mm_storeu_si128((__m128i *)dest, _mm_unpacklo_epi16(words, zero));
# endif
#elif STRINGLIB_SIZEOF_CHAR == 2
uint64_t t = v;
t = (t | (t << 16)) & UTF8_LANES32(0xffff);
t = (t | (t << 8)) & UTF8_LANES16(0xff);
memcpy(dest, &t, sizeof(t));
#else
/* The low half contains the last two bytes on big-endian systems. */
for (int i = 0; i < 4; i += 2) {
uint64_t pair = (v & 0xff) | ((uint64_t)(v & 0xff00) << 24);
memcpy(dest + (PY_LITTLE_ENDIAN ? i : 2 - i), &pair, sizeof(pair));
v >>= 16;
}
#endif
}

Py_LOCAL_INLINE(Py_UCS4)
STRINGLIB(utf8_decode)(const char **inptr, const char *end,
STRINGLIB_CHAR *dest,
Py_ssize_t *outpos)
STRINGLIB_CHAR *dest, Py_ssize_t *outpos)
{
Py_UCS4 ch;
const char *s = *inptr;
Expand All @@ -32,61 +90,29 @@ STRINGLIB(utf8_decode)(const char **inptr, const char *end,
ch = (unsigned char)*s;

if (ch < 0x80) {
/* Fast path for runs of ASCII characters. Given that common UTF-8
input will consist of an overwhelming majority of ASCII
characters, we try to optimize for this case by checking
as many characters as a C 'size_t' can contain.
First, check if we can do an aligned read, as most CPUs have
a penalty for unaligned reads.
*/
if (_Py_IS_ALIGNED(s, ALIGNOF_SIZE_T)) {
/* Help register allocation */
const char *_s = s;
STRINGLIB_CHAR *_p = p;
while (_s + SIZEOF_SIZE_T <= end) {
/* Read a whole size_t at a time (either 4 or 8 bytes),
and do a fast unrolled copy if it only contains ASCII
characters. */
size_t value = *(const size_t *) _s;
if (value & ASCII_CHAR_MASK)
while (end - s >= 8) {
uint64_t v;
memcpy(&v, s, sizeof(v));
uint32_t first = (uint32_t)(v >> (PY_LITTLE_ENDIAN ? 0 : 32));
if (v & ASCII_CHAR_MASK) {
if (first & UINT32_C(0x80808080)) {
break;
#if PY_LITTLE_ENDIAN
_p[0] = (STRINGLIB_CHAR)(value & 0xFFu);
_p[1] = (STRINGLIB_CHAR)((value >> 8) & 0xFFu);
_p[2] = (STRINGLIB_CHAR)((value >> 16) & 0xFFu);
_p[3] = (STRINGLIB_CHAR)((value >> 24) & 0xFFu);
# if SIZEOF_SIZE_T == 8
_p[4] = (STRINGLIB_CHAR)((value >> 32) & 0xFFu);
_p[5] = (STRINGLIB_CHAR)((value >> 40) & 0xFFu);
_p[6] = (STRINGLIB_CHAR)((value >> 48) & 0xFFu);
_p[7] = (STRINGLIB_CHAR)((value >> 56) & 0xFFu);
# endif
#else
# if SIZEOF_SIZE_T == 8
_p[0] = (STRINGLIB_CHAR)((value >> 56) & 0xFFu);
_p[1] = (STRINGLIB_CHAR)((value >> 48) & 0xFFu);
_p[2] = (STRINGLIB_CHAR)((value >> 40) & 0xFFu);
_p[3] = (STRINGLIB_CHAR)((value >> 32) & 0xFFu);
_p[4] = (STRINGLIB_CHAR)((value >> 24) & 0xFFu);
_p[5] = (STRINGLIB_CHAR)((value >> 16) & 0xFFu);
_p[6] = (STRINGLIB_CHAR)((value >> 8) & 0xFFu);
_p[7] = (STRINGLIB_CHAR)(value & 0xFFu);
# else
_p[0] = (STRINGLIB_CHAR)((value >> 24) & 0xFFu);
_p[1] = (STRINGLIB_CHAR)((value >> 16) & 0xFFu);
_p[2] = (STRINGLIB_CHAR)((value >> 8) & 0xFFu);
_p[3] = (STRINGLIB_CHAR)(value & 0xFFu);
# endif
#endif
_s += SIZEOF_SIZE_T;
_p += SIZEOF_SIZE_T;
}
s = _s;
p = _p;
if (s == end)
}
STRINGLIB(utf8_ascii4)(p, first);
s += 4;
p += 4;
break;
ch = (unsigned char)*s;
}
uint32_t second = (uint32_t)(v >> (PY_LITTLE_ENDIAN ? 32 : 0));
STRINGLIB(utf8_ascii4)(p, first);
STRINGLIB(utf8_ascii4)(p + 4, second);
s += 8;
p += 8;
}
if (s == end) {
break;
}
ch = (unsigned char)*s;
if (ch < 0x80) {
s++;
*p++ = ch;
Expand All @@ -96,6 +122,34 @@ STRINGLIB(utf8_decode)(const char **inptr, const char *end,

if (ch < 0xE0) {
/* \xC2\x80-\xDF\xBF -- 0080-07FF */
#if PY_LITTLE_ENDIAN && STRINGLIB_MAX_CHAR >= 0xff
const char *run = s;
while (end - s >= 8) {
uint64_t v;
memcpy(&v, s, sizeof(v));
if (!utf8_four_pairs(v, STRINGLIB_MAX_CHAR == 255)) {
break;
}
uint64_t chars = ((v & UTF8_LANES16(0x1f)) << 6) |
((v >> 8) & UTF8_LANES16(0x3f));
# if STRINGLIB_SIZEOF_CHAR == 1
chars = (chars | (chars >> 8)) & UTF8_LANES32(0xffff);
uint32_t bytes = (uint32_t)(chars | (chars >> 16));
memcpy(p, &bytes, sizeof(bytes));
# elif STRINGLIB_SIZEOF_CHAR == 2
memcpy(p, &chars, sizeof(chars));
# else
for (int i = 0; i < 4; i++) {
p[i] = (uint16_t)(chars >> (16 * i));
}
# endif
p += 4;
s += 8;
}
if (s != run) {
continue;
}
#endif
Py_UCS4 ch2;
if (ch < 0xC2) {
/* invalid sequence
Expand Down Expand Up @@ -126,6 +180,26 @@ STRINGLIB(utf8_decode)(const char **inptr, const char *end,

if (ch < 0xF0) {
/* \xE0\xA0\x80-\xEF\xBF\xBF -- 0800-FFFF */
#if PY_LITTLE_ENDIAN && STRINGLIB_SIZEOF_CHAR >= 2
const char *run = s;
while (end - s >= 8) {
uint64_t v;
memcpy(&v, s, sizeof(v));
if (!utf8_two_triples(v)) {
break;
}
uint64_t chars = ((v & UTF8_LANES24(0x0f)) << 12) |
((v >> 2) & UTF8_LANES24(0xfc0)) |
((v >> 16) & UTF8_LANES24(0x3f));
p[0] = (uint16_t)chars;
p[1] = (uint16_t)(chars >> 24);
p += 2;
s += 6;
}
if (s != run) {
continue;
}
#endif
Py_UCS4 ch2, ch3;
if (end - s < 3) {
/* unexpected end of data: the caller will decide whether
Expand Down
4 changes: 2 additions & 2 deletions Objects/unicode_writer.c
Original file line number Diff line number Diff line change
Expand Up @@ -581,7 +581,7 @@ _PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
}

if (writer->recheck_maxchar) {
Py_UCS4 maxchar = _PyUnicode_FindMaxChar(str, 0, final_size);
Py_UCS4 maxchar = _PyUnicode_ScanMaxChar(str, 0, final_size);
if (maxchar != writer->maxchar) {
// Adjust the string kind
PyObject *str2 = PyUnicode_New(final_size, maxchar);
Expand All @@ -591,7 +591,7 @@ _PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
}
_PyUnicode_FastCopyCharacters(str2, 0, str, 0, final_size);
Py_SETREF(str, str2);
goto done;
return _PyUnicode_Result(str);
}
}

Expand Down
Loading
Loading