feat: add read_element function for raw bloc or field parsing

This commit is contained in:
Florian Briand 2024-07-30 15:53:19 +02:00
parent b8123306b7
commit dc6d41a1a2
Signed by: florian_briand
GPG Key ID: CC981B9E6B98E70B

View File

@ -54,6 +54,20 @@ pub fn read_element_size(bytes: &[u8]) -> Result<ElementSize, MemoryParsingError
Ok(element_size)
}
pub struct Element {
pub pad: usize,
pub contenu: Vec<u8>,
}
pub fn read_element(bytes: &[u8]) -> Element {
let ElementSize { size, pad } = read_element_size(bytes).unwrap();
let contenu = bytes[pad..pad+size].to_vec();
Element {
pad: pad+size,
contenu,
}
}
#[cfg(test)]
mod test_read_element_size {
use super::*;
@ -117,3 +131,35 @@ mod test_read_element_size {
);
}
}
#[cfg(test)]
mod test_read_element {
use super::*;
#[test]
fn short_size() {
let bytes = [51,
1, 48, 1, 56, 11, 57, 57, 55, 48, 48,
53, 50, 52, 49, 57, 52, 1, 52, 2, 50,
50, 17, 80, 72, 65, 82, 77, 65, 67, 73,
69, 78, 48, 48, 53, 50, 52, 49, 57, 9,
70, 82, 65, 78, 67, 79, 73, 83, 69, 1,
84,
];
let element = read_element(&bytes);
assert_eq!(element.pad, 52);
assert_eq!(element.contenu[..5], [1, 48, 1, 56, 11]);
}
#[test]
fn long_size() {
let mut bytes = vec![0b_1000_0010_u8,
0b_0000_0001_u8, 0b_0000_0000_u8, // size = 256
];
// Add 256 bytes to the content
bytes.append(&mut vec![1; 256]);
let element = read_element(&bytes);
assert_eq!(element.pad, 259);
assert_eq!(element.contenu.len(), 256);
}
}