Skip to content
Merged
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
30 changes: 25 additions & 5 deletions compiler/rustc_ast/src/util/literal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,31 @@ use crate::token::{self, Token};
// Escapes a string, represented as a symbol. Reuses the original symbol,
// avoiding interning, if no changes are required.
pub fn escape_string_symbol(symbol: Symbol) -> Symbol {
// Don't use escape_default() here, because using it in conjunction with to_string()
// is slow.
let s = symbol.as_str();
let mut escaped = String::with_capacity(s.len());
for c in s.chars() {

fn requires_escape(b: &u8) -> bool {
match *b {
b'\\' | b'\'' | b'"' => true,
b'\x20'..=b'\x7e' => false,
_ => true,
}
}

// Fast-path: if we don't need escaping, just return the original symbol

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.

I swear I did this exact optimization somewhere else a long time ago.

let Some(position) = s.as_bytes().iter().position(requires_escape) else {
return symbol;
};

// At this point we know that we need to escape something in `suffix`
let (prefix, suffix) = s.split_at(position);

// We set the capacity to the original size + 1, because the resulting string will be at least
// one character larger than the original, because of escaping.
let mut escaped = String::with_capacity(s.len() + 1);
escaped.push_str(prefix);

// Don't use escape_default() here, because using it is slower than escaping manually.
for c in suffix.chars() {
match c {
'\t' => escaped.push_str("\\t"),
'\r' => escaped.push_str("\\r"),
Expand All @@ -31,7 +51,7 @@ pub fn escape_string_symbol(symbol: Symbol) -> Symbol {
c => write!(escaped, "\\u{{{:x}}}", c as u32).unwrap(),
}
}
if s == escaped { symbol } else { Symbol::intern(&escaped) }
Symbol::intern(&escaped)
}

// Escapes a char.
Expand Down
Loading