mirror of
https://github.com/erg-lang/erg.git
synced 2025-08-04 10:49:54 +00:00
fix: escape when displaying string literals
This commit is contained in:
parent
5e8d1b987a
commit
b04429b3fd
2 changed files with 20 additions and 1 deletions
|
@ -200,6 +200,7 @@ impl Str {
|
|||
Str::rc(&self.chars().rev().collect::<String>())
|
||||
}
|
||||
|
||||
/// Note that replacements may be chained because it attempt to rewrite in sequence
|
||||
pub fn multi_replace(&self, paths: &[(&str, &str)]) -> Self {
|
||||
let mut self_ = self.to_string();
|
||||
for (from, to) in paths {
|
||||
|
@ -232,6 +233,24 @@ impl Str {
|
|||
pub fn find_sub<'a>(&self, pats: &[&'a str]) -> Option<&'a str> {
|
||||
pats.iter().find(|&&pat| self.contains(pat)).copied()
|
||||
}
|
||||
|
||||
/// ```
|
||||
/// # use erg_common::str::Str;
|
||||
/// let s = Str::rc("\n");
|
||||
/// assert_eq!(&s.escape()[..], "\\n");
|
||||
/// let s = Str::rc("\\");
|
||||
/// assert_eq!(&s.escape()[..], "\\\\");
|
||||
/// ```
|
||||
pub fn escape(&self) -> Str {
|
||||
self.multi_replace(&[
|
||||
("\\", "\\\\"),
|
||||
("\0", "\\0"),
|
||||
("\r", "\\r"),
|
||||
("\n", "\\n"),
|
||||
("\"", "\\\""),
|
||||
("\'", "\\'"),
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
|
|
@ -487,7 +487,7 @@ impl fmt::Debug for ValueObj {
|
|||
}
|
||||
Ok(())
|
||||
}
|
||||
Self::Str(s) => write!(f, "\"{s}\""),
|
||||
Self::Str(s) => write!(f, "\"{}\"", s.escape()),
|
||||
Self::Bool(b) => {
|
||||
if *b {
|
||||
write!(f, "True")
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue