Skip to content

gh-119182: Optimize PyUnicode_FromFormat() #120796

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 20, 2024
Merged
Changes from 1 commit
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
38 changes: 19 additions & 19 deletions Objects/unicodeobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -2891,31 +2891,31 @@ unicode_from_format(_PyUnicodeWriter *writer, const char *format, va_list vargs)
goto fail;
}
else {
const char *p;
const char *p = strchr(f, '%');
Py_ssize_t len;

p = f;
do
{
if ((unsigned char)*p > 127) {
PyErr_Format(PyExc_ValueError,
"PyUnicode_FromFormatV() expects an ASCII-encoded format "
"string, got a non-ASCII byte: 0x%02x",
(unsigned char)*p);
goto fail;
}
p++;
if (p != NULL) {
len = p - f;
}
while (*p != '\0' && *p != '%');
len = p - f;

if (*p == '\0')
else {
len = strlen(f);
writer->overallocate = 0;
}

if (_PyUnicodeWriter_WriteASCIIString(writer, f, len) < 0)
int is_ascii = (ucs1lib_find_max_char((Py_UCS1*)f, (Py_UCS1*)f + len) < 128);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can run it once, for the whole format string.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right. I modified my PR to run it only once, good idea!

if (!is_ascii) {
Py_ssize_t i;
for (i=0; i < len && (unsigned char)f[i] <= 127; i++);
PyErr_Format(PyExc_ValueError,
"PyUnicode_FromFormatV() expects an ASCII-encoded format "
"string, got a non-ASCII byte: 0x%02x",
(unsigned char)f[i]);
goto fail;
}

f = p;
if (_PyUnicodeWriter_WriteASCIIString(writer, f, len) < 0) {
goto fail;
}
f += len;
}
}
va_end(vargs2);
Expand Down
Loading