ufotofu 0.12.5

Abstractions for lazily consuming and producing sequences
Documentation
//! Consumer functionality for types implementing the trait [`AsyncFnMut`].
//!
//! Specifically, this module provides a [`ClosureConsumer`] type which implements [`Consumer`] and wraps any [`AsyncFnMut<Args=(Either<Item, Final>,), Output=Result<(), Error>>`].
//!
//! <br/>Counterpart: the [`producer::compat::fn_mut`] module.

use crate::prelude::*;
use core::{marker::PhantomData, ops::AsyncFnMut};

/// A [`Consumer`] which [`consumes`](Consumer::consume) values by passing them as arguments to a wrapped [`AsyncFnMut`].
///
/// ```
/// use ufotofu::prelude::*;
/// use ufotofu::{pipe, PipeError};
/// use ufotofu::consumer::compat::fn_mut::*;
/// # pollster::block_on(async {
///
/// let mut result = 1u8;
///
/// let mut c: ClosureConsumer<_, u8, (), ()> = (async |item_or_final| {
///     match item_or_final {
///         Left(n) => {
///             result = result.checked_mul(n).ok_or(())?;
///             Ok(())
///         },
///         Right(()) => Ok(())
///     }
/// }).into();
///
/// let numbers = [1, 2, 3].into_producer();
///
/// pipe(numbers, c).await?;
///
/// assert_eq!(result, 6);
/// # Ok::<(), PipeError<Infallible, _>>(())
/// # });
/// ```
///
/// <br/>Counterpart: the [`ClosureProducer`](producer::compat::fn_mut::ClosureProducer) type.
pub struct ClosureConsumer<F, Item, Final, Error>
where
    F: AsyncFnMut(Either<Item, Final>) -> Result<(), Error>,
{
    inner: F,
    item: PhantomData<Item>,
    fin: PhantomData<Final>,
    err: PhantomData<Error>,
}

impl<F, Item, Final, Error> ClosureConsumer<F, Item, Final, Error>
where
    F: AsyncFnMut(Either<Item, Final>) -> Result<(), Error>,
{
    /// Constructs a new `ClosureConsumer` from the given [`AsyncFnMut`].
    pub fn new(inner: F) -> Self {
        ClosureConsumer {
            inner,
            item: PhantomData,
            fin: PhantomData,
            err: PhantomData,
        }
    }
}

impl<F, Item, Final, Error> From<F> for ClosureConsumer<F, Item, Final, Error>
where
    F: AsyncFnMut(Either<Item, Final>) -> Result<(), Error>,
{
    fn from(value: F) -> Self {
        Self::new(value)
    }
}

impl<F, Item, Final, Error> Consumer for ClosureConsumer<F, Item, Final, Error>
where
    F: AsyncFnMut(Either<Item, Final>) -> Result<(), Error>,
{
    type Item = Item;

    type Final = Final;

    type Error = Error;

    async fn consume(&mut self, val: Either<Self::Item, Self::Final>) -> Result<(), Self::Error> {
        (self.inner)(val).await
    }

    async fn flush(&mut self) -> Result<(), Self::Error> {
        Ok(())
    }
}