use core::{fmt, marker::PhantomData};
use crate::{Covar, FallibleLend, FallibleLender, FallibleLending, higher_order::FnMutHKAResOpt};
#[inline]
pub fn from_fn<St, E, F>(state: St, f: Covar<F>) -> FromFn<St, E, F>
where
F: for<'all> FnMutHKAResOpt<'all, &'all mut St, E>,
{
FromFn {
state,
f,
_marker: PhantomData,
}
}
#[derive(Clone)]
#[must_use = "lenders are lazy and do nothing unless consumed"]
pub struct FromFn<St, E, F> {
state: St,
f: Covar<F>,
_marker: PhantomData<fn() -> E>,
}
impl<St: fmt::Debug, E, F> fmt::Debug for FromFn<St, E, F> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("FromFallibleFn")
.field("state", &self.state)
.finish_non_exhaustive()
}
}
impl<'lend, St, E, F> FallibleLending<'lend> for FromFn<St, E, F>
where
F: for<'all> FnMutHKAResOpt<'all, &'all mut St, E>,
{
type Lend = <F as FnMutHKAResOpt<'lend, &'lend mut St, E>>::B;
}
impl<St, E, F> FallibleLender for FromFn<St, E, F>
where
F: for<'all> FnMutHKAResOpt<'all, &'all mut St, E>,
{
type Error = E;
crate::unsafe_assume_covariance_fallible!();
#[inline]
fn next(&mut self) -> Result<Option<FallibleLend<'_, Self>>, Self::Error> {
(self.f.as_inner_mut())(&mut self.state)
}
}