use std::collections::{BTreeSet, VecDeque};
use super::super::doubt::NOT_HELD;
use super::read::{Reading, Taken};
use super::run::LISTEN_SECONDS;
use super::{Invocation, Mailbox, lock_mail};
pub type Now = Box<dyn Fn() -> i64 + Send>;
pub struct Push {
mail: Mailbox,
reading: Reading,
held: BTreeSet<String>,
ready: VecDeque<Invocation>,
now: Now,
quiet: u32,
ended: bool,
}
impl Mailbox {
pub fn push(&self, client: &str, holding: &[String], now: Now) -> Push {
let reading = self.claim(&mut lock_mail(&self.cell), client, true);
Push {
mail: self.clone(),
reading,
held: holding.iter().cloned().collect(),
ready: VecDeque::new(),
now,
quiet: 0,
ended: false,
}
}
fn look(&self, push: &mut Push) -> Option<()> {
let now = (push.now)();
let mut slots = lock_mail(&self.cell);
if !push.reading.holds(&slots) {
return None;
}
for (id, slot) in &mut slots.live {
if slot.client != push.reading.name() || slot.run.over() || push.held.contains(id) {
continue;
}
let listening = now - slot.heard <= LISTEN_SECONDS;
if let Some(job) = slot.met(true, listening, NOT_HELD) {
push.held.insert(id.clone());
push.ready.push_back(job);
}
}
Some(())
}
}
impl Iterator for Push {
type Item = Taken;
fn next(&mut self) -> Option<Taken> {
if self.ended {
return None;
}
let mail = self.mail.clone();
loop {
if let Some(job) = self.ready.pop_front() {
self.quiet = 0;
return Some(Taken::Work(vec![job]));
}
if mail.look(self).is_none() {
self.ended = true;
return Some(Taken::Superseded);
}
if self.ready.is_empty() {
if self.quiet >= mail.waits {
self.quiet = 0;
return Some(Taken::Work(Vec::new()));
}
self.quiet += 1;
std::thread::sleep(mail.tick);
}
}
}
}