rw_parser_rs/utils/
byte_stream.rs1use std::io::{Cursor, Read, Seek, SeekFrom};
2use byteorder::{LittleEndian, ReadBytesExt};
3
4pub struct ByteStream<'a> {
5 cursor: Cursor<&'a [u8]>,
6}
7
8impl<'a> ByteStream<'a> {
9 pub fn new(stream: &'a [u8]) -> Self {
10 ByteStream {
11 cursor: Cursor::new(stream),
12 }
13 }
14
15 pub fn read_u8(&mut self) -> std::io::Result<u8> {
16 self.cursor.read_u8()
17 }
18
19 pub fn read_u16(&mut self) -> std::io::Result<u16> {
20 self.cursor.read_u16::<LittleEndian>()
21 }
22
23 pub fn read_u32(&mut self) -> std::io::Result<u32> {
24 self.cursor.read_u32::<LittleEndian>()
25 }
26
27 pub fn read_i16(&mut self) -> std::io::Result<i16> {
28 self.cursor.read_i16::<LittleEndian>()
29 }
30
31 pub fn read_i32(&mut self) -> std::io::Result<i32> {
32 self.cursor.read_i32::<LittleEndian>()
33 }
34
35 pub fn read_f32(&mut self) -> std::io::Result<f32> {
36 self.cursor.read_f32::<LittleEndian>()
37 }
38
39 pub fn read_string(&mut self, size: usize) -> std::io::Result<String> {
40 let mut buf = vec![0; size];
41 self.cursor.read_exact(&mut buf)?;
42 let pos = buf.iter().position(|&c| c == 0).unwrap_or(buf.len());
43 Ok(String::from_utf8_lossy(&buf[..pos]).to_string())
44 }
45
46 pub fn read(&mut self, size: usize) -> std::io::Result<Vec<u8>> {
47 let mut buf = vec![0; size];
48 self.cursor.read_exact(&mut buf)?;
49 Ok(buf)
50 }
51
52 pub fn get_size(&self) -> u64 {
53 self.cursor.get_ref().len() as u64
54 }
55
56 pub fn get_position(&self) -> u64 {
57 self.cursor.position()
58 }
59
60 pub fn set_position(&mut self, position: u64) {
61 self.cursor.set_position(position);
62 }
63
64 pub fn skip(&mut self, size: u64) -> std::io::Result<u64> {
65 self.cursor.seek(SeekFrom::Current(size as i64))
66 }
67}