blender_armature/action/action_keyframes/action_keyframes_serde/
deserialize.rs

1use std::fmt;
2
3use serde::de::{self, SeqAccess, Visitor};
4
5use crate::action::action_keyframes::ActionKeyframes;
6use serde::{Deserialize, Deserializer};
7struct ActionKeyframesVisitor;
8
9impl<'de> Deserialize<'de> for ActionKeyframes {
10    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
11    where
12        D: Deserializer<'de>,
13    {
14        deserializer.deserialize_seq(ActionKeyframesVisitor)
15    }
16}
17
18impl<'de> Visitor<'de> for ActionKeyframesVisitor {
19    type Value = ActionKeyframes;
20
21    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
22        formatter.write_str("A non-empty sequence of `Keyframe`s")
23    }
24
25    fn visit_seq<S>(self, mut seq: S) -> Result<Self::Value, S::Error>
26    where
27        S: SeqAccess<'de>,
28    {
29        let mut keyframes = Vec::with_capacity(1);
30
31        while let Some(value) = seq.next_element()? {
32            keyframes.push(value);
33        }
34
35        // This allows lowest/smallest frame caches to not have to be Option<u16>
36        // If in the future we need to support empty keyframe lists we can remove this requirement
37        // and just make our largest/smallest keyframe cache and Option<(u16, u16)>
38        if keyframes.len() == 0 {
39            return Err(de::Error::custom(
40                "sequence must contain at least one keyframe",
41            ));
42        }
43
44        Ok(ActionKeyframes::new(keyframes))
45    }
46}
47
48#[cfg(test)]
49mod tests {
50    use super::*;
51    /// Verify that there is an error if there are no keyframes.
52    #[test]
53    fn empty_list() {
54        assert!(serde_yaml::from_str::<ActionKeyframes>(r#"[]"#).is_err());
55    }
56
57    /// Verify that we can deserialize keyframes
58    #[test]
59    fn deserialize() {
60        let action_keyframes: ActionKeyframes = serde_yaml::from_str(
61            r#"
62- frame: 5
63  bones: []
64- frame: 2
65  bones: []
66"#,
67        )
68        .unwrap();
69
70        assert_eq!(action_keyframes.smallest_frame, 2);
71        assert_eq!(action_keyframes.largest_frame, 5);
72    }
73}