Skip to main content

nurtex_codec/types/basic/
string.rs

1use crate::types::variable::VarI32;
2use crate::{Buffer, read_bytes};
3
4impl Buffer for String {
5  fn read_buf(buffer: &mut std::io::Cursor<&[u8]>) -> Option<Self> {
6    let length = i32::read_var(buffer)? as u32;
7
8    if length > 32767 * 4 {
9      return None;
10    }
11
12    let buffer = read_bytes(buffer, length as usize)?;
13    let string = std::str::from_utf8(buffer).ok()?;
14
15    if string.len() > length as usize {
16      return None;
17    }
18
19    Some(string.to_string())
20  }
21
22  fn write_buf(&self, buffer: &mut impl std::io::Write) -> std::io::Result<()> {
23    let len = self.len();
24
25    if len > 32767 {
26      return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "string is too long"));
27    }
28
29    (len as i32).write_var(buffer)?;
30    buffer.write_all(self.as_bytes())?;
31
32    Ok(())
33  }
34}