mirror of
https://github.com/allankoechke/rust.git
synced 2026-12-05 17:36:20 +00:00
Optimize escape_string_symbol()
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
//! Code related to parsing literals.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
use std::{ascii, fmt, str};
|
||||
|
||||
use rustc_literal_escaper::{
|
||||
@@ -14,8 +15,22 @@ 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 escaped = s.escape_default().to_string();
|
||||
let mut escaped = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'\t' => escaped.push_str("\\t"),
|
||||
'\r' => escaped.push_str("\\r"),
|
||||
'\n' => escaped.push_str("\\n"),
|
||||
'\\' => escaped.push_str("\\\\"),
|
||||
'\'' => escaped.push_str("\\'"),
|
||||
'\"' => escaped.push_str("\\\""),
|
||||
'\x20'..='\x7e' => escaped.push(c),
|
||||
c => write!(escaped, "\\u{{{:x}}}", c as u32).unwrap(),
|
||||
}
|
||||
}
|
||||
if s == escaped { symbol } else { Symbol::intern(&escaped) }
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user