1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
use std::fmt;

use serde::de::{self, SeqAccess, Visitor};

use crate::action::action_keyframes::ActionKeyframes;
use serde::{Deserialize, Deserializer};
struct ActionKeyframesVisitor;

impl<'de> Deserialize<'de> for ActionKeyframes {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_seq(ActionKeyframesVisitor)
    }
}

impl<'de> Visitor<'de> for ActionKeyframesVisitor {
    type Value = ActionKeyframes;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("A non-empty sequence of `Keyframe`s")
    }

    fn visit_seq<S>(self, mut seq: S) -> Result<Self::Value, S::Error>
    where
        S: SeqAccess<'de>,
    {
        let mut keyframes = Vec::with_capacity(1);

        while let Some(value) = seq.next_element()? {
            keyframes.push(value);
        }

        // This allows lowest/smallest frame caches to not have to be Option<u16>
        // If in the future we need to support empty keyframe lists we can remove this requirement
        // and just make our largest/smallest keyframe cache and Option<(u16, u16)>
        if keyframes.len() == 0 {
            return Err(de::Error::custom(
                "sequence must contain at least one keyframe",
            ));
        }

        Ok(ActionKeyframes::new(keyframes))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    /// Verify that there is an error if there are no keyframes.
    #[test]
    fn empty_list() {
        assert!(serde_yaml::from_str::<ActionKeyframes>(r#"[]"#).is_err());
    }

    /// Verify that we can deserialize keyframes
    #[test]
    fn deserialize() {
        let action_keyframes: ActionKeyframes = serde_yaml::from_str(
            r#"
- frame: 5
  bones: []
- frame: 2
  bones: []
"#,
        )
        .unwrap();

        assert_eq!(action_keyframes.smallest_frame, 2);
        assert_eq!(action_keyframes.largest_frame, 5);
    }
}