Skip to content

Commit

Permalink
implement IntoIterator for Receiver
Browse files Browse the repository at this point in the history
  • Loading branch information
rapha committed Apr 20, 2015
1 parent be9a72b commit 6bf5838
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions src/libstd/sync/mpsc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,7 @@ pub use self::select::{Select, Handle};
use self::select::StartResult;
use self::select::StartResult::*;
use self::blocking::SignalToken;
use core::iter::IntoIterator;

mod blocking;
mod oneshot;
Expand Down Expand Up @@ -306,6 +307,10 @@ pub struct Iter<'a, T: 'a> {
rx: &'a Receiver<T>
}

pub struct IntoIter<T> {
rx: Receiver<T>
}

/// The sending-half of Rust's asynchronous channel type. This half can only be
/// owned by one task, but it can be cloned to send to other tasks.
#[stable(feature = "rust1", since = "1.0.0")]
Expand Down Expand Up @@ -899,6 +904,20 @@ impl<'a, T> Iterator for Iter<'a, T> {
fn next(&mut self) -> Option<T> { self.rx.recv().ok() }
}

impl<T> Iterator for IntoIter<T> {
type Item = T;
fn next(&mut self) -> Option<T> { self.rx.recv().ok() }
}

impl <T> IntoIterator for Receiver<T> {
type Item = T;
type IntoIter = IntoIter<T>;

fn into_iter(self) -> IntoIter<T> {
IntoIter { rx: self }
}
}

#[unsafe_destructor]
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Drop for Receiver<T> {
Expand Down Expand Up @@ -1507,6 +1526,22 @@ mod test {
assert_eq!(count_rx.recv().unwrap(), 4);
}

#[test]
fn test_recv_into_iter() {
use core::iter::IntoIterator;

let mut iter = {
let (tx, rx) = channel::<i32>();
tx.send(1).unwrap();
tx.send(2).unwrap();

rx.into_iter()
};
assert_eq!(iter.next().unwrap(), 1);
assert_eq!(iter.next().unwrap(), 2);
assert_eq!(iter.next().is_none(), true);
}

#[test]
fn try_recv_states() {
let (tx1, rx1) = channel::<i32>();
Expand Down

0 comments on commit 6bf5838

Please sign in to comment.