1use std::string::FromUtf8Error;
2
3macro_rules! read_int {
4 ($t: ty, $p: expr, $buff: expr) => {{
5 let size = std::mem::size_of::<$t>();
6
7 let mut offset = 0;
8 let mut total: $t = 0;
9
10 for _ in 0..size {
11 total |= (read_byte($p, $buff) as $t) << offset;
12 offset += 8;
13 }
14
15 total
16 }};
17}
18
19pub(crate) use read_int;
20
21pub fn read_byte(p: &mut usize, buff: &[u8]) -> u8 {
22 let byte = buff[*p];
23 *p += 1;
24 byte
25}
26
27pub fn read_uleb(p: &mut usize, buff: &[u8]) -> usize {
28 let mut result = 0;
29 let mut shift: u8 = 0;
30
31 loop {
32 let byte = read_byte(p, buff) as usize;
33 result |= (byte & 0x7f) << shift;
34 shift += 7;
35 if byte & 0x80 == 0 {
36 break;
37 }
38 }
39
40 result
41}
42
43pub fn read_string(p: &mut usize, buff: &mut [u8]) -> Result<String, FromUtf8Error> {
44 let byte = read_byte(p, buff);
45
46 let mut string_length = 0;
47 if byte == 0x0b {
48 string_length = read_uleb(p, buff);
49 }
50
51 let start = *p;
52 let end = *p + string_length;
53 *p = end;
54
55 String::from_utf8(buff[start..end].to_vec())
56}