nom icon indicating copy to clipboard operation
nom copied to clipboard

Parsing flags from bitstream

Open w1ll-i-code opened this issue 2 years ago • 0 comments

Feature request:

Hello, I want to parse some bit flags from a bit stream. I know I could do that with bit masks, but with nom it seems clearer and the error handling comes for free. It would also improve the ergonomics for parsing binary formats in general in my opinion.

I propose to add a new function nom::bits::*::bool that takes exactly one bit from the bitstream and transforms it into a bool. If I can have an opinion if this would be useful, I will implement it myself, document it and open a PR for it, so it is no hustle for you.

System Information

  • Rust version : 1.61.0
  • nom version : 7.11
  • nom compilation features used: default

Test case

use nom::bits::{ bits, streaming::{tag, bool} };
use nom::error::Error;
use nom::sequence::tuple;
use nom::IResult;

fn parse(input: &[u8]) -> IResult<&[u8], (u8, bool)> {
    bits::<_, _, Error<(&[u8], usize)>, _, _>(tuple((tag(0, 2usize), bool)))(input)
}

#[test]
fn parse_flag_from_bitstream() {
    let input = 0b00100000u32.to_le_bytes();
    let (remaining, parsed) = parse(&input).expect("We only take three bits, so this is save.");

    assert_eq!(remaining, &[0x00, 0x00, 0x00]);
    assert_eq!(parsed, (0x00, true));
}

w1ll-i-code avatar Jun 28 '22 18:06 w1ll-i-code