Skip to content

Commit

Permalink
#1500: Add example for bits::complete::tag
Browse files Browse the repository at this point in the history
  • Loading branch information
Adam Chalmers committed Feb 18, 2022
1 parent e99f9e0 commit d28963b
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions src/bits/complete.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,49 @@ where
}

/// Generates a parser taking `count` bits and comparing them to `pattern`
///
/// # Example
/// ```rust
///
/// use nom::error::{Error, ErrorKind};
///
/// /// Compare the lowest `count` bits of `input` against the lowest `count` bits of `pattern`.
/// /// Return Ok and the matching section of `input` if there's a match.
/// /// Return Err if there's no match.
/// fn parser(pattern: u8, count: u8, input: (&[u8], usize)) -> nom::IResult<(&[u8], usize), u8> {
/// nom::bits::complete::tag(pattern, count)(input)
/// }
///
/// // The lowest 4 bits of 0x0f match the lowest 4 bits of 0xff (both are 1111).
/// assert_eq!(
/// parser(0x0f, 4, ([0xff].as_slice(), 0)),
/// Ok((([0xff].as_slice(), 4), 0x0f))
/// );
///
/// // The lowest bit of 0x0f matches the lowest bit of 0xff (both are 1).
/// assert_eq!(
/// parser(0x01, 1, ([0xff].as_slice(), 0)),
/// Ok((([0xff].as_slice(), 1), 0x01))
/// );
///
/// // The lowest 2 bits of 0xff and 0x01 are different.
/// assert_eq!(
/// parser(0x01, 2, ([0xff].as_slice(), 0)),
/// Err(nom::Err::Error(Error {
/// input: ([0xff].as_ref(), 0),
/// code: ErrorKind::TagBits
/// }))
/// );
///
/// // The lowest 8 bits of 0xff and 0xfe are different.
/// assert_eq!(
/// parser(0xfe, 8, ([0xff].as_slice(), 0)),
/// Err(nom::Err::Error(Error {
/// input: ([0xff].as_ref(), 0),
/// code: ErrorKind::TagBits
/// }))
/// );
/// ```
pub fn tag<I, O, C, E: ParseError<(I, usize)>>(
pattern: O,
count: C,
Expand Down

0 comments on commit d28963b

Please sign in to comment.