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.
This commit is contained in:
parent
9b4e2a5b2d
commit
8aeb9303e9
1 changed files with 25 additions and 0 deletions
|
|
@ -311,6 +311,16 @@ pub struct Iter<'a, T: 'a> {
|
|||
rx: &'a Receiver<T>
|
||||
}
|
||||
|
||||
/// An iterator that attempts to yield all pending values for a receiver.
|
||||
/// `None` will be returned when there are no pending values remaining or
|
||||
/// if the corresponding channel has hung up.
|
||||
///
|
||||
/// This Iterator will never block the caller in order to wait for data to
|
||||
/// become available. Instead, it will return `None`.
|
||||
pub struct TryIter<'a, T: 'a> {
|
||||
rx: &'a Receiver<T>
|
||||
}
|
||||
|
||||
/// An owning iterator over messages on a receiver, this iterator will block
|
||||
/// whenever `next` is called, waiting for a new message, and `None` will be
|
||||
/// returned when the corresponding channel has hung up.
|
||||
|
|
@ -982,6 +992,15 @@ impl<T> Receiver<T> {
|
|||
pub fn iter(&self) -> Iter<T> {
|
||||
Iter { rx: self }
|
||||
}
|
||||
|
||||
/// Returns an iterator that will attempt to yield all pending values.
|
||||
/// It will return `None` if there are no more pending values or if the
|
||||
/// channel has hung up. The iterator will never `panic!` or block the
|
||||
/// user by waiting for values.
|
||||
pub fn try_iter(&self) -> TryIter<T> {
|
||||
TryIter { rx: self }
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
impl<T> select::Packet for Receiver<T> {
|
||||
|
|
@ -1077,6 +1096,12 @@ impl<'a, T> Iterator for Iter<'a, T> {
|
|||
fn next(&mut self) -> Option<T> { self.rx.recv().ok() }
|
||||
}
|
||||
|
||||
impl<'a, T> Iterator for TryIter<'a, T> {
|
||||
type Item = T;
|
||||
|
||||
fn next(&mut self) -> Option<T> { self.rx.try_recv().ok() }
|
||||
}
|
||||
|
||||
#[stable(feature = "receiver_into_iter", since = "1.1.0")]
|
||||
impl<'a, T> IntoIterator for &'a Receiver<T> {
|
||||
type Item = T;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue