jam1garner / binrw

A Rust crate for helping parse and rebuild binary data using ✨macro magic✨.
https://binrw.rs
MIT License
545 stars 35 forks source link

Parsing unit enum variants tries to rewind on a `NoSeek` stream #215

Closed sigeryang closed 11 months ago

sigeryang commented 11 months ago

Minimal example:

use std::io::Cursor;

use binrw::{binrw, BinRead, BinWrite, BinReaderExt, BinWriterExt, io::NoSeek};

#[derive(Debug, Copy, Clone)]
#[binrw]
#[brw(big, repr = u32)]
enum Unit {
    A = 1,
    B = 2,
    C = 3,
}

fn main() {
    let cursor = Cursor::new(b"\0\0\0\0");
    let unit = Unit::read(&mut NoSeek::new(cursor)).unwrap();
    println!("{:?}", unit);
}

Output:

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: seek on unseekable file', src/main.rs:16:53
csnover commented 11 months ago

Thanks for your report!

In the given test case, the enumeration does not match the data, so parsing has failed. When this happens, the parser attempts to restore the position of the data stream so it is not left in an indeterminate state. This is expected behaviour. However, the original error should not be lost. I have added a patch to binrw to ensure the original error is retained when this happens, which should resolve this issue. Let me know if you have any questions about this.