ufotofu 0.12.5

Abstractions for lazily consuming and producing sequences
Documentation
use core::convert::Infallible;
use core::fmt::Debug;

use crate::prelude::*;

/// A consumer that immediately returns a predetermined error on any operation.
///
/// <br/>Counterpart: the [`producer::ErrorImmediately`] type.
#[derive(Debug, Clone, Copy)]

pub struct ErrorImmediately<Err>(Option<Err>);

/// Creates a consumer that immediately returns a predetermined error on any operation.
///
/// ```
/// # use ufotofu::prelude::*;
/// use consumer::error_immediately;
/// # pollster::block_on(async {
///
/// let mut c = error_immediately(99);
/// assert_eq!(c.flush().await, Err(99));
/// # });
/// ```
///
/// <br/>Counterpart: the [producer::error_immediately] function.
pub fn error_immediately<Err>(err: Err) -> ErrorImmediately<Err> {
    ErrorImmediately(Some(err))
}

impl<Err> Consumer for ErrorImmediately<Err> {
    type Item = Infallible;
    type Final = Infallible;
    type Error = Err;

    async fn consume(&mut self, _val: Either<Self::Item, Self::Final>) -> Result<(), Self::Error> {
        Err(self
            .0
            .take()
            .expect("Must not call consume after having yielded an error"))
    }

    async fn flush(&mut self) -> Result<(), Self::Error> {
        Err(self
            .0
            .take()
            .expect("Must not call flush after having yielded an error"))
    }
}

impl<Err> BulkConsumer for ErrorImmediately<Err> {
    async fn expose_slots_gracefully<F, R>(&mut self, f: F) -> Result<R, (F, Self::Error)>
    where
        F: AsyncFnOnce(&mut [Self::Item]) -> (usize, R),
    {
        Err((
            f,
            self.0
                .take()
                .expect("Must not call expose_slots after having yielded an error"),
        ))
    }
}