calc_rational 3.0.0

CLI calculator for rational numbers.
Documentation
/// Generalizes [`Iterator`] by allowing one to yield references.
pub trait LendingIterator {
    /// Read [`Iterator::Item`].
    type Item<'a>
    where
        Self: 'a;
    /// Read [`Iterator::next`].
    fn lend_next(&mut self) -> Option<Self::Item<'_>>;
    /// Read [`Iterator::size_hint`].
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, None)
    }
    /// Read [`Iterator::count`].
    #[expect(
        clippy::arithmetic_side_effects,
        reason = "must, and overflow is no worry"
    )]
    #[inline]
    fn count(self) -> usize
    where
        Self: Sized,
    {
        self.lend_fold(0, |count, _| count + 1)
    }
    /// Read [`Iterator::advance_by`].
    ///
    /// # Errors
    ///
    /// Read [`Iterator::advance_by`].
    #[inline]
    fn advance_by(&mut self, n: usize) -> Result<(), usize> {
        for i in 0..n {
            drop(self.lend_next().ok_or(i)?);
        }
        Ok(())
    }
    /// Read [`Iterator::by_ref`].
    #[inline]
    fn by_ref(&mut self) -> &mut Self
    where
        Self: Sized,
    {
        self
    }
    /// Read [`Iterator::try_fold`].
    /// # Errors
    ///
    /// Read [`Iterator::try_fold`].
    #[inline]
    fn lend_try_fold<B, E, F>(&mut self, init: B, mut f: F) -> Result<B, E>
    where
        Self: Sized,
        F: FnMut(B, Self::Item<'_>) -> Result<B, E>,
    {
        let mut accum = init;
        while let Some(x) = self.lend_next() {
            accum = f(accum, x)?;
        }
        Ok(accum)
    }
    /// Read [`Iterator::fold`].
    #[inline]
    fn lend_fold<B, F>(mut self, init: B, mut f: F) -> B
    where
        Self: Sized,
        F: FnMut(B, Self::Item<'_>) -> B,
    {
        let mut accum = init;
        while let Some(x) = self.lend_next() {
            accum = f(accum, x);
        }
        accum
    }
}
impl<T> LendingIterator for T
where
    T: Iterator,
{
    type Item<'a>
        = T::Item
    where
        Self: 'a;
    #[inline]
    fn lend_next(&mut self) -> Option<Self::Item<'_>> {
        self.next()
    }
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.size_hint()
    }
    #[inline]
    fn count(self) -> usize
    where
        Self: Sized,
    {
        self.count()
    }
    #[inline]
    fn advance_by(&mut self, n: usize) -> Result<(), usize> {
        for i in 0..n {
            drop(self.lend_next().ok_or(i)?);
        }
        Ok(())
    }
    #[inline]
    fn by_ref(&mut self) -> &mut Self
    where
        Self: Sized,
    {
        self
    }
    // Due to a bug in GATs, fold and try_fold cannot be
    // implemented.
}