godot_binary_serialization/encoder/
int.rs1use byteorder::{ByteOrder, LittleEndian};
2
3use crate::types::{primitive::GodotInteger, SerializeFlag, GodotTypeIndex};
4
5use super::Encoder;
6
7impl Encoder {
8 pub fn encode_int(int: &GodotInteger) -> anyhow::Result<Vec<u8>> {
12 if int.value > i32::MAX as i64 || int.value < i32::MIN as i64 {
13 return Ok(Self::encode_int64(int.value));
14 }
15
16 Ok(Self::encode_int32(int.value as i32))
17 }
18
19 pub fn encode_int32(i: i32) -> Vec<u8> {
21 let bytes: &mut [u8] = &mut [0; 8];
22 LittleEndian::write_i16(&mut bytes[0..2], GodotTypeIndex::Integer as i16);
23 LittleEndian::write_i16(&mut bytes[2..4], SerializeFlag::None as i16);
24 LittleEndian::write_i32(&mut bytes[4..8], i);
25
26 bytes.to_vec()
27 }
28
29 pub fn encode_int64(i: i64) -> Vec<u8> {
31 let bytes: &mut [u8] = &mut [0; 12];
32 LittleEndian::write_i16(&mut bytes[0..2], GodotTypeIndex::Integer as i16);
33 LittleEndian::write_i16(&mut bytes[2..4], SerializeFlag::Bit64 as i16);
34 LittleEndian::write_i64(&mut bytes[4..12], i);
35
36 bytes.to_vec()
37 }
38}
39
40#[cfg(test)]
41mod tests {
42 use crate::{encoder::Encoder, types::primitive::GodotInteger};
43
44 #[test]
45 fn encode_int32() {
46 let expected_bytes = [2, 0, 0, 0, 80, 2, 0, 0].to_vec();
47 let value = GodotInteger::new_from_i32(592);
48 let bytes = Encoder::encode_int(&value).unwrap();
49
50 assert_eq!(
51 expected_bytes, bytes,
52 "Expected {:?} but got {:?}",
53 expected_bytes, bytes
54 );
55 }
56
57 #[test]
58 fn encode_int64() {
59 let expected_bytes = [2, 0, 1, 0, 107, 27, 152, 164, 225, 53, 0, 0].to_vec();
60 let value = GodotInteger::new_from_i64(59243245345643);
61 let bytes = Encoder::encode_int(&value).unwrap();
62
63 assert_eq!(
64 expected_bytes, bytes,
65 "Expected {:?} but got {:?}",
66 expected_bytes, bytes
67 );
68 }
69}