xiaoai
xiaoai

Reputation: 1421

The remaining data returned by nom::bits::bits is incorrect

I am trying to take 7 bits from &[u8] vector using nom::bits::bits, but I found that the remaining data is incorrect, it seems it must be the integral multiple of 4/8, but I'm not sure. some code like this(nom = 5.12):

fn take_7_bits(i: &[u8]) -> IResult<&[u8], u32> {
    nom::bits::bits(nom::bits::complete::take::<_, _, _, (_, _)>(7_usize))(i)
}

fn main() {
    let input = vec![0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56, 0x78];
    println!("origin: {:X?}", &input);
    let (remain, data) = take_7_bits(&input).unwrap();
    println!("remain: {:X?}", remain);
    println!("data: {:08X}", data);

    let (remain2, data2) = take_7_bits(&remain).unwrap();
    println!("remain2: {:X?}", remain2);
    println!("data2: {:08X}", data2);
}

and the output:

origin: [AB, CD, EF, 12, 34, 56, 78]
remain: [CD, EF, 12, 34, 56, 78]
data: 00000055
remain2: [EF, 12, 34, 56, 78]
data2: 00000066

From the output, you can see the start of remaining data was aligned with the integral multiple of 4/8. so the second data2 is incorrect. Do I make any mistake in the code or miss something?

Upvotes: 0

Views: 163

Answers (1)

harmic
harmic

Reputation: 30597

In the documentation for bits, it says:

Afterwards, the input is converted back to a byte-level parser, with any remaining bits thrown away.

So, when you take 7 bits, the last bit is discarded and the remaining byte level data starts with the next complete byte.

Upvotes: 1

Related Questions