Skip to content

Commit 8aeb930

Browse files
committed
add a non blocking iterator for the mpsc::Receiver
Currently, the `mpsc::Receiver` offers methods for receiving values in both blocking (`recv`) and non-blocking (`try_recv`) flavours. However only blocking iteration over values is supported. This commit adds a non-blocking iterator to complement the `try_recv` method, just as the blocking iterator complements the `recv` method.
1 parent 9b4e2a5 commit 8aeb930

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

src/libstd/sync/mpsc/mod.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -311,6 +311,16 @@ pub struct Iter<'a, T: 'a> {
311311
rx: &'a Receiver<T>
312312
}
313313

314+
/// An iterator that attempts to yield all pending values for a receiver.
315+
/// `None` will be returned when there are no pending values remaining or
316+
/// if the corresponding channel has hung up.
317+
///
318+
/// This Iterator will never block the caller in order to wait for data to
319+
/// become available. Instead, it will return `None`.
320+
pub struct TryIter<'a, T: 'a> {
321+
rx: &'a Receiver<T>
322+
}
323+
314324
/// An owning iterator over messages on a receiver, this iterator will block
315325
/// whenever `next` is called, waiting for a new message, and `None` will be
316326
/// returned when the corresponding channel has hung up.
@@ -982,6 +992,15 @@ impl<T> Receiver<T> {
982992
pub fn iter(&self) -> Iter<T> {
983993
Iter { rx: self }
984994
}
995+
996+
/// Returns an iterator that will attempt to yield all pending values.
997+
/// It will return `None` if there are no more pending values or if the
998+
/// channel has hung up. The iterator will never `panic!` or block the
999+
/// user by waiting for values.
1000+
pub fn try_iter(&self) -> TryIter<T> {
1001+
TryIter { rx: self }
1002+
}
1003+
9851004
}
9861005

9871006
impl<T> select::Packet for Receiver<T> {
@@ -1077,6 +1096,12 @@ impl<'a, T> Iterator for Iter<'a, T> {
10771096
fn next(&mut self) -> Option<T> { self.rx.recv().ok() }
10781097
}
10791098

1099+
impl<'a, T> Iterator for TryIter<'a, T> {
1100+
type Item = T;
1101+
1102+
fn next(&mut self) -> Option<T> { self.rx.try_recv().ok() }
1103+
}
1104+
10801105
#[stable(feature = "receiver_into_iter", since = "1.1.0")]
10811106
impl<'a, T> IntoIterator for &'a Receiver<T> {
10821107
type Item = T;

0 commit comments

Comments
 (0)