From 35814a511528bfa07fbf37a491e32fd421d29183 Mon Sep 17 00:00:00 2001 From: Kyrylo Polezhaiev Date: Tue, 30 Mar 2021 05:01:39 +0300 Subject: [PATCH] model: Add partial field deserializer --- src/models/model.rs | 38 ++++++++++++++++++++++++-------------- 1 file changed, 24 insertions(+), 14 deletions(-) diff --git a/src/models/model.rs b/src/models/model.rs index af1af47..9718be2 100644 --- a/src/models/model.rs +++ b/src/models/model.rs @@ -44,6 +44,28 @@ impl Serialize for Model { impl<'de> Deserialize<'de> for Model { fn deserialize>(deserializer: D) -> Result { + struct Field(String); + impl<'de> Deserialize<'de> for Field { + fn deserialize>(deserializer: D) -> Result { + struct FieldVisitor; + impl<'de> Visitor<'de> for FieldVisitor { + type Value = Field; + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("`id` or `type`") + } + fn visit_str(self, value: &str) -> Result + where + E: de::Error, + { + match value { + tag => Ok(Field(String::from(tag))) + } + } + } + + deserializer.deserialize_identifier(FieldVisitor) + } + } struct ModelVisitor; impl<'de> Visitor<'de> for ModelVisitor { type Value = Model; @@ -58,20 +80,8 @@ impl<'de> Deserialize<'de> for Model { let mut model_type = None; while let Some(key) = map.next_key()? { match key { - "id" => { - if id.is_some() { - return Err(de::Error::duplicate_field("id")); - } - id = Some(map.next_value()?); - } - "type" => { - if model_type.is_some() { - return Err(de::Error::duplicate_field("type")); - } - model_type = Some(map.next_value()?); - } - field => { - println!("Unparsed field: {}", field); + Field(tag) => { + println!("Unparsed field: {}", tag); } } }