Skip to content

Commit 296fafb

Browse files
committed
Factor out JSON-specific Display impl for serde::de::Unexpected
1 parent e56cc69 commit 296fafb

File tree

1 file changed

+17
-5
lines changed

1 file changed

+17
-5
lines changed

src/error.rs

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -438,11 +438,11 @@ impl de::Error for Error {
438438

439439
#[cold]
440440
fn invalid_type(unexp: de::Unexpected, exp: &dyn de::Expected) -> Self {
441-
if let de::Unexpected::Unit = unexp {
442-
Error::custom(format_args!("invalid type: null, expected {}", exp))
443-
} else {
444-
Error::custom(format_args!("invalid type: {}, expected {}", unexp, exp))
445-
}
441+
Error::custom(format_args!(
442+
"invalid type: {}, expected {}",
443+
JsonUnexpected(unexp),
444+
exp,
445+
))
446446
}
447447
}
448448

@@ -453,6 +453,18 @@ impl ser::Error for Error {
453453
}
454454
}
455455

456+
struct JsonUnexpected<'a>(de::Unexpected<'a>);
457+
458+
impl<'a> Display for JsonUnexpected<'a> {
459+
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
460+
if let de::Unexpected::Unit = self.0 {
461+
formatter.write_str("null")
462+
} else {
463+
Display::fmt(&self.0, formatter)
464+
}
465+
}
466+
}
467+
456468
// Parse our own error message that looks like "{} at line {} column {}" to work
457469
// around erased-serde round-tripping the error through de::Error::custom.
458470
fn make_error(mut msg: String) -> Error {

0 commit comments

Comments
 (0)