Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
pub trait InternalIterator {
type Item;
fn each<F>(&mut self, mut f: F) -> bool
where F: FnMut(Self::Item) -> bool;
}
impl<I> InternalIterator for I
where I: Iterator,
{
type Item = I::Item;
fn each<F>(&mut self, f: F) -> bool
where F: FnMut(Self::Item) -> bool
{
self.all(f)
}
}
#[derive(Clone)]
pub struct FlatMap<I, U: InternalIterator, F> {
iter: I,
f: F,
frontiter: Option<U>,
backiter: Option<U>,
}
impl<I, U, F> InternalIterator for FlatMap<I, U, F>
where I: InternalIterator,
U: InternalIterator,
F: FnMut(I::Item) -> U,
{
type Item = U::Item;
fn each<G>(&mut self, mut g: G) -> bool
where G: FnMut(Self::Item) -> bool
{
if let Some(ref mut inner) = self.frontiter {
inner.each(&mut g) || return false;
}
let FlatMap { ref mut iter, ref mut f, ref mut frontiter, .. } = *self;
iter.each(|front| {
let mut iter = f(front);
iter.each(&mut g) || { *frontiter = Some(iter); false }
}) || return false;
*frontiter = None;
if let Some(ref mut inner) = self.backiter {
inner.each(&mut g) || return false;
}
true
}
}
#[derive(Clone)]
pub struct Filter<I, P> {
iter: I,
predicate: P,
}
impl<I, P> InternalIterator for Filter<I, P>
where I: InternalIterator,
P: FnMut(&I::Item) -> bool
{
type Item = I::Item;
fn each<F>(&mut self, mut f: F) -> bool
where F: FnMut(Self::Item) -> bool
{
let Filter { ref mut iter, ref mut predicate } = *self;
iter.each(|elem| !predicate(&elem) || f(elem))
}
}
fn flat_map<I, U, F>(iter: I, f: F) -> FlatMap<I, U, F>
where I: InternalIterator,
U: InternalIterator,
F: FnMut(I::Item) -> U,
{
FlatMap { iter: iter, f: f, frontiter: None, backiter: None }
}
fn filter<I, P>(iter: I, predicate: P) -> Filter<I, P>
where I: InternalIterator,
P: FnMut(&I::Item) -> bool,
{
Filter { iter: iter, predicate: predicate }
}
pub fn math_internal_u32(big: u32) -> u32 {
let mut iter = filter(flat_map(0..big, |x| (0..x)), |x| x % 16 < 4);
let mut maths = 0;
iter.each(|x| { maths += x; true });
maths
}
pub fn math_internal_u64(big: u64) -> u64 {
let mut iter = filter(flat_map(0..big, |x| (0..x)), |x| x % 16 < 4);
let mut maths = 0;
iter.each(|x| { maths += x; true });
maths
}
pub fn math_internal_i32(big: i32) -> i32 {
let mut iter = filter(flat_map(0..big, |x| (0..x)), |x| x % 16 < 4);
let mut maths = 0;
iter.each(|x| { maths += x; true });
maths
}
pub fn math_internal_i64(big: i64) -> i64 {
let mut iter = filter(flat_map(0..big, |x| (0..x)), |x| x % 16 < 4);
let mut maths = 0;
iter.each(|x| { maths += x; true });
maths
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment