simplify Deserialize impl for Atoms

This commit is contained in:
Ponj 2024-11-07 21:43:32 -05:00
parent 304a360608
commit 78d7c493bb
Signed by: p6nj
GPG key ID: 6FED68D87C479A59

View file

@ -60,54 +60,7 @@ impl<'de> Deserialize<'de> for Atoms {
notes: String,
sheet: String,
}
struct NotesSheetVisitor;
impl<'de> Visitor<'de> for NotesSheetVisitor {
type Value = NotesSheet;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("a \"notes\" field and a \"sheet\" field")
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: serde::de::SeqAccess<'de>,
{
let notes = seq
.next_element()?
.ok_or_else(|| de::Error::invalid_length(0, &self))?;
let sheet = seq
.next_element()?
.ok_or_else(|| de::Error::invalid_length(1, &self))?;
Ok(NotesSheet::new(notes, sheet))
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
A: de::MapAccess<'de>,
{
let mut notes = None;
let mut sheet = None;
while let Some(key) = map.next_key()? {
match key {
Field::Notes => {
if notes.is_some() {
return Err(de::Error::duplicate_field("notes"));
}
notes = Some(map.next_value()?);
}
Field::Sheet => {
if sheet.is_some() {
return Err(de::Error::duplicate_field("sheet"));
}
sheet = Some(map.next_value()?);
}
}
}
let notes = notes.ok_or_else(|| de::Error::missing_field("notes"))?;
let sheet = sheet.ok_or_else(|| de::Error::missing_field("sheet"))?;
Ok(NotesSheet::new(notes, sheet))
}
}
const FIELDS: &[&str] = &["notes", "sheet"];
let NotesSheet { notes, sheet } =
deserializer.deserialize_struct("NotesSheet", FIELDS, NotesSheetVisitor)?;
let NotesSheet { notes, sheet } = NotesSheet::deserialize(deserializer)?;
if sheet.is_empty() {
Ok(Default::default())
} else {