Skip to content

Commit 32c0eb4

Browse files
committed
rebase: apply review feedback on #1342
1 parent 06ba94d commit 32c0eb4

1 file changed

Lines changed: 33 additions & 4 deletions

File tree

multidict/_multilib/hashtable.h

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1809,10 +1809,39 @@ md_repr(MultiDictObject *md, PyObject *name, bool show_keys, bool show_values)
18091809
}
18101810
}
18111811
if (show_keys) {
1812-
/* Use repr() so keys containing quotes produce parseable output.
1813-
*/
1814-
if (PyUnicodeWriter_WriteRepr(writer, key) < 0) {
1815-
goto fail;
1812+
/* Fast path: ASCII keys without characters that would be escaped
1813+
* by repr() can be wrapped in single quotes directly. Falls back
1814+
* to PyUnicodeWriter_WriteRepr for keys containing quotes,
1815+
* backslashes, or non-printable characters so the output stays
1816+
* a valid Python string literal. */
1817+
int fast = 0;
1818+
if (PyUnicode_IS_ASCII(key)) {
1819+
Py_ssize_t klen = PyUnicode_GET_LENGTH(key);
1820+
const unsigned char *kdata =
1821+
(const unsigned char *)PyUnicode_DATA(key);
1822+
fast = 1;
1823+
for (Py_ssize_t ki = 0; ki < klen; ++ki) {
1824+
unsigned char c = kdata[ki];
1825+
if (c < 0x20 || c == 0x7f || c == '\'' || c == '\\') {
1826+
fast = 0;
1827+
break;
1828+
}
1829+
}
1830+
}
1831+
if (fast) {
1832+
if (PyUnicodeWriter_WriteChar(writer, '\'') < 0) {
1833+
goto fail;
1834+
}
1835+
if (PyUnicodeWriter_WriteStr(writer, key) < 0) {
1836+
goto fail;
1837+
}
1838+
if (PyUnicodeWriter_WriteChar(writer, '\'') < 0) {
1839+
goto fail;
1840+
}
1841+
} else {
1842+
if (PyUnicodeWriter_WriteRepr(writer, key) < 0) {
1843+
goto fail;
1844+
}
18161845
}
18171846
}
18181847
if (show_keys && show_values) {

0 commit comments

Comments
 (0)