Skip to content

Commit

Permalink
Improve the JS string representation.
Browse files Browse the repository at this point in the history
  • Loading branch information
bamidev committed Mar 11, 2024
1 parent f0a04a9 commit d76170a
Showing 1 changed file with 13 additions and 4 deletions.
17 changes: 13 additions & 4 deletions src/javascript.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,15 +143,15 @@ impl fmt::Display for JsValue {
write!(f, "}}")
}
Self::Null => write!(f, "null"),
Self::String(s) => write!(f, "'{}'", escape_string(s)),
Self::String(s) => write!(f, "\"{}\"", escape_string(s)),
Self::Undefined => write!(f, "undefined"),
Self::Other(code) => write!(f, "{}", code),
}
}
}

const UNESCAPED_CHARACTERS: &str =
" \t_0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@\\*_+-./";
" \t_0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@*_+-./";

fn escape_string(string: &str) -> Cow<'_, str> {
if string.len() == 0 {
Expand All @@ -160,10 +160,19 @@ fn escape_string(string: &str) -> Cow<'_, str> {

let mut result = String::with_capacity(string.len() * 2);
for char in string.chars() {
if !UNESCAPED_CHARACTERS.contains(char) {
if char == '\n' {
result.push('\\');
result.push('n');
} else if char == '\r' {
result.push('\\');
result.push('r');
}
else {
if !UNESCAPED_CHARACTERS.contains(char) {
result.push('\\');
}
result.push(char);
}
result.push(char);
}
Cow::Owned(result)
}

0 comments on commit d76170a

Please sign in to comment.