tiny_http/util/
messages_queue.rsuse std::collections::VecDeque;
use std::sync::{Arc, Condvar, Mutex};
use std::time::{Duration, Instant};
enum Control<T> {
Elem(T),
Unblock,
}
pub struct MessagesQueue<T>
where
T: Send,
{
queue: Mutex<VecDeque<Control<T>>>,
condvar: Condvar,
}
impl<T> MessagesQueue<T>
where
T: Send,
{
pub fn with_capacity(capacity: usize) -> Arc<MessagesQueue<T>> {
Arc::new(MessagesQueue {
queue: Mutex::new(VecDeque::with_capacity(capacity)),
condvar: Condvar::new(),
})
}
pub fn push(&self, value: T) {
let mut queue = self.queue.lock().unwrap();
queue.push_back(Control::Elem(value));
self.condvar.notify_one();
}
pub fn unblock(&self) {
let mut queue = self.queue.lock().unwrap();
queue.push_back(Control::Unblock);
self.condvar.notify_one();
}
pub fn pop(&self) -> Option<T> {
let mut queue = self.queue.lock().unwrap();
loop {
match queue.pop_front() {
Some(Control::Elem(value)) => return Some(value),
Some(Control::Unblock) => return None,
None => (),
}
queue = self.condvar.wait(queue).unwrap();
}
}
pub fn try_pop(&self) -> Option<T> {
let mut queue = self.queue.lock().unwrap();
match queue.pop_front() {
Some(Control::Elem(value)) => Some(value),
Some(Control::Unblock) | None => None,
}
}
pub fn pop_timeout(&self, timeout: Duration) -> Option<T> {
let mut queue = self.queue.lock().unwrap();
let mut duration = timeout;
loop {
match queue.pop_front() {
Some(Control::Elem(value)) => return Some(value),
Some(Control::Unblock) => return None,
None => (),
}
let now = Instant::now();
let (_queue, result) = self.condvar.wait_timeout(queue, timeout).unwrap();
queue = _queue;
let sleep_time = now.elapsed();
duration = if duration > sleep_time {
duration - sleep_time
} else {
Duration::from_millis(0)
};
if result.timed_out()
|| (duration.as_secs() == 0 && duration.subsec_nanos() < 1_000_000)
{
return None;
}
}
}
}