From 7d907003fbf4962540ea2dbc09b54f62b9c4765b Mon Sep 17 00:00:00 2001 From: Ed Page Date: Tue, 11 Jan 2022 10:24:28 -0600 Subject: [PATCH] fix(easy): Escape tokens in errors Fixes #333 --- src/stream/easy.rs | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/src/stream/easy.rs b/src/stream/easy.rs index 0a541824..bd872a67 100644 --- a/src/stream/easy.rs +++ b/src/stream/easy.rs @@ -162,14 +162,41 @@ impl PartialEq for Info { impl fmt::Display for Info { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { - Info::Token(ref c) => write!(f, "`{}`", c), - Info::Range(ref c) => write!(f, "`{}`", c), + Info::Token(ref c) => escaped_token(c, '`', f), + Info::Range(ref c) => escaped_token(c, '`', f), Info::Owned(ref s) => write!(f, "{}", s), Info::Static(s) => write!(f, "{}", s), } } } +fn escaped_token( + token: &T, + quote: char, + f: &mut fmt::Formatter<'_>, +) -> fmt::Result { + let token = token.to_string(); + write!(f, "{}", quote)?; + for c in token.chars() { + match c { + '\t' | '\n' | '\r' => { + write!(f, "{}", c.escape_debug())?; + } + c if c.is_ascii_control() => { + write!(f, "{}", c.escape_debug())?; + } + c if c == quote => { + write!(f, "\\{}", quote)?; + } + _ => { + write!(f, "{}", c)?; + } + } + } + write!(f, "{}", quote)?; + Ok(()) +} + impl From for Info { fn from(s: char) -> Info { Info::Token(s)