physis/havok/
byte_reader.rs1use core::mem::size_of;
5
6#[derive(Clone)]
7pub struct ByteReader<'a> {
8 data: &'a [u8],
9 cursor: usize,
10}
11
12impl<'a> ByteReader<'a> {
13 pub fn new(data: &'a [u8]) -> Self {
14 Self { data, cursor: 0 }
15 }
16
17 pub fn read(&mut self) -> u8 {
18 let result = self.data[self.cursor];
19 self.cursor += 1;
20
21 result
22 }
23
24 pub fn read_u16_le(&mut self) -> u16 {
25 let result = u16::from_le_bytes([self.data[self.cursor], self.data[self.cursor + 1]]);
26 self.cursor += size_of::<u16>();
27
28 result
29 }
30
31 pub fn read_f32_le(&mut self) -> f32 {
32 let result = f32::from_le_bytes([
33 self.data[self.cursor],
34 self.data[self.cursor + 1],
35 self.data[self.cursor + 2],
36 self.data[self.cursor + 3],
37 ]);
38 self.cursor += size_of::<f32>();
39
40 result
41 }
42
43 pub fn read_bytes(&mut self, size: usize) -> &[u8] {
44 let result = &self.data[self.cursor..self.cursor + size];
45 self.cursor += size;
46
47 result
48 }
49
50 pub fn align(&mut self, align: usize) {
51 self.cursor = Self::round_up(self.cursor, align)
52 }
53
54 fn round_up(num_to_round: usize, multiple: usize) -> usize {
55 if multiple == 0 {
56 return num_to_round;
57 }
58
59 let remainder = num_to_round % multiple;
60 if remainder == 0 {
61 num_to_round
62 } else {
63 num_to_round + multiple - remainder
64 }
65 }
66
67 pub fn raw(&self) -> &[u8] {
68 &self.data[self.cursor..]
69 }
70
71 pub fn seek(&mut self, offset: usize) {
72 self.cursor += offset;
73 }
74}