Skip to content

Commit

Permalink
Print char 0 in error messages as '\0' rather than '\u{0}'
Browse files Browse the repository at this point in the history
  • Loading branch information
dtolnay committed Mar 28, 2022
1 parent 8d8bdb2 commit ce1fef1
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
34 changes: 30 additions & 4 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,26 @@ impl Display for Error {
ErrorKind::UnexpectedChar(pos, ch) => {
write!(
formatter,
"unexpected character {:?} while parsing {}",
ch, pos,
"unexpected character {} while parsing {}",
QuotedChar(*ch),
pos,
)
}
ErrorKind::UnexpectedCharAfter(pos, ch) => {
write!(formatter, "unexpected character {:?} after {}", ch, pos)
write!(
formatter,
"unexpected character {} after {}",
QuotedChar(*ch),
pos,
)
}
ErrorKind::ExpectedCommaFound(pos, ch) => {
write!(formatter, "expected comma after {}, found {:?}", pos, ch)
write!(
formatter,
"expected comma after {}, found {}",
pos,
QuotedChar(*ch),
)
}
ErrorKind::LeadingZero(pos) => {
write!(formatter, "invalid leading zero in {}", pos)
Expand Down Expand Up @@ -96,3 +107,18 @@ impl Debug for Error {
Ok(())
}
}

struct QuotedChar(char);

impl Display for QuotedChar {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
// Standard library versions prior to https://github.com/rust-lang/rust/pull/95345
// print character 0 as '\u{0}'. We prefer '\0' to keep error messages
// the same across all supported Rust versions.
if self.0 == '\0' {
formatter.write_str("'\\0'")
} else {
write!(formatter, "{:?}", self.0)
}
}
}
2 changes: 1 addition & 1 deletion tests/test_version_req.rs
Original file line number Diff line number Diff line change
Expand Up @@ -336,7 +336,7 @@ pub fn test_parse_errors() {
let err = req_err("\0");
assert_to_string(
err,
"unexpected character '\\u{0}' while parsing major version number",
"unexpected character '\\0' while parsing major version number",
);

let err = req_err(">= >= 0.0.2");
Expand Down

0 comments on commit ce1fef1

Please sign in to comment.