godot_binary_serialization/decoder/
vector.rs

1use crate::types::{
2    structures::{GodotVector2, GodotVector3},
3    SerializeFlag,
4};
5
6use super::Decoder;
7
8impl Decoder {
9    /// Decodes bytes into a vector 2. This will fail if the inner bytes can't be decoded into a
10    /// float
11    pub fn decode_vector2(bytes: &[u8]) -> anyhow::Result<GodotVector2> {
12        let x = Decoder::decode_raw_float(bytes, 4, &SerializeFlag::None)?.value as f32;
13        let y = Decoder::decode_raw_float(bytes, 8, &SerializeFlag::None)?.value as f32;
14
15        Ok(GodotVector2 { x, y })
16    }
17
18    /// Decodes bytes into a vector 3. This will fail if the inner bytes can't be decoded into a
19    /// float
20    pub fn decode_vector3(bytes: &[u8]) -> anyhow::Result<GodotVector3> {
21        let x = Decoder::decode_raw_float(bytes, 4, &SerializeFlag::None)?.value as f32;
22        let y = Decoder::decode_raw_float(bytes, 8, &SerializeFlag::None)?.value as f32;
23        let z = Decoder::decode_raw_float(bytes, 12, &SerializeFlag::None)?.value as f32;
24
25        Ok(GodotVector3 { x, y, z })
26    }
27}
28
29#[cfg(test)]
30mod tests {
31    use crate::{
32        decoder::Decoder,
33        types::structures::{GodotVector2, GodotVector3},
34    };
35
36    #[test]
37    fn decode_vector2() {
38        let bytes = [5, 0, 0, 0, 0, 0, 134, 66, 0, 31, 94, 71];
39        let (_type, _flag) = Decoder::get_type_and_flags(&bytes).unwrap();
40        let vector2 = Decoder::decode_vector2(&bytes).unwrap();
41        let value = GodotVector2 {
42            x: 67.0,
43            y: 56863.0,
44        };
45
46        assert_eq!(
47            vector2, value,
48            "Expected value of {:?} but got {:?} instead",
49            value, vector2
50        );
51    }
52
53    #[test]
54    fn decode_vector3() {
55        let bytes = [7, 0, 0, 0, 0, 0, 134, 66, 0, 31, 94, 71, 0, 179, 168, 199];
56        let (_type, _flag) = Decoder::get_type_and_flags(&bytes).unwrap();
57        let vector2 = Decoder::decode_vector3(&bytes).unwrap();
58        let value = GodotVector3 {
59            x: 67.0,
60            y: 56863.0,
61            z: -86374.0,
62        };
63
64        assert_eq!(
65            vector2, value,
66            "Expected value of {:?} but got {:?} instead",
67            value, vector2
68        );
69    }
70}