godot_binary_serialization/encoder/
string.rs

1use byteorder::{ByteOrder, LittleEndian};
2
3use crate::types::{primitive::GodotString, SerializeFlag, GodotTypeIndex};
4
5use super::Encoder;
6
7impl Encoder {
8    /// Encodes a Godot String into bytes
9    pub fn encode_string(string: &GodotString) -> anyhow::Result<Vec<u8>> {
10        Ok(Self::encode_owned_string(string.value.clone()))
11    }
12
13    /// Encodes an owned String into bytes
14    pub fn encode_owned_string(string: String) -> Vec<u8> {
15        let length = string.len();
16        let pad = (4 - (length % 4)) % 4;
17        let total_length = 8 + length + pad;
18        let mut bytes = vec![0; total_length];
19
20        LittleEndian::write_i16(&mut bytes[0..2], GodotTypeIndex::String as i16);
21        LittleEndian::write_i16(&mut bytes[2..4], SerializeFlag::None as i16);
22        LittleEndian::write_i32(&mut bytes[4..8], length as i32);
23        bytes[8..8 + length].copy_from_slice(string.as_bytes());
24
25        bytes
26    }
27
28    /// Encodes a str into bytes
29    pub fn encode_str(string: &str) -> Vec<u8> {
30        Self::encode_owned_string(string.to_owned())
31    }
32}
33
34#[cfg(test)]
35mod tests {
36    use crate::{encoder::Encoder, types::primitive::GodotString};
37
38    #[test]
39    fn encode_string() {
40        let expected_bytes = [
41            4, 0, 0, 0, 10, 0, 0, 0, 98, 97, 110, 97, 110, 97, 66, 108, 111, 120, 0, 0,
42        ]
43        .to_vec();
44        let value = GodotString::new("bananaBlox");
45        let bytes = Encoder::encode_string(&value).unwrap();
46
47        assert_eq!(
48            expected_bytes, bytes,
49            "Expected {:?} but got {:?}",
50            expected_bytes, bytes
51        );
52    }
53}