typeward 0.4.0

A type-driven parser combinator library for Rust.
Documentation
/// Succeeds only when `P` fails, then parses and returns `S`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Not<P, S = &'static str> {
    value: S,
    _marker: std::marker::PhantomData<P>,
}

impl<'a, I, S, P> crate::parse::Parse<'a, I> for Not<P, S>
where
    I: crate::input::Input<'a>,
    S: crate::parse::Parse<'a, I>,
    P: crate::parse::Parse<'a, I>,
{
    #[inline]
    fn parse_with_context(
        input: I,
        context: &mut crate::parse::ParseOffsetContext,
    ) -> crate::error::ParseResult<(Self, I)> {
        match P::parse_with_context(input, context) {
            Ok(_) => {
                let preview = crate::error::preview_input(
                    input.display().as_ref(),
                    crate::error::DEFAULT_INPUT_PREVIEW,
                );
                return Err(crate::error::ParseError::custom(format!(
                    "expected `{}` but matched the forbidden pattern `{}` at '{}'",
                    std::any::type_name::<S>(),
                    std::any::type_name::<P>(),
                    preview,
                )));
            }
            Err(err) if err.is_fatal() => return Err(err),
            Err(_) => {}
        }

        let (value, rest) = S::parse_with_context(input, context)?;
        Ok((
            Not {
                value,
                _marker: std::marker::PhantomData,
            },
            rest,
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{parse::Parse, primitives::prelude::*};

    #[test]
    fn test_not() {
        let input = "42";
        let (result, rest) = Not::<Alpha>::parse(input).unwrap();
        assert_eq!(result.value, "42");
        assert_eq!(rest, "");
    }

    #[test]
    fn test_not_fail() {
        let input = "123";
        let err = Not::<i64, AlphaNum>::parse(input);
        assert!(err.is_err());
    }

    #[test]
    fn test_not_propagates_fatal_lookahead_errors() {
        type Parser<'a> = Not<i64, crate::primitives::basic::Rest<&'a [u8]>>;

        let bytes: &[u8] = &[0xFF, b'a'];
        let err = Parser::parse(bytes).unwrap_err();

        assert!(err.is_fatal());
        assert!(err.to_string().contains("invalid UTF-8 input"));
    }
}