use std::fmt;
use std::mem;
pub struct RepeatCall<F> {
f: F,
}
impl<F> fmt::Debug for RepeatCall<F>
{
debug_fmt_fields!(RepeatCall, );
}
pub fn repeat_call<F>(function: F) -> RepeatCall<F> {
RepeatCall { f: function }
}
impl<A, F> Iterator for RepeatCall<F>
where F: FnMut() -> A
{
type Item = A;
#[inline]
fn next(&mut self) -> Option<A> {
Some((self.f)())
}
fn size_hint(&self) -> (usize, Option<usize>) {
(usize::max_value(), None)
}
}
pub fn unfold<A, St, F>(initial_state: St, f: F) -> Unfold<St, F>
where F: FnMut(&mut St) -> Option<A>
{
Unfold {
f: f,
state: initial_state,
}
}
impl<St, F> fmt::Debug for Unfold<St, F>
where St: fmt::Debug,
{
debug_fmt_fields!(Unfold, state);
}
#[derive(Clone)]
pub struct Unfold<St, F> {
f: F,
pub state: St,
}
impl<A, St, F> Iterator for Unfold<St, F>
where F: FnMut(&mut St) -> Option<A>
{
type Item = A;
#[inline]
fn next(&mut self) -> Option<A> {
(self.f)(&mut self.state)
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
(0, None)
}
}
#[derive(Clone)]
pub struct Iterate<St, F> {
state: St,
f: F,
}
impl<St, F> fmt::Debug for Iterate<St, F>
where St: fmt::Debug,
{
debug_fmt_fields!(Iterate, state);
}
impl<St, F> Iterator for Iterate<St, F>
where F: FnMut(&St) -> St
{
type Item = St;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
let next_state = (self.f)(&self.state);
Some(mem::replace(&mut self.state, next_state))
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
(usize::max_value(), None)
}
}
pub fn iterate<St, F>(initial_value: St, f: F) -> Iterate<St, F>
where F: FnMut(&St) -> St
{
Iterate {
state: initial_value,
f: f,
}
}