use std::sync::mpsc::{Receiver, TryRecvError};
use std::thread;
use std::time::Duration;
#[derive(Debug)]
pub enum RecvWithTimeoutError {
Disconnected,
Timeout,
}
pub fn recv_with_timeout<T>(receiver: &Receiver<T>,
timeout: Duration)
-> Result<T, RecvWithTimeoutError> {
let interval = Duration::from_millis(100);
let mut elapsed = Duration::from_millis(0);
loop {
match receiver.try_recv() {
Ok(value) => return Ok(value),
Err(TryRecvError::Disconnected) => return Err(RecvWithTimeoutError::Disconnected),
Err(TryRecvError::Empty) => {
thread::sleep(interval);
elapsed = elapsed + interval;
if elapsed > timeout {
return Err(RecvWithTimeoutError::Timeout);
}
}
}
}
}
#[allow(unused)]
pub fn iter_with_timeout<T>(receiver: &Receiver<T>, timeout: Duration) -> Iter<T> {
Iter {
rx: receiver,
timeout: timeout,
}
}
#[allow(unused)]
pub struct Iter<'a, T: 'a> {
rx: &'a Receiver<T>,
timeout: Duration,
}
impl<'a, T> Iterator for Iter<'a, T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
recv_with_timeout(self.rx, self.timeout).ok()
}
}