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
use std::fmt;

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

use super::SortedKeyframes;

struct SortedKeyframesVisitor;

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

impl<'de> Visitor<'de> for SortedKeyframesVisitor {
    type Value = SortedKeyframes;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("A of `BoneKeyframe`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);
        }

        Ok(SortedKeyframes::new(keyframes))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Verify that we can deserialize keyframes
    #[test]
    fn deserialize() {
        let keyframes: SortedKeyframes = serde_yaml::from_str(
            r#"
- frame: 5
  bone: {DualQuat: [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]}
- frame: 2
  bone: {DualQuat: [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]}
"#,
        )
        .unwrap();

        assert_eq!(keyframes.0[0].frame(), 2);
        assert_eq!(keyframes.0[1].frame(), 5);
    }
}