Skip to content

Commit

Permalink
Factor out JSON-specific Display impl for serde::de::Unexpected
Browse files Browse the repository at this point in the history
  • Loading branch information
dtolnay committed Jan 26, 2024
1 parent e56cc69 commit 296fafb
Showing 1 changed file with 17 additions and 5 deletions.
22 changes: 17 additions & 5 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -438,11 +438,11 @@ impl de::Error for Error {

#[cold]
fn invalid_type(unexp: de::Unexpected, exp: &dyn de::Expected) -> Self {
if let de::Unexpected::Unit = unexp {
Error::custom(format_args!("invalid type: null, expected {}", exp))
} else {
Error::custom(format_args!("invalid type: {}, expected {}", unexp, exp))
}
Error::custom(format_args!(
"invalid type: {}, expected {}",
JsonUnexpected(unexp),
exp,
))
}
}

Expand All @@ -453,6 +453,18 @@ impl ser::Error for Error {
}
}

struct JsonUnexpected<'a>(de::Unexpected<'a>);

impl<'a> Display for JsonUnexpected<'a> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
if let de::Unexpected::Unit = self.0 {
formatter.write_str("null")
} else {
Display::fmt(&self.0, formatter)
}
}
}

// Parse our own error message that looks like "{} at line {} column {}" to work
// around erased-serde round-tripping the error through de::Error::custom.
fn make_error(mut msg: String) -> Error {
Expand Down

0 comments on commit 296fafb

Please sign in to comment.