From f38f5a5533c9574abdf9aea762f2eec17a5f8794 Mon Sep 17 00:00:00 2001 From: Inada Naoki Date: Thu, 3 Dec 2026 02:44:43 +0900 Subject: [PATCH] Speed up scalar UTF-8 decoding Decode short UTF-8 strings directly and use code point counts and character widths to size longer results. --- Include/internal/pycore_unicodeobject.h | 3 + Lib/test/test_str.py | 39 ++++ ...-12-04-23-19-51.gh-issue-163144.xnAPo1.rst | 2 + Objects/stringlib/codecs.h | 200 +++++++++++------ Objects/unicode_writer.c | 4 +- Objects/unicodeobject.c | 210 +++++++++++++----- 6 files changed, 336 insertions(+), 122 deletions(-) create mode 100644 Misc/NEWS.d/next/Core_and_Builtins/2026-12-04-23-19-51.gh-issue-163144.xnAPo1.rst diff --git a/Include/internal/pycore_unicodeobject.h b/Include/internal/pycore_unicodeobject.h index 62f3c96c716c42..02a097fd13413e 100644 --- a/Include/internal/pycore_unicodeobject.h +++ b/Include/internal/pycore_unicodeobject.h @@ -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 ( diff --git a/Lib/test/test_str.py b/Lib/test/test_str.py index 5e553094cac107..2b6feabd6016d0 100644 --- a/Lib/test/test_str.py +++ b/Lib/test/test_str.py @@ -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 @@ -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. @@ -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 @@ -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 diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-12-04-23-19-51.gh-issue-163144.xnAPo1.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-12-04-23-19-51.gh-issue-163144.xnAPo1.rst new file mode 100644 index 00000000000000..b52c650baa8c9a --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-12-04-23-19-51.gh-issue-163144.xnAPo1.rst @@ -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. diff --git a/Objects/stringlib/codecs.h b/Objects/stringlib/codecs.h index aa3de5e34eaaae..db73f3770bd9d4 100644 --- a/Objects/stringlib/codecs.h +++ b/Objects/stringlib/codecs.h @@ -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; @@ -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; @@ -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 @@ -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 diff --git a/Objects/unicode_writer.c b/Objects/unicode_writer.c index 8046accfd7e2ab..1ff3258009d696 100644 --- a/Objects/unicode_writer.c +++ b/Objects/unicode_writer.c @@ -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); @@ -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); } } diff --git a/Objects/unicodeobject.c b/Objects/unicodeobject.c index 309621acdaa3c8..a705b99343d38e 100644 --- a/Objects/unicodeobject.c +++ b/Objects/unicodeobject.c @@ -2347,7 +2347,7 @@ PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size) } Py_UCS4 -_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end) +_PyUnicode_ScanMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end) { int kind; const void *startptr, *endptr; @@ -2356,9 +2356,6 @@ _PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end) assert(end <= PyUnicode_GET_LENGTH(unicode)); assert(start <= end); - if (start == 0 && end == PyUnicode_GET_LENGTH(unicode)) - return PyUnicode_MAX_CHAR_VALUE(unicode); - if (start == end) return 127; @@ -2381,6 +2378,15 @@ _PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end) } } +Py_UCS4 +_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end) +{ + if (start == 0 && end == PyUnicode_GET_LENGTH(unicode)) { + return PyUnicode_MAX_CHAR_VALUE(unicode); + } + return _PyUnicode_ScanMaxChar(unicode, start, end); +} + /* Ensure that a string uses the most efficient storage, if it is not the case: create a new string with of the right kind. Write NULL into *p_unicode on error. */ @@ -4923,6 +4929,12 @@ PyUnicode_DecodeUTF8(const char *s, return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL); } +#if !defined(_M_ARM64EC) && \ + ((defined(__x86_64__) && defined(__SSE2__)) || defined(_M_X64)) +# include +# define UTF8_USE_SSE2 +#endif + #include "stringlib/asciilib.h" #include "stringlib/codecs.h" #include "stringlib/undef.h" @@ -5121,36 +5133,27 @@ vector_utf8_start_chars(size_t v) } -// Count the number of UTF-8 code points in a given byte sequence. +/* Count non-continuation bytes to size the output for valid UTF-8. */ static Py_ssize_t utf8_count_codepoints(const unsigned char *s, const unsigned char *end) { Py_ssize_t len = 0; - - if (end - s >= SIZEOF_SIZE_T) { - while (!_Py_IS_ALIGNED(s, ALIGNOF_SIZE_T)) { - len += scalar_utf8_start_char(*s++); - } - - while (s + SIZEOF_SIZE_T <= end) { - const unsigned char *e = end; - if (e - s > SIZEOF_SIZE_T * 255) { - e = s + SIZEOF_SIZE_T * 255; - } - Py_ssize_t vstart = 0; - while (s + SIZEOF_SIZE_T <= e) { - size_t v = *(size_t*)s; - size_t vs = vector_utf8_start_chars(v); - vstart += vs; - s += SIZEOF_SIZE_T; - } - vstart = (vstart & VECTOR_00FF) + ((vstart >> 8) & VECTOR_00FF); - vstart += vstart >> 16; + while (end - s >= SIZEOF_SIZE_T) { + Py_ssize_t words = Py_MIN((end - s) / SIZEOF_SIZE_T, 255); + const unsigned char *limit = s + words * SIZEOF_SIZE_T; + size_t starts = 0; + do { + size_t v; + memcpy(&v, s, sizeof(v)); + starts += vector_utf8_start_chars(v); + s += sizeof(v); + } while (s != limit); + starts = (starts & VECTOR_00FF) + ((starts >> 8) & VECTOR_00FF); + starts += starts >> 16; #if SIZEOF_SIZE_T == 8 - vstart += vstart >> 32; + starts += starts >> 32; #endif - len += vstart & 0x7ff; - } + len += starts & 0x7ff; } while (s < end) { len += scalar_utf8_start_char(*s++); @@ -5169,7 +5172,7 @@ ascii_decode(const char *start, const char *end, Py_UCS1 *dest) an explanation. */ const char *p = start; Py_UCS1 *q = dest; - while (p + SIZEOF_SIZE_T <= end) { + while (end - p >= SIZEOF_SIZE_T) { size_t value = *(const size_t *) p; if (value & ASCII_CHAR_MASK) break; @@ -5191,12 +5194,38 @@ ascii_decode(const char *start, const char *end, Py_UCS1 *dest) return pos; } +/* Each consecutive illegal start byte constitutes a separate error. */ +static inline const char * +utf8_skip_invalid_starts(const char *p, const char *end) +{ + while (p < end) { + unsigned char ch = (unsigned char)*p; + if (ch < 0x80 || (ch >= 0xc2 && ch <= 0xf4)) { + break; + } + p++; + } + return p; +} + +static void +raise_utf8_decode_error(const char *data, Py_ssize_t size, Py_ssize_t start, + Py_ssize_t end, const char *reason) +{ + PyObject *exc = PyUnicodeDecodeError_Create("utf-8", data, size, + start, end, reason); + if (exc != NULL) { + PyErr_SetObject(PyExc_UnicodeDecodeError, exc); + Py_DECREF(exc); + } +} + static int unicode_decode_utf8_impl(_PyUnicodeWriter *writer, const char *starts, const char *s, const char *end, _Py_error_handler error_handler, const char *errors, - Py_ssize_t *consumed) + Py_ssize_t *consumed, int sized_for_valid) { Py_ssize_t startinpos, endinpos; const char *errmsg = ""; @@ -5219,6 +5248,13 @@ unicode_decode_utf8_impl(_PyUnicodeWriter *writer, ch = ucs4lib_utf8_decode(&s, end, writer->data, &writer->pos); } + /* Exact sizing counts valid characters. Error handlers may emit one + character per invalid byte and a truncated lead may have suggested + a wider output than the consumed prefix actually needs. */ + if (sized_for_valid && ch <= 4 && s != end) { + writer->recheck_maxchar = 1; + } + switch (ch) { case 0: if (s == end || consumed) @@ -5257,16 +5293,43 @@ unicode_decode_utf8_impl(_PyUnicodeWriter *writer, if (error_handler == _Py_ERROR_UNKNOWN) error_handler = _Py_GetErrorHandler(errors); + if (sized_for_valid) { + // These handlers can produce a character for each invalid byte. + if ((error_handler == _Py_ERROR_REPLACE || + error_handler == _Py_ERROR_SURROGATEESCAPE) && + _PyUnicodeWriter_Prepare(writer, end - s, 127) < 0) { + goto onError; + } + sized_for_valid = 0; + } + switch (error_handler) { + case _Py_ERROR_STRICT: + raise_utf8_decode_error(starts, end - starts, startinpos, endinpos, errmsg); + goto onError; + case _Py_ERROR_IGNORE: - s += (endinpos - startinpos); + s = utf8_skip_invalid_starts(starts + endinpos, end); break; - case _Py_ERROR_REPLACE: - if (_PyUnicodeWriter_WriteCharInline(writer, 0xfffd) < 0) - goto onError; - s += (endinpos - startinpos); + case _Py_ERROR_REPLACE: { + const char *next = starts + endinpos; + s = utf8_skip_invalid_starts(next, end); + Py_ssize_t count = 1 + (s - next); + if (count == 1) { + if (_PyUnicodeWriter_WriteCharInline(writer, 0xfffd) < 0) { + goto onError; + } + } + else { + if (_PyUnicodeWriter_Prepare(writer, count, 0xfffd) < 0) { + goto onError; + } + _PyUnicode_FastFill(writer->buffer, writer->pos, count, 0xfffd); + writer->pos += count; + } break; + } case _Py_ERROR_SURROGATEESCAPE: { @@ -5275,6 +5338,7 @@ unicode_decode_utf8_impl(_PyUnicodeWriter *writer, if (_PyUnicodeWriter_PrepareKind(writer, PyUnicode_2BYTE_KIND) < 0) goto onError; assert(_PyUnicodeWriter_CanWrite(writer)); + endinpos = utf8_skip_invalid_starts(starts + endinpos, end) - starts; for (i=startinpos; ikind, writer->data, writer->pos, @@ -5315,6 +5379,32 @@ unicode_decode_utf8_impl(_PyUnicodeWriter *writer, } +/* Short strings fit on the stack even when every code point needs four + bytes. Discover their final storage width before allocating the result. */ +#define UTF8_SHORT_LIMIT 64 +Py_NO_INLINE static int +utf8_decode_short(const char *s, const char *end, PyObject **result) +{ + if (end - s <= 4) { + const char *next = s; + Py_UCS1 ascii[4]; + Py_ssize_t length = 0; + Py_UCS4 ch = asciilib_utf8_decode(&next, end, ascii, &length); + if (ch > 127 && length == 0 && next == end) { + *result = unicode_char(ch); + return 1; + } + } + Py_UCS4 chars[UTF8_SHORT_LIMIT]; + Py_ssize_t length = 0; + assert(end - s < UTF8_SHORT_LIMIT); + if (ucs4lib_utf8_decode(&s, end, chars, &length) != 0 || s != end) { + return 0; + } + *result = _PyUnicode_FromUCS4(chars, length); + return 1; +} + static PyObject * unicode_decode_utf8(const char *s, Py_ssize_t size, _Py_error_handler error_handler, const char *errors, @@ -5328,11 +5418,14 @@ unicode_decode_utf8(const char *s, Py_ssize_t size, } /* ASCII is equivalent to the first 128 ordinals in Unicode. */ - if (size == 1 && (unsigned char)s[0] < 128) { - if (consumed) { - *consumed = 1; + if (size == 1) { + unsigned char ch = (unsigned char)s[0]; + if (ch < 128) { + if (consumed) { + *consumed = 1; + } + return get_latin1_char(ch); } - return get_latin1_char((unsigned char)s[0]); } // I don't know this check is necessary or not. But there is a test @@ -5345,7 +5438,8 @@ unicode_decode_utf8(const char *s, Py_ssize_t size, const char *starts = s; const char *end = s + size; - Py_ssize_t pos = find_first_nonascii((const unsigned char*)starts, (const unsigned char*)end); + Py_ssize_t pos = find_first_nonascii((const unsigned char *)s, + (const unsigned char *)end); if (pos == size) { // fast path: ASCII string. PyObject *u = PyUnicode_New(size, 127); if (u == NULL) { @@ -5358,31 +5452,33 @@ unicode_decode_utf8(const char *s, Py_ssize_t size, return u; } + if (size < UTF8_SHORT_LIMIT && error_handler == _Py_ERROR_STRICT && !consumed) { + PyObject *result; + if (utf8_decode_short(s, end, &result)) { + return result; + } + } + int maxchr = 127; Py_ssize_t maxsize = size; unsigned char ch = (unsigned char)(s[pos]); - // error handler other than strict may remove/replace the invalid byte. - // consumed != NULL allows 1~3 bytes remainings. - // 0x80 <= ch < 0xc2 is invalid start byte that cause UnicodeDecodeError. - // otherwise: check the input and decide the maxchr and maxsize to reduce - // reallocation and copy. - if (error_handler == _Py_ERROR_STRICT && !consumed && ch >= 0xc2) { - // we only calculate the number of codepoints and don't determine the exact maxchr. - // This is because writing fast and portable SIMD code to find maxchr is difficult. - // If reallocation occurs for a larger maxchar, knowing the exact number of codepoints - // means that it is no longer necessary to allocate several times the required amount - // of memory. - maxsize = utf8_count_codepoints((const unsigned char *)s, (const unsigned char *)end); - if (ch < 0xc4) { // latin1 + int sized_for_valid = 0; + if (ch >= 0xc2 && ch <= 0xf4 && + (size >= UTF8_SHORT_LIMIT || (error_handler == _Py_ERROR_STRICT && !consumed))) { + maxsize = pos + utf8_count_codepoints((const unsigned char *)s + pos, + (const unsigned char *)end); + // The first non-ASCII lead byte determines the initial storage width. + if (ch < 0xc4) { maxchr = 0xff; } - else if (ch < 0xf0) { // ucs2 + else if (ch < 0xf0) { maxchr = 0xffff; } - else { // ucs4 + else { maxchr = 0x10ffff; } + sized_for_valid = (error_handler != _Py_ERROR_STRICT || consumed != NULL); } PyObject *u = PyUnicode_New(maxsize, maxchr); if (!u) { @@ -5400,7 +5496,7 @@ unicode_decode_utf8(const char *s, Py_ssize_t size, if (unicode_decode_utf8_impl(&writer, starts, s, end, error_handler, errors, - consumed) < 0) { + consumed, sized_for_valid) < 0) { _PyUnicodeWriter_Dealloc(&writer); return NULL; } @@ -5448,7 +5544,7 @@ _PyUnicode_DecodeUTF8Writer(_PyUnicodeWriter *writer, } int res = unicode_decode_utf8_impl(writer, starts, s, end, - error_handler, errors, consumed); + error_handler, errors, consumed, 0); if (res < 0) { goto error; }