langis 0.1.0

A signal is a structure that can yield an infinite amount of data. The API is very similar to `std::iter::Iterator` but with the assumption that it will never end.
Documentation
//! This module contains signal generators.

use super::Signal;
use core::mem;

/// A signal that yields a constant value.
#[derive(Clone)]
pub struct Const<T> {
    pub(super) value: T,
}

impl<T: Clone> Signal for Const<T> {
    type Type = T;

    #[inline]
    fn next(&mut self) -> Self::Type {
        self.value.clone()
    }
}

/// A signal that returns the values a function.
#[derive(Clone)]
pub struct Gen<F> {
    pub(super) gen: F,
}

impl<F, T> Signal for Gen<F>
where
    F: FnMut() -> T,
{
    type Type = T;

    #[inline]
    fn next(&mut self) -> Self::Type {
        (self.gen)()
    }
}

/// A signal where each successive value is computed based on the preceding one.
#[derive(Clone)]
pub struct Successors<T, F> {
    pub(super) state: T,
    pub(super) successor: F,
}

impl<T, F> Signal for Successors<T, F>
where
    F: FnMut(&T) -> T,
{
    type Type = T;

    #[inline]
    fn next(&mut self) -> Self::Type {
        let next_state = (self.successor)(&self.state);
        mem::replace(&mut self.state, next_state)
    }
}

/// A signal that endlessly repeats the items of an iterator.
/// Calling `next` on this signal when the inner iterator always return `None` makes the
/// function panic.
pub struct Cycle<I> {
    pub(super) orig: I,
    pub(super) iter: I,
}

impl<I> Signal for Cycle<I>
where
    I: Iterator + Clone,
{
    type Type = I::Item;

    fn next(&mut self) -> Self::Type {
        match self.iter.next() {
            Some(item) => item,
            None => {
                self.iter = self.orig.clone();
                self.iter
                    .next()
                    .expect("The iterator always returns `None`")
            }
        }
    }
}