godot_binary_serialization/encoder/
vector.rs1use byteorder::{ByteOrder, LittleEndian};
2
3use crate::types::{
4 structures::{GodotVector2, GodotVector3},
5 SerializeFlag, GodotTypeIndex,
6};
7
8use super::Encoder;
9
10impl Encoder {
11 pub fn encode_vector2(vec2: &GodotVector2) -> anyhow::Result<Vec<u8>> {
13 let bytes = &mut [0; 12];
14 LittleEndian::write_i16(&mut bytes[0..2], GodotTypeIndex::Vector2 as i16);
15 LittleEndian::write_i16(&mut bytes[2..4], SerializeFlag::None as i16);
16 LittleEndian::write_f32(&mut bytes[4..8], vec2.x);
17 LittleEndian::write_f32(&mut bytes[8..12], vec2.y);
18
19 Ok(bytes.to_vec())
20 }
21
22 pub fn encode_vector3(vec3: &GodotVector3) -> anyhow::Result<Vec<u8>> {
24 let bytes = &mut [0; 16];
25 LittleEndian::write_i16(&mut bytes[0..2], GodotTypeIndex::Vector3 as i16);
26 LittleEndian::write_i16(&mut bytes[2..4], SerializeFlag::None as i16);
27 LittleEndian::write_f32(&mut bytes[4..8], vec3.x);
28 LittleEndian::write_f32(&mut bytes[8..12], vec3.y);
29 LittleEndian::write_f32(&mut bytes[12..16], vec3.z);
30
31 Ok(bytes.to_vec())
32 }
33}
34
35#[cfg(test)]
36mod tests {
37 use crate::{
38 encoder::Encoder,
39 types::structures::{GodotVector2, GodotVector3},
40 };
41
42 #[test]
43 fn encode_vector2() {
44 let expected_bytes = [5, 0, 0, 0, 0, 0, 80, 66, 128, 162, 133, 71].to_vec();
45 let value = GodotVector2::new(52.0, 68421.0);
46 let bytes = Encoder::encode_vector2(&value).unwrap();
47
48 assert_eq!(
49 expected_bytes, bytes,
50 "Expected {:?} but got {:?}",
51 expected_bytes, bytes
52 );
53 }
54
55 #[test]
56 fn encode_vector3() {
57 let expected_bytes =
58 [7, 0, 0, 0, 0, 0, 80, 66, 128, 162, 133, 71, 224, 46, 14, 73].to_vec();
59 let value = GodotVector3::new(52.0, 68421.0, 582382.0);
60 let bytes = Encoder::encode_vector3(&value).unwrap();
61
62 assert_eq!(
63 expected_bytes, bytes,
64 "Expected {:?} but got {:?}",
65 expected_bytes, bytes
66 );
67 }
68}