add Cloned iterator adaptor

This commit is contained in:
Alexis Beingessner 2014-11-17 21:00:07 -05:00
parent 9702fb9c7b
commit 4a656062ee
2 changed files with 57 additions and 1 deletions

View File

@ -65,9 +65,10 @@ use cmp;
use cmp::Ord;
use mem;
use num::{ToPrimitive, Int};
use ops::Add;
use ops::{Add, Deref};
use option::{Option, Some, None};
use uint;
#[deprecated = "renamed to Extend"] pub use self::Extend as Extendable;
/// Conversion from an `Iterator`
@ -1021,6 +1022,44 @@ impl<T: Clone> MinMaxResult<T> {
}
}
/// A trait for iterators that contain cloneable elements
pub trait CloneIteratorExt<A> {
/// Creates an iterator that clones the elements it yields. Useful for converting an
/// Iterator<&T> to an Iterator<T>.
fn cloned(self) -> Cloned<Self>;
}
impl<A: Clone, D: Deref<A>, I: Iterator<D>> CloneIteratorExt<A> for I {
fn cloned(self) -> Cloned<I> {
Cloned { it: self }
}
}
/// An iterator that clones the elements of an underlying iterator
pub struct Cloned<I> {
it: I,
}
impl<A: Clone, D: Deref<A>, I: Iterator<D>> Iterator<A> for Cloned<I> {
fn next(&mut self) -> Option<A> {
self.it.next().cloned()
}
fn size_hint(&self) -> (uint, Option<uint>) {
self.it.size_hint()
}
}
impl<A: Clone, D: Deref<A>, I: DoubleEndedIterator<D>>
DoubleEndedIterator<A> for Cloned<I> {
fn next_back(&mut self) -> Option<A> {
self.it.next_back().cloned()
}
}
impl<A: Clone, D: Deref<A>, I: ExactSize<D>> ExactSize<A> for Cloned<I> {}
/// A trait for iterators that are cloneable.
pub trait CloneableIterator {
/// Repeats an iterator endlessly

View File

@ -440,6 +440,23 @@ fn test_rev() {
vec![16, 14, 12, 10, 8, 6]);
}
#[test]
fn test_cloned() {
let xs = [2u8, 4, 6, 8];
let mut it = xs.iter().cloned();
assert_eq!(it.len(), 4);
assert_eq!(it.next(), Some(2));
assert_eq!(it.len(), 3);
assert_eq!(it.next(), Some(4));
assert_eq!(it.len(), 2);
assert_eq!(it.next_back(), Some(8));
assert_eq!(it.len(), 1);
assert_eq!(it.next_back(), Some(6));
assert_eq!(it.len(), 0);
assert_eq!(it.next_back(), None);
}
#[test]
fn test_double_ended_map() {
let xs = [1i, 2, 3, 4, 5, 6];