godot_binary_serialization/decoder/
string.rs1use anyhow::anyhow;
2use byteorder::{ByteOrder, LittleEndian};
3
4use crate::types::primitive::GodotString;
5
6use super::Decoder;
7
8impl Decoder {
9 pub fn decode_string(bytes: &[u8]) -> anyhow::Result<GodotString> {
12 if bytes.len() < 8 {
13 return Err(anyhow!("Not enough bytes for a string"));
14 }
15
16 let length = LittleEndian::read_u32(&bytes[4..8]) as usize;
17 let pad = (4 - (length % 4)) % 4;
19
20 let total_length = 8 + length + pad;
21 if bytes.len() < total_length {
22 return Err(anyhow!("Amount of bytes does not match string length"));
23 }
24
25 let string = String::from_utf8(bytes[8..8 + length].to_vec())?;
26
27 Ok(GodotString {
28 value: string,
29 byte_size: total_length,
30 })
31 }
32}
33
34#[cfg(test)]
35mod tests {
36 use crate::decoder::Decoder;
37
38 #[test]
39 fn decode_string() {
40 let bytes: &[u8] = &[
41 4, 0, 0, 0, 10, 0, 0, 0, 98, 97, 110, 97, 110, 97, 66, 108, 111, 120, 0, 0,
42 ];
43 let (_type, _flag) = Decoder::get_type_and_flags(bytes).unwrap();
44 let string = Decoder::decode_string(bytes).unwrap();
45 let value = "bananaBlox";
46
47 assert_eq!(
48 string.value, value,
49 "Expected value of {} but got {} instead",
50 value, string.value
51 )
52 }
53}