Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement ExactSizeIterator for (Circular)TupleWindows #752

Merged
34 changes: 30 additions & 4 deletions src/tuple_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
use std::iter::Cycle;
use std::iter::Fuse;
use std::iter::FusedIterator;
use std::iter::Take;
use std::marker::PhantomData;

// `HomogeneousTuple` is a public facade for `TupleCollect`, allowing
Expand Down Expand Up @@ -208,7 +207,8 @@ where
I: Iterator<Item = T::Item> + Clone,
T: TupleCollect + Clone,
{
iter: Take<TupleWindows<Cycle<I>, T>>,
iter: TupleWindows<Cycle<I>, T>,
len: usize,
phantom_data: PhantomData<T>,
}

Expand All @@ -219,10 +219,11 @@ where
T::Item: Clone,
{
let len = iter.len();
let iter = tuple_windows(iter.cycle()).take(len);
let iter = tuple_windows(iter.cycle());

CircularTupleWindows {
iter,
len,
phantom_data: PhantomData {},
}
}
Expand All @@ -236,10 +237,35 @@ where
type Item = T;

fn next(&mut self) -> Option<Self::Item> {
self.iter.next()
if self.len != 0 {
self.len -= 1;
self.iter.next()
} else {
None
}
}

fn size_hint(&self) -> (usize, Option<usize>) {
(self.len, Some(self.len))
Philippe-Cholet marked this conversation as resolved.
Show resolved Hide resolved
}
}

impl<I, T> ExactSizeIterator for CircularTupleWindows<I, T>
where
I: Iterator<Item = T::Item> + Clone,
T: TupleCollect + Clone,
T::Item: Clone,
{
}

impl<I, T> FusedIterator for CircularTupleWindows<I, T>
where
I: Iterator<Item = T::Item> + Clone,
T: TupleCollect + Clone,
T::Item: Clone,
{
}

pub trait TupleCollect: Sized {
type Item;
type Buffer: Default + AsRef<[Option<Self::Item>]> + AsMut<[Option<Self::Item>]>;
Expand Down
4 changes: 4 additions & 0 deletions tests/quick.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1117,6 +1117,10 @@ quickcheck! {
true
}

fn circular_tuple_windows_exact_size(a: Vec<u8>) -> bool {
exact_size(a.iter().circular_tuple_windows::<(_, _, _, _)>())
}

fn equal_tuple_windows_1(a: Vec<u8>) -> bool {
let x = a.windows(1).map(|s| (&s[0], ));
let y = a.iter().tuple_windows::<(_,)>();
Expand Down