Skip to content
Open
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
28 changes: 26 additions & 2 deletions isa-utils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,19 @@ pub enum SingleDataValue {
}

pub fn quote(s: &str) -> String {
// TODO more things to quote
format!("\"{}\"", s.replace('\\', "\\\\").replace('\"', "\\\""))
let escaped = s
.chars()
.map(|c| match c {
'\\' => "\\\\".to_string(),
'"' => "\\\"".to_string(),
'\n' => "\\n".to_string(),
'\r' => "\\r".to_string(),
'\t' => "\\t".to_string(),
c if c.is_control() => format!("\\u{{{:x}}}", c as u32),
c => c.to_string(),
})
.collect::<String>();
format!("\"{escaped}\"")
}

pub fn escape_label(l: &str) -> String {
Expand All @@ -31,3 +42,16 @@ pub fn escape_label(l: &str) -> String {
.replace("'", "_quote_")
.replace("*", "_deref_")
}

#[cfg(test)]
mod tests {
use super::quote;

#[test]
fn quote_escapes_control_characters() {
assert_eq!(
quote("line\ncolumn\treturn\r"),
"\"line\\ncolumn\\treturn\\r\""
);
}
}
Loading