-
Hi, I was struggled with binary parsing, and this library looks awesome. We have somewhat non standard binary layout and am looking for the API that I can use of. Binary layout like below
As you can see, I was trying to implement #[derive(BinRead)]
pub struct Header {
code_size: u32,
data_size: u32,
}
#[derive(BinRead)]
pub struct Program {
#[br(count = ?)] # This size should be decided via Header (code_size)
code: Vec<u8>,
#[br(count = ?)] # This size should be decided via Header (data_size)
data: Vec<u8>,
}
#[derive(BinRead)]
pub struct Metadata {
count: u64,
#[br(count = count)]
headers: Vec<Header>,
#[br(count = count)]
programs: Vec<Program>,
} but did not find any way to pass length information from Thanks |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
Hi, Probably you will want to write and use a helper function that creates the programs field from an iterator of #[derive(BinRead, Clone, Copy)]
pub struct Header {
code_size: u32,
data_size: u32,
}
#[derive(BinRead)]
#[br(import_raw(header: Header))]
struct Program {
#[br(count = header.code_size)]
code: Vec<u8>,
#[br(count = header.data_size)]
data: Vec<u8>,
}
#[derive(BinRead)]
struct Metadata {
count: u64,
#[br(count = count)]
headers: Vec<Header>,
#[br(parse_with = from_iterator_args(headers.iter()))]
programs: Vec<Program>,
}
fn from_iterator_args<'it, R, T, Arg, Ret, It>(it: It) -> impl FnOnce(&mut R, &ReadOptions, ()) -> BinResult<Ret>
where
T: BinRead<Args = Arg>,
R: Read + Seek,
Arg: Clone + 'static,
Ret: FromIterator<T> + 'static,
It: Iterator<Item = &'it Arg> + 'it,
{
move |reader, options, _| {
it.map(|arg| T::read_options(reader, options, arg.clone())).collect()
}
} The arguments need to be cloned instead of passed by reference because binrw hasn’t yet implemented GATs for the associated This is probably a sufficiently common pattern that it makes sense to add something like this helper to the library in the future, but in the meantime I think this should do what you need. |
Beta Was this translation helpful? Give feedback.
Hi,
Probably you will want to write and use a helper function that creates the programs field from an iterator of
Header
values: