group into is generic

master
Avril 4 years ago
parent b03a90f493
commit 95359c2a81
Signed by: flanchan
GPG Key ID: 284488987C31F630

@ -18,11 +18,11 @@ use tokio::{
use futures::future::Future; use futures::future::Future;
#[derive(Debug)] #[derive(Debug)]
pub struct GroupIter<I, T>(std::iter::Fuse<I>, Vec<T>, usize); pub struct GroupIter<I, T, U=Box<[T]>>(std::iter::Fuse<I>, Vec<T>, usize, PhantomData<U>);
impl<I: Iterator<Item=T>, T> Iterator for GroupIter<I, T> impl<U: From<Vec<T>>, I: Iterator<Item=T>, T> Iterator for GroupIter<I, T, U>
{ {
type Item = Box<[T]>; type Item = U;
fn next(&mut self) -> Option<Self::Item> fn next(&mut self) -> Option<Self::Item>
{ {
if self.1.len() == 0 { if self.1.len() == 0 {
@ -48,18 +48,39 @@ impl<I: Iterator<Item=T>, T> std::iter::FusedIterator for GroupIter<I, T>{}
pub trait GroupIterExt<I, T>: Sized pub trait GroupIterExt<I, T>: Sized
{ {
/// Group this iterator to return a constructed `U` of every `n` items.
///
/// # Notes
/// If there isn't `n` items left in the iterator, then the rest is returned.
fn group_into<U>(self, n: usize) -> GroupIter<I, T, U>
where U: From<Vec<T>>;
/// Group this iterator to return a `Vec<T>` of every `n` items.
///
/// # Notes
/// If there isn't `n` items left in the iterator, then the rest is returned.
#[inline] fn group(self, n: usize) -> GroupIter<I, T, Vec<T>>
{
self.group_into(n)
}
/// Group this iterator to return a boxed slice of every `n` items. /// Group this iterator to return a boxed slice of every `n` items.
/// ///
/// # Notes /// # Notes
/// If there isn't `n` items left in the iterator, then the rest is returned. /// If there isn't `n` items left in the iterator, then the rest is returned.
fn group(self, n: usize) -> GroupIter<I, T>; #[inline] fn group_into_boxed_slice(self, n: usize) -> GroupIter<I, T>
{
self.group_into(n)
}
} }
impl<T: IntoIterator> GroupIterExt<<T as IntoIterator>::IntoIter, <T as IntoIterator>::Item> for T impl<T: IntoIterator> GroupIterExt<<T as IntoIterator>::IntoIter, <T as IntoIterator>::Item> for T
{ {
fn group(self, every: usize) -> GroupIter<<T as IntoIterator>::IntoIter, <T as IntoIterator>::Item> fn group_into<U>(self, every: usize) -> GroupIter<<T as IntoIterator>::IntoIter, <T as IntoIterator>::Item, U>
where U: From<Vec<<T as IntoIterator>::Item>>
{ {
GroupIter(self.into_iter().fuse(), Vec::with_capacity(every), every) GroupIter(self.into_iter().fuse(), Vec::with_capacity(every), every, PhantomData)
} }
} }

Loading…
Cancel
Save