about summary refs log tree commit diff
path: root/src/libstd
diff options
context:
space:
mode:
authormitchmindtree <mitchell.nordine@gmail.com>2016-07-08 22:12:36 +1000
committermitchmindtree <mitchell.nordine@gmail.com>2016-07-08 22:12:36 +1000
commit8aeb9303e954502f67f4af7c5c7e79f6d4f706eb (patch)
treef20307a74b668d186f9747d22d77b66695e6bf1d /src/libstd
parent9b4e2a5b2d410318051a38e6b7da10b45975d022 (diff)
downloadrust-8aeb9303e954502f67f4af7c5c7e79f6d4f706eb.tar.gz
rust-8aeb9303e954502f67f4af7c5c7e79f6d4f706eb.zip
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.
Diffstat (limited to 'src/libstd')
-rw-r--r--src/libstd/sync/mpsc/mod.rs25
1 files changed, 25 insertions, 0 deletions
diff --git a/src/libstd/sync/mpsc/mod.rs b/src/libstd/sync/mpsc/mod.rs
index 34bc210b3c8..30ce9c3f382 100644
--- a/src/libstd/sync/mpsc/mod.rs
+++ b/src/libstd/sync/mpsc/mod.rs
@@ -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;