Skip to content

Add a "peekable" iterator adaptor, with a peek() method that returns the next element. #8396

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

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 96 additions & 0 deletions src/libstd/iterator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,28 @@ pub trait IteratorUtil<A> {
/// ~~~
fn enumerate(self) -> Enumerate<Self>;


/// Creates an iterator that has a `.peek()` method
/// that returns a optional reference to the next element,
/// and a `.peek_clone()` method that returns an optional copy.
///
/// # Example
///
/// ~~~ {.rust}
/// let a = [100, 200, 300];
/// let mut it = a.consume_iter().peekable();
/// assert_eq!(it.peek().unwrap(), &100);
/// assert_eq!(it.next().unwrap(), 100);
/// assert_eq!(it.next().unwrap(), 200);
/// assert_eq!(it.peek().unwrap(), &300);
/// assert_eq!(it.peek().unwrap(), &300);
/// assert_eq!(it.peek_clone().unwrap(), 300);
/// assert_eq!(it.next().unwrap(), 300);
/// assert!(it.peek().is_none());
/// assert!(it.next().is_none());
/// ~~~
fn peekable(self) -> Peekable<A, Self>;

/// Creates an iterator which invokes the predicate on elements until it
/// returns false. Once the predicate returns false, all further elements are
/// yielded.
Expand Down Expand Up @@ -520,6 +542,11 @@ impl<A, T: Iterator<A>> IteratorUtil<A> for T {
Enumerate{iter: self, count: 0}
}

#[inline]
fn peekable(self) -> Peekable<A, T> {
Peekable{iter: self, peeked: None}
}

#[inline]
fn skip_while<'r>(self, predicate: &'r fn(&A) -> bool) -> SkipWhile<'r, A, T> {
SkipWhile{iter: self, flag: false, predicate: predicate}
Expand Down Expand Up @@ -1154,6 +1181,56 @@ impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<(uint, A)> for Enumerat
}
}

/// An iterator with a `peek()` that returns an optional reference to the next element.
pub struct Peekable<A, T> {
priv iter: T,
priv peeked: Option<A>,
}

impl<A, T: Iterator<A>> Iterator<A> for Peekable<A, T> {
#[inline]
fn next(&mut self) -> Option<A> {
if self.peeked.is_some() { self.peeked.take() }
else { self.iter.next() }
}
}

impl<'self, A, T: Iterator<A>> Peekable<A, T> {
/// Return a reference to the next element of the iterator with out advancing it,
/// or None if the iterator is exhausted.
#[inline]
pub fn peek(&'self mut self) -> Option<&'self A> {
match self.peeked {
Some(ref value) => Some(value),
None => {
self.peeked = self.iter.next();
match self.peeked {
Some(ref value) => Some(value),
None => None,
}
},
}
}
}

impl<A: Clone, T: Iterator<A>> Peekable<A, T> {
/// Return a copy of the next element of the iterator with out advancing it,
/// or None if the iterator is exhausted.
#[inline]
pub fn peek_clone(&mut self) -> Option<A> {
match self.peeked {
Some(ref value) => Some(value.clone()),
None => {
self.peeked = self.iter.next();
match self.peeked {
Some(ref value) => Some(value.clone()),
None => None,
}
},
}
}
}

/// An iterator which rejects elements while `predicate` is true
pub struct SkipWhile<'self, A, T> {
priv iter: T,
Expand Down Expand Up @@ -1645,6 +1722,25 @@ mod tests {
}
}

#[test]
fn test_iterator_peekable() {
let xs = ~[0u, 1, 2, 3, 4, 5];
let mut it = xs.consume_iter().peekable();
assert_eq!(it.peek().unwrap(), &0);
assert_eq!(it.next().unwrap(), 0);
assert_eq!(it.next().unwrap(), 1);
assert_eq!(it.next().unwrap(), 2);
assert_eq!(it.peek().unwrap(), &3);
assert_eq!(it.peek().unwrap(), &3);
assert_eq!(it.next().unwrap(), 3);
assert_eq!(it.next().unwrap(), 4);
assert_eq!(it.peek().unwrap(), &5);
assert_eq!(it.peek_clone().unwrap(), 5);
assert_eq!(it.next().unwrap(), 5);
assert!(it.peek().is_none());
assert!(it.next().is_none());
}

#[test]
fn test_iterator_take_while() {
let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19];
Expand Down