Skip to content

Commit

Permalink
feat(parser): Add Parser::void
Browse files Browse the repository at this point in the history
  • Loading branch information
epage committed Feb 1, 2023
1 parent 18fa650 commit ad4b2d7
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/_cookbook.rs
Expand Up @@ -70,7 +70,7 @@
//! pub fn peol_comment<'a, E: ParseError<&'a str>>(i: &'a str) -> IResult<&'a str, (), E>
//! {
//! pair('%', take_till1("\n\r"))
//! .value(()) // Output is thrown away.
//! .void() // Output is thrown away.
//! .parse_next(i)
//! }
//! ```
Expand All @@ -93,7 +93,7 @@
//! take_until("*)"),
//! "*)"
//! )
//! .value(()) // Output is thrown away.
//! .void() // Output is thrown away.
//! .parse_next(i)
//! }
//! ```
Expand Down
22 changes: 22 additions & 0 deletions src/combinator/mod.rs
Expand Up @@ -947,6 +947,28 @@ impl<I, O1, O2: Clone, E: ParseError<I>, F: Parser<I, O1, E>> Parser<I, O2, E>
}
}

/// Implementation of [`Parser::void`]
#[cfg_attr(nightly, warn(rustdoc::missing_doc_code_examples))]
pub struct Void<F, O> {
parser: F,
phantom: core::marker::PhantomData<O>,
}

impl<F, O> Void<F, O> {
pub(crate) fn new(parser: F) -> Self {
Self {
parser,
phantom: Default::default(),
}
}
}

impl<I, O, E: ParseError<I>, F: Parser<I, O, E>> Parser<I, (), E> for Void<F, O> {
fn parse_next(&mut self, input: I) -> IResult<I, (), E> {
(self.parser).parse_next(input).map(|(i, _)| (i, ()))
}
}

/// Succeeds if the child parser returns an error.
///
/// ```rust
Expand Down
23 changes: 23 additions & 0 deletions src/parser.rs
Expand Up @@ -392,6 +392,7 @@ pub trait Parser<I, O, E> {
{
ByRef::new(self)
}

/// Returns the provided value if the child parser succeeds.
///
/// # Example
Expand All @@ -415,6 +416,28 @@ pub trait Parser<I, O, E> {
Value::new(self, val)
}

/// Discards the output of the `Parser`
///
/// # Example
///
/// ```rust
/// # use winnow::{Err,error::ErrorKind, error::Error, IResult, Parser};
/// use winnow::character::alpha1;
/// # fn main() {
///
/// let mut parser = alpha1.void();
///
/// assert_eq!(parser.parse_next("abcd"), Ok(("", ())));
/// assert_eq!(parser.parse_next("123abcd;"), Err(Err::Error(Error::new("123abcd;", ErrorKind::Alpha))));
/// # }
/// ```
fn void(self) -> Void<Self, O>
where
Self: core::marker::Sized,
{
Void::new(self)
}

/// Convert the parser's output to another type using [`std::convert::From`]
///
/// # Example
Expand Down

0 comments on commit ad4b2d7

Please sign in to comment.