Skip to content

Commit

Permalink
Make SimdAabb deserializable in a map-like formats like JSON, YAML, o…
Browse files Browse the repository at this point in the history
…r RON
  • Loading branch information
shoebe authored and sebcrozet committed Apr 15, 2023
1 parent b1493eb commit 8974bb9
Showing 1 changed file with 37 additions and 1 deletion.
38 changes: 37 additions & 1 deletion src/bounding_volume/simd_aabb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ impl serde::Serialize for SimdAabb {
.map(|e| array![|ii| e.extract(ii); SIMD_WIDTH]),
);

let mut simd_aabb = serializer.serialize_struct("simd_aabb", 2)?;
let mut simd_aabb = serializer.serialize_struct("SimdAabb", 2)?;
simd_aabb.serialize_field("mins", &mins)?;
simd_aabb.serialize_field("maxs", &maxs)?;
simd_aabb.end()
Expand All @@ -54,6 +54,13 @@ impl<'de> serde::Deserialize<'de> for SimdAabb {
{
struct Visitor {}

#[derive(Deserialize)]
#[serde(field_identifier, rename_all = "lowercase")]
enum Field {
Mins,
Maxs,
}

impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = SimdAabb;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
Expand All @@ -64,6 +71,35 @@ impl<'de> serde::Deserialize<'de> for SimdAabb {
)
}

fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
A: serde::de::MapAccess<'de>,
{
let mut mins: Option<Point<[Real; SIMD_WIDTH]>> = None;
let mut maxs: Option<Point<[Real; SIMD_WIDTH]>> = None;
while let Some(key) = map.next_key()? {
match key {
Field::Mins => {
if mins.is_some() {
return Err(serde::de::Error::duplicate_field("mins"));
}
mins = Some(map.next_value()?);
}
Field::Maxs => {
if maxs.is_some() {
return Err(serde::de::Error::duplicate_field("maxs"));
}
maxs = Some(map.next_value()?);
}
}
}
let mins = mins.ok_or_else(|| serde::de::Error::missing_field("mins"))?;
let maxs = maxs.ok_or_else(|| serde::de::Error::missing_field("maxs"))?;
let mins = Point::from(mins.coords.map(|e| SimdReal::from(e)));
let maxs = Point::from(maxs.coords.map(|e| SimdReal::from(e)));
Ok(SimdAabb { mins, maxs })
}

fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: serde::de::SeqAccess<'de>,
Expand Down

0 comments on commit 8974bb9

Please sign in to comment.