16855e09eSopenharmony_ci//! Bit level parsers
26855e09eSopenharmony_ci//!
36855e09eSopenharmony_ci
46855e09eSopenharmony_cipub mod complete;
56855e09eSopenharmony_cipub mod streaming;
66855e09eSopenharmony_ci
76855e09eSopenharmony_ciuse crate::error::{ErrorKind, ParseError};
86855e09eSopenharmony_ciuse crate::internal::{Err, IResult, Needed, Parser};
96855e09eSopenharmony_ciuse crate::lib::std::ops::RangeFrom;
106855e09eSopenharmony_ciuse crate::traits::{ErrorConvert, Slice};
116855e09eSopenharmony_ci
126855e09eSopenharmony_ci/// Converts a byte-level input to a bit-level input, for consumption by a parser that uses bits.
136855e09eSopenharmony_ci///
146855e09eSopenharmony_ci/// Afterwards, the input is converted back to a byte-level parser, with any remaining bits thrown
156855e09eSopenharmony_ci/// away.
166855e09eSopenharmony_ci///
176855e09eSopenharmony_ci/// # Example
186855e09eSopenharmony_ci/// ```
196855e09eSopenharmony_ci/// use nom::bits::{bits, streaming::take};
206855e09eSopenharmony_ci/// use nom::error::Error;
216855e09eSopenharmony_ci/// use nom::sequence::tuple;
226855e09eSopenharmony_ci/// use nom::IResult;
236855e09eSopenharmony_ci///
246855e09eSopenharmony_ci/// fn parse(input: &[u8]) -> IResult<&[u8], (u8, u8)> {
256855e09eSopenharmony_ci///     bits::<_, _, Error<(&[u8], usize)>, _, _>(tuple((take(4usize), take(8usize))))(input)
266855e09eSopenharmony_ci/// }
276855e09eSopenharmony_ci///
286855e09eSopenharmony_ci/// let input = &[0x12, 0x34, 0xff, 0xff];
296855e09eSopenharmony_ci///
306855e09eSopenharmony_ci/// let output = parse(input).expect("We take 1.5 bytes and the input is longer than 2 bytes");
316855e09eSopenharmony_ci///
326855e09eSopenharmony_ci/// // The first byte is consumed, the second byte is partially consumed and dropped.
336855e09eSopenharmony_ci/// let remaining = output.0;
346855e09eSopenharmony_ci/// assert_eq!(remaining, [0xff, 0xff]);
356855e09eSopenharmony_ci///
366855e09eSopenharmony_ci/// let parsed = output.1;
376855e09eSopenharmony_ci/// assert_eq!(parsed.0, 0x01);
386855e09eSopenharmony_ci/// assert_eq!(parsed.1, 0x23);
396855e09eSopenharmony_ci/// ```
406855e09eSopenharmony_cipub fn bits<I, O, E1, E2, P>(mut parser: P) -> impl FnMut(I) -> IResult<I, O, E2>
416855e09eSopenharmony_ciwhere
426855e09eSopenharmony_ci  E1: ParseError<(I, usize)> + ErrorConvert<E2>,
436855e09eSopenharmony_ci  E2: ParseError<I>,
446855e09eSopenharmony_ci  I: Slice<RangeFrom<usize>>,
456855e09eSopenharmony_ci  P: Parser<(I, usize), O, E1>,
466855e09eSopenharmony_ci{
476855e09eSopenharmony_ci  move |input: I| match parser.parse((input, 0)) {
486855e09eSopenharmony_ci    Ok(((rest, offset), result)) => {
496855e09eSopenharmony_ci      // If the next byte has been partially read, it will be sliced away as well.
506855e09eSopenharmony_ci      // The parser functions might already slice away all fully read bytes.
516855e09eSopenharmony_ci      // That's why `offset / 8` isn't necessarily needed at all times.
526855e09eSopenharmony_ci      let remaining_bytes_index = offset / 8 + if offset % 8 == 0 { 0 } else { 1 };
536855e09eSopenharmony_ci      Ok((rest.slice(remaining_bytes_index..), result))
546855e09eSopenharmony_ci    }
556855e09eSopenharmony_ci    Err(Err::Incomplete(n)) => Err(Err::Incomplete(n.map(|u| u.get() / 8 + 1))),
566855e09eSopenharmony_ci    Err(Err::Error(e)) => Err(Err::Error(e.convert())),
576855e09eSopenharmony_ci    Err(Err::Failure(e)) => Err(Err::Failure(e.convert())),
586855e09eSopenharmony_ci  }
596855e09eSopenharmony_ci}
606855e09eSopenharmony_ci
616855e09eSopenharmony_ci/// Counterpart to `bits`, `bytes` transforms its bit stream input into a byte slice for the underlying
626855e09eSopenharmony_ci/// parser, allowing byte-slice parsers to work on bit streams.
636855e09eSopenharmony_ci///
646855e09eSopenharmony_ci/// A partial byte remaining in the input will be ignored and the given parser will start parsing
656855e09eSopenharmony_ci/// at the next full byte.
666855e09eSopenharmony_ci///
676855e09eSopenharmony_ci/// ```
686855e09eSopenharmony_ci/// use nom::bits::{bits, bytes, streaming::take};
696855e09eSopenharmony_ci/// use nom::combinator::rest;
706855e09eSopenharmony_ci/// use nom::error::Error;
716855e09eSopenharmony_ci/// use nom::sequence::tuple;
726855e09eSopenharmony_ci/// use nom::IResult;
736855e09eSopenharmony_ci///
746855e09eSopenharmony_ci/// fn parse(input: &[u8]) -> IResult<&[u8], (u8, u8, &[u8])> {
756855e09eSopenharmony_ci///   bits::<_, _, Error<(&[u8], usize)>, _, _>(tuple((
766855e09eSopenharmony_ci///     take(4usize),
776855e09eSopenharmony_ci///     take(8usize),
786855e09eSopenharmony_ci///     bytes::<_, _, Error<&[u8]>, _, _>(rest)
796855e09eSopenharmony_ci///   )))(input)
806855e09eSopenharmony_ci/// }
816855e09eSopenharmony_ci///
826855e09eSopenharmony_ci/// let input = &[0x12, 0x34, 0xff, 0xff];
836855e09eSopenharmony_ci///
846855e09eSopenharmony_ci/// assert_eq!(parse( input ), Ok(( &[][..], (0x01, 0x23, &[0xff, 0xff][..]) )));
856855e09eSopenharmony_ci/// ```
866855e09eSopenharmony_cipub fn bytes<I, O, E1, E2, P>(mut parser: P) -> impl FnMut((I, usize)) -> IResult<(I, usize), O, E2>
876855e09eSopenharmony_ciwhere
886855e09eSopenharmony_ci  E1: ParseError<I> + ErrorConvert<E2>,
896855e09eSopenharmony_ci  E2: ParseError<(I, usize)>,
906855e09eSopenharmony_ci  I: Slice<RangeFrom<usize>> + Clone,
916855e09eSopenharmony_ci  P: Parser<I, O, E1>,
926855e09eSopenharmony_ci{
936855e09eSopenharmony_ci  move |(input, offset): (I, usize)| {
946855e09eSopenharmony_ci    let inner = if offset % 8 != 0 {
956855e09eSopenharmony_ci      input.slice((1 + offset / 8)..)
966855e09eSopenharmony_ci    } else {
976855e09eSopenharmony_ci      input.slice((offset / 8)..)
986855e09eSopenharmony_ci    };
996855e09eSopenharmony_ci    let i = (input, offset);
1006855e09eSopenharmony_ci    match parser.parse(inner) {
1016855e09eSopenharmony_ci      Ok((rest, res)) => Ok(((rest, 0), res)),
1026855e09eSopenharmony_ci      Err(Err::Incomplete(Needed::Unknown)) => Err(Err::Incomplete(Needed::Unknown)),
1036855e09eSopenharmony_ci      Err(Err::Incomplete(Needed::Size(sz))) => Err(match sz.get().checked_mul(8) {
1046855e09eSopenharmony_ci        Some(v) => Err::Incomplete(Needed::new(v)),
1056855e09eSopenharmony_ci        None => Err::Failure(E2::from_error_kind(i, ErrorKind::TooLarge)),
1066855e09eSopenharmony_ci      }),
1076855e09eSopenharmony_ci      Err(Err::Error(e)) => Err(Err::Error(e.convert())),
1086855e09eSopenharmony_ci      Err(Err::Failure(e)) => Err(Err::Failure(e.convert())),
1096855e09eSopenharmony_ci    }
1106855e09eSopenharmony_ci  }
1116855e09eSopenharmony_ci}
1126855e09eSopenharmony_ci
1136855e09eSopenharmony_ci#[cfg(test)]
1146855e09eSopenharmony_cimod test {
1156855e09eSopenharmony_ci  use super::*;
1166855e09eSopenharmony_ci  use crate::bits::streaming::take;
1176855e09eSopenharmony_ci  use crate::error::Error;
1186855e09eSopenharmony_ci  use crate::sequence::tuple;
1196855e09eSopenharmony_ci
1206855e09eSopenharmony_ci  #[test]
1216855e09eSopenharmony_ci  /// Take the `bits` function and assert that remaining bytes are correctly returned, if the
1226855e09eSopenharmony_ci  /// previous bytes are fully consumed
1236855e09eSopenharmony_ci  fn test_complete_byte_consumption_bits() {
1246855e09eSopenharmony_ci    let input = &[0x12, 0x34, 0x56, 0x78];
1256855e09eSopenharmony_ci
1266855e09eSopenharmony_ci    // Take 3 bit slices with sizes [4, 8, 4].
1276855e09eSopenharmony_ci    let result: IResult<&[u8], (u8, u8, u8)> =
1286855e09eSopenharmony_ci      bits::<_, _, Error<(&[u8], usize)>, _, _>(tuple((take(4usize), take(8usize), take(4usize))))(
1296855e09eSopenharmony_ci        input,
1306855e09eSopenharmony_ci      );
1316855e09eSopenharmony_ci
1326855e09eSopenharmony_ci    let output = result.expect("We take 2 bytes and the input is longer than 2 bytes");
1336855e09eSopenharmony_ci
1346855e09eSopenharmony_ci    let remaining = output.0;
1356855e09eSopenharmony_ci    assert_eq!(remaining, [0x56, 0x78]);
1366855e09eSopenharmony_ci
1376855e09eSopenharmony_ci    let parsed = output.1;
1386855e09eSopenharmony_ci    assert_eq!(parsed.0, 0x01);
1396855e09eSopenharmony_ci    assert_eq!(parsed.1, 0x23);
1406855e09eSopenharmony_ci    assert_eq!(parsed.2, 0x04);
1416855e09eSopenharmony_ci  }
1426855e09eSopenharmony_ci
1436855e09eSopenharmony_ci  #[test]
1446855e09eSopenharmony_ci  /// Take the `bits` function and assert that remaining bytes are correctly returned, if the
1456855e09eSopenharmony_ci  /// previous bytes are NOT fully consumed. Partially consumed bytes are supposed to be dropped.
1466855e09eSopenharmony_ci  /// I.e. if we consume 1.5 bytes of 4 bytes, 2 bytes will be returned, bits 13-16 will be
1476855e09eSopenharmony_ci  /// dropped.
1486855e09eSopenharmony_ci  fn test_partial_byte_consumption_bits() {
1496855e09eSopenharmony_ci    let input = &[0x12, 0x34, 0x56, 0x78];
1506855e09eSopenharmony_ci
1516855e09eSopenharmony_ci    // Take bit slices with sizes [4, 8].
1526855e09eSopenharmony_ci    let result: IResult<&[u8], (u8, u8)> =
1536855e09eSopenharmony_ci      bits::<_, _, Error<(&[u8], usize)>, _, _>(tuple((take(4usize), take(8usize))))(input);
1546855e09eSopenharmony_ci
1556855e09eSopenharmony_ci    let output = result.expect("We take 1.5 bytes and the input is longer than 2 bytes");
1566855e09eSopenharmony_ci
1576855e09eSopenharmony_ci    let remaining = output.0;
1586855e09eSopenharmony_ci    assert_eq!(remaining, [0x56, 0x78]);
1596855e09eSopenharmony_ci
1606855e09eSopenharmony_ci    let parsed = output.1;
1616855e09eSopenharmony_ci    assert_eq!(parsed.0, 0x01);
1626855e09eSopenharmony_ci    assert_eq!(parsed.1, 0x23);
1636855e09eSopenharmony_ci  }
1646855e09eSopenharmony_ci
1656855e09eSopenharmony_ci  #[test]
1666855e09eSopenharmony_ci  #[cfg(feature = "std")]
1676855e09eSopenharmony_ci  /// Ensure that in Incomplete error is thrown, if too few bytes are passed for a given parser.
1686855e09eSopenharmony_ci  fn test_incomplete_bits() {
1696855e09eSopenharmony_ci    let input = &[0x12];
1706855e09eSopenharmony_ci
1716855e09eSopenharmony_ci    // Take bit slices with sizes [4, 8].
1726855e09eSopenharmony_ci    let result: IResult<&[u8], (u8, u8)> =
1736855e09eSopenharmony_ci      bits::<_, _, Error<(&[u8], usize)>, _, _>(tuple((take(4usize), take(8usize))))(input);
1746855e09eSopenharmony_ci
1756855e09eSopenharmony_ci    assert!(result.is_err());
1766855e09eSopenharmony_ci    let error = result.err().unwrap();
1776855e09eSopenharmony_ci    assert_eq!("Parsing requires 2 bytes/chars", error.to_string());
1786855e09eSopenharmony_ci  }
1796855e09eSopenharmony_ci}
180