Skip to main content

nbs/
io.rs

1use crate::error::NbsError;
2use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
3use std::io;
4
5pub trait ReadStringExt: ReadBytesExt {
6    fn read_string(&mut self) -> Result<String, NbsError> {
7        let len = self.read_i32::<LittleEndian>()?;
8        let mut buffer: Vec<u8> = Vec::with_capacity(len as usize);
9        buffer.resize(len as usize, 0u8);
10        self.read_exact(&mut buffer)?;
11        Ok(String::from_utf8(buffer)?)
12    }
13}
14
15pub trait WriteStringExt: WriteBytesExt {
16    fn write_string(&mut self, s: &str) -> io::Result<()> {
17        self.write_i32::<LittleEndian>(s.len() as i32)?;
18        self.write_all(s.as_bytes())?;
19        Ok(())
20    }
21}
22
23impl<R> ReadStringExt for R where R: ReadBytesExt {}
24impl<W> WriteStringExt for W where W: WriteBytesExt {}