rust-bakery / nom

Rust parser combinator framework
MIT License
9.35k stars 802 forks source link

nom::bits::complete::take panics when bit_offset >= 8 #1528

Open btielen opened 2 years ago

btielen commented 2 years ago

Thanks for all the work on this library. I encountered a panic while working with the nom::bits::complete::take function. One could argue that I am misusing the take-function, but it panics when the input bit_offset >= 8.

Environment

Test case

Example test case:

use nom::bits::complete::take;
use nom::IResult;

// Input is a tuple of (input: I, bit_offset: usize) (taken from documentation)
fn parser(input: (&[u8], usize), count: usize)-> IResult<(&[u8], usize), i64> {
    take(count)(input)
}

fn main() {
    let data: Vec<u8> = vec![0b10010110, 0b11010011];

    let result = parser((&data, 6), 4);    // doesn't panic
    let result = parser((&data, 12), 4);  // panics because 12 >= 8
}

results in

thread 'main' panicked at 'attempt to shift left with overflow', /home/(...)/.cargo/registry/src/github.com-1ecc6299db9ec823/nom-7.1.1/src/bits/complete.rs:65:14

complete.rs panics here

Stargateur commented 2 years ago

That panic is normal you break assumption of take() please use https://docs.rs/nom/latest/nom/bits/fn.bits.html when you want use bits API.

Thus, the fact user can too easily construct a tuple and send it to take is error prone, maybe nom need a have a opaque struct for bit api.