Skip to content

Commit

Permalink
Added visitor for newtype struct
Browse files Browse the repository at this point in the history
  • Loading branch information
cikzh committed Feb 16, 2024
1 parent 7a0b878 commit cc37eb1
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions statime/src/datastructures/messages/header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ impl<'de> serde::Deserialize<'de> for SdoId {
where
D: serde::Deserializer<'de>,
{
deserializer.deserialize_u16(SdoIdVisitor)
deserializer.deserialize_newtype_struct("SdoId", SdoIdVisitor)
}
}

Expand All @@ -197,6 +197,19 @@ impl<'de> serde::de::Visitor<'de> for SdoIdVisitor {
formatter.write_str("a 12 bit value within the 0..=0xFFF range")
}

fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::de::Error;
use serde::Deserialize;
let v = u16::deserialize(deserializer)?;
SdoId::try_from(v).or(Err(D::Error::custom(std::format!(
"SdoId not in range of 0..=0xFFF: {}",
v
))))
}

fn visit_u16<E>(self, v: u16) -> Result<Self::Value, E>
where
E: serde::de::Error,
Expand Down Expand Up @@ -416,7 +429,7 @@ mod tests {

assert_de_tokens_error::<SdoId>(
&[Token::NewtypeStruct { name: "SdoId" }, Token::U16(4096)],
"invalid type: newtype struct, expected a 12 bit value within the 0..=0xFFF range",
"SdoId not in range of 0..=0xFFF: 4096",
);
}
}

0 comments on commit cc37eb1

Please sign in to comment.