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
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Speed up the tokenizer by copying source text verbatim when it contains no
carriage returns.
11 changes: 10 additions & 1 deletion Parser/tokenizer/helpers.c
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,8 @@ char *
_PyTokenizer_translate_newlines(const char *s, int exec_input, int preserve_crlf,
struct tok_state *tok) {
int skip_next_lf = 0;
size_t needed_length = strlen(s) + 2, final_length;
size_t input_length = strlen(s);
size_t needed_length = input_length + 2, final_length;
char *buf, *current;
char c = '\0';
buf = PyMem_Malloc(needed_length);
Expand All @@ -274,6 +275,13 @@ _PyTokenizer_translate_newlines(const char *s, int exec_input, int preserve_crlf
PyErr_NoMemory();
return NULL;
}
if (memchr(s, '\r', input_length) == NULL) {
// No carriage returns: nothing to translate, copy verbatim.
memcpy(buf, s, input_length);
current = buf + input_length;
c = input_length ? s[input_length - 1] : '\0';
goto add_final_newline;
Comment on lines +282 to +283

@maurycy maurycy Jul 11, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggested change
c = input_length ? s[input_length - 1] : '\0';
goto add_final_newline;
if (exec_input && input_length && s[input_length - 1] != '\n') {
*current++ = '\n';
}
*current = '\0';
return buf;

Do you think it makes sense to spare PyMem_Realloc()?

}
for (current = buf; *s; s++, current++) {
c = *s;
if (skip_next_lf) {
Expand All @@ -290,6 +298,7 @@ _PyTokenizer_translate_newlines(const char *s, int exec_input, int preserve_crlf
}
*current = c;
}
add_final_newline:
/* If this is exec input, add a newline to the end of the string if
there isn't one already. */
if (exec_input && c != '\n' && c != '\0') {
Expand Down
Loading