diff options
author | Azriel Hoh <azriel91@gmail.com> | 2018-11-12 10:09:30 +1300 |
---|---|---|
committer | Azriel Hoh <azriel91@gmail.com> | 2018-11-12 10:09:30 +1300 |
commit | 2907bd1953b15c81d4e7bfd1b060a9c9d947c2e4 (patch) | |
tree | ec3779ffc3c3362ee7203cb851ef829ded91ee86 /src | |
parent | 2c2d62981279721c87128f988148c876c1caf18c (diff) | |
download | milf-rs-2907bd1953b15c81d4e7bfd1b060a9c9d947c2e4.tar.gz milf-rs-2907bd1953b15c81d4e7bfd1b060a9c9d947c2e4.zip |
Error when deserializing struct if encountering unknown fields.
Issue #225
Diffstat (limited to 'src')
-rw-r--r-- | src/de.rs | 41 |
1 files changed, 41 insertions, 0 deletions
@@ -178,6 +178,16 @@ enum ErrorKind { /// Dotted key attempted to extend something that is not a table. DottedKeyInvalidType, + /// An unexpected key was encountered. + /// + /// Used when deserializing a struct with a limited set of fields. + UnexpectedKeys { + /// The unexpected keys. + keys: Vec<String>, + /// Keys that may be specified. + available: &'static [&'static str], + }, + #[doc(hidden)] __Nonexhaustive, } @@ -547,6 +557,28 @@ impl<'de> de::Deserializer<'de> for ValueDeserializer<'de> { } } + match &self.value.e { + E::InlineTable(values) | E::DottedTable(values) => { + let extra_fields = values.iter() + .filter_map(|(key, _val)| { + if !fields.contains(&&(**key)) { + Some(key.clone()) + } else { + None + } + }) + .collect::<Vec<Cow<'de, str>>>(); + + if !extra_fields.is_empty() { + return Err(Error::from_kind(ErrorKind::UnexpectedKeys { + keys: extra_fields.iter().map(|k| k.to_string()).collect::<Vec<_>>(), + available: fields, + })); + } + } + _ => {} + } + if name == spanned::NAME && fields == &[spanned::START, spanned::END, spanned::VALUE] { let start = self.value.start; let end = self.value.end; @@ -1653,6 +1685,14 @@ impl fmt::Display for Error { ErrorKind::DottedKeyInvalidType => { "dotted key attempted to extend non-table type".fmt(f)? } + ErrorKind::UnexpectedKeys { ref keys, available } => { + write!( + f, + "unexpected keys in table: `{:?}`, available keys: `{:?}`", + keys, + available + )? + } ErrorKind::__Nonexhaustive => panic!(), } @@ -1700,6 +1740,7 @@ impl error::Error for Error { ErrorKind::ExpectedTupleIndex { .. } => "expected table key", ErrorKind::ExpectedEmptyTable => "expected empty table", ErrorKind::DottedKeyInvalidType => "dotted key invalid type", + ErrorKind::UnexpectedKeys { .. } => "unexpected keys in table", ErrorKind::__Nonexhaustive => panic!(), } } |