typeward 0.5.2

A type-driven parser combinator library for Rust.
Documentation
/// Parses zero or more occurrences of `T` and returns them as a `Vec<T>`.
pub type Many0<T> = Vec<T>;

/// Parses one or more occurrences of `T`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Many1<T> {
    items: Vec<T>,
}

impl<T> Many1<T> {
    /// Returns the parsed items.
    #[must_use]
    pub fn items(&self) -> &[T] {
        &self.items
    }

    /// Returns the parsed items and consumes the wrapper.
    #[must_use]
    pub fn into_items(self) -> Vec<T> {
        self.items
    }

    #[must_use]
    /// Returns the number of parsed items.
    pub fn len(&self) -> usize {
        self.items.len()
    }

    #[must_use]
    /// Returns whether the collection is empty.
    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    #[must_use]
    #[allow(clippy::missing_panics_doc)]
    /// Returns the first parsed item.
    pub fn first(&self) -> &T {
        // Invariant: `Many1::parse_with_context` only constructs the value
        // after pushing the first successful item, so `items` is never empty.
        self.items
            .first()
            .expect("Many1 invariant: at least one item")
    }

    #[must_use]
    #[allow(clippy::missing_panics_doc)]
    /// Returns the last parsed item.
    pub fn last(&self) -> &T {
        self.items
            .last()
            .expect("Many1 invariant: at least one item")
    }

    /// Convert to the underlying `Vec<T>`.
    ///
    /// Guaranteed to be non-empty; prefer [`Self::into_items`] when semantic
    /// emphasis on the non-empty invariant is desirable.
    #[must_use]
    pub fn into_vec(self) -> Vec<T> {
        self.items
    }
}

impl<'a, I, T> crate::parse::Parse<'a, I> for Many1<T>
where
    I: crate::input::Input<'a>,
    T: crate::parse::Parse<'a, I>,
{
    #[inline]
    fn parse_with_context(
        input: I,
        context: &mut crate::parse::ParseOffsetContext,
    ) -> crate::error::ParseResult<(Self, I)> {
        let (first, mut rest) = T::parse_with_context(input, context)?;
        crate::collections::ensure_progress(input, rest, "Many1")?;
        let mut items = Vec::new();
        items.push(first);
        for res in crate::combinators::iter::iter::<I, T>(rest, context, "Many1") {
            let (item, new_rest) = match res {
                Ok((item, new_rest)) => (item, new_rest),
                Err(err) if err.is_fatal() => return Err(err),
                Err(_) => break,
            };
            items.push(item);
            rest = new_rest;
        }

        Ok((Many1 { items }, rest))
    }
}

impl<T, U> crate::parse::Unpack<Vec<U>> for Many1<T>
where
    T: crate::parse::Unpack<U>,
{
    #[inline]
    fn unpack(self) -> Vec<U> {
        self.items
            .into_iter()
            .map(crate::parse::Unpack::unpack)
            .collect()
    }
}

impl<T, U> crate::parse::Unpack<Many1<U>> for Many1<T>
where
    T: crate::parse::Unpack<U>,
{
    #[inline]
    fn unpack(self) -> Many1<U> {
        Many1 {
            items: self
                .items
                .into_iter()
                .map(crate::parse::Unpack::unpack)
                .collect(),
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::combinators::Ws;
    use crate::parse::{Parse, Unpack};

    use super::*;

    #[test]
    fn many0_collects_until_failure() {
        let (result, rest) = Many0::<char>::parse("abc123").unwrap();
        assert_eq!(result, ['a', 'b', 'c', '1', '2', '3']);
        assert_eq!(rest, "");
    }

    #[test]
    fn many1_requires_at_least_one_match() {
        let result = Many1::<i64>::parse("abc");
        assert!(result.is_err());
    }

    #[test]
    fn many0_rejects_non_consuming_parser() {
        let result = Many0::<()>::parse("input");
        assert!(result.is_err());
    }

    #[test]
    fn many1_rejects_non_consuming_parser() {
        let result = Many1::<()>::parse("input");
        assert!(result.is_err());
    }

    #[test]
    fn many1_unpacks_wrapped_items() {
        let (many, rest) = Many1::<Ws<i64>>::parse("1 2 3").unwrap();
        let many: Many1<i64> = many.unpack();
        assert_eq!(many.items(), [1, 2, 3]);
        assert_eq!(rest, "");
    }
}