pub(crate) fn escape_c_str(s: &str) -> String {
let mut out = String::with_capacity(s.len() + 2);
for &b in s.as_bytes() {
match b {
b'"' => out.push_str("\\\""),
b'\\' => out.push_str("\\\\"),
b'\n' => out.push_str("\\n"),
b'\t' => out.push_str("\\t"),
b'\r' => out.push_str("\\r"),
0x07 => out.push_str("\\a"),
0x08 => out.push_str("\\b"),
0x0b => out.push_str("\\v"),
0x0c => out.push_str("\\f"),
0x20..=0x7e => out.push(b as char),
_ => out.push_str(&format!("\\{b:03o}")),
}
}
out
}
pub(crate) fn escape_c_char(c: char) -> String {
match c {
'\'' => "\\'".to_string(),
'\\' => "\\\\".to_string(),
'\n' => "\\n".to_string(),
'\t' => "\\t".to_string(),
'\r' => "\\r".to_string(),
'\0' => "\\0".to_string(),
'\u{07}' => "\\a".to_string(),
'\u{08}' => "\\b".to_string(),
'\u{0b}' => "\\v".to_string(),
'\u{0c}' => "\\f".to_string(),
c if (' '..='~').contains(&c) => c.to_string(),
c if (c as u32) <= 0xff => format!("\\{:03o}", c as u32),
c => format!("\\x{:x}", c as u32),
}
}