From 296fafb8f32e8442ef8e4d5725c15ffca726b288 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Fri, 26 Jan 2024 13:03:05 -0800 Subject: [PATCH] Factor out JSON-specific Display impl for serde::de::Unexpected --- src/error.rs | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/src/error.rs b/src/error.rs index 03555eb4c..c260fe17e 100644 --- a/src/error.rs +++ b/src/error.rs @@ -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, + )) } } @@ -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 {