/// Generates a parser taking `count` bits /// /// # Example /// ```rust /// # use nom::bits::complete::take; /// # use nom::IResult; /// # use nom::error::{Error, ErrorKind}; /// // Input is a tuple of (input: I, bit_offset: usize) /// fn parser(input: (&[u8], usize), count: usize)-> IResult<(&[u8], usize), u8> { /// take(count)(input) /// } /// /// // Consumes 0 bits, returns 0 /// assert_eq!(parser(([0b00010010].as_ref(), 0), 0), Ok((([0b00010010].as_ref(), 0), 0))); /// /// // Consumes 4 bits, returns their values and increase offset to 4 /// assert_eq!(parser(([0b00010010].as_ref(), 0), 4), Ok((([0b00010010].as_ref(), 4), 0b00000001))); /// /// // Consumes 4 bits, offset is 4, returns their values and increase offset to 0 of next byte /// assert_eq!(parser(([0b00010010].as_ref(), 4), 4), Ok((([].as_ref(), 0), 0b00000010))); /// /// // Tries to consume 12 bits but only 8 are available /// assert_eq!(parser(([0b00010010].as_ref(), 0), 12), Err(nom::Err::Error(Error{input: ([0b00010010].as_ref(), 0), code: ErrorKind::Eof }))); /// ``` pubfn take<I, O, C, E: ParseError<(I, usize)>>(
count: C,
) -> implFn((I, usize)) -> IResult<(I, usize), O, E> where
I: Slice<RangeFrom<usize>> + InputIter<Item = u8> + InputLength,
C: ToUsize,
O: From<u8> + AddAssign + Shl<usize, Output = O> + Shr<usize, Output = O>,
{ let count = count.to_usize(); move |(input, bit_offset): (I, usize)| { if count == 0 {
Ok(((input, bit_offset), 0u8.into()))
} else { let cnt = (count + bit_offset).div(8); if input.input_len() * 8 < count + bit_offset {
Err(Err::Error(E::from_error_kind(
(input, bit_offset),
ErrorKind::Eof,
)))
} else { letmut acc: O = 0_u8.into(); letmut offset: usize = bit_offset; letmut remaining: usize = count; letmut end_offset: usize = 0;
for byte in input.iter_elements().take(cnt + 1) { if remaining == 0 { break;
} let val: O = if offset == 0 {
byte.into()
} else {
((byte << offset) as u8 >> offset).into()
};
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.