use std::time::{Duration, SystemTime};
use super::priority::{PRIORITY_AFTER, SERVED_PRIORITY_AFTER, Scarce};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Wait {
pub job: u64,
pub since: SystemTime,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Waits {
memory: Option<Wait>,
cpu: Option<Wait>,
owner: Option<u64>,
served: bool,
cpu_held: bool,
}
impl Waits {
pub fn is_empty(&self) -> bool {
*self == Waits::default()
}
pub fn note(&mut self, scarce: Scarce, job: u64, now: SystemTime) -> bool {
let wait = match scarce {
Scarce::Memory => &mut self.memory,
Scarce::Cpu => &mut self.cpu,
};
let started = wait.is_none();
wait.get_or_insert(Wait { job, since: now });
started
}
pub fn retain(&mut self, queued: impl Fn(u64) -> bool) {
for wait in [&mut self.memory, &mut self.cpu] {
if wait.is_some_and(|wait| !queued(wait.job)) {
*wait = None;
}
}
self.owner = self.owner.filter(|job| queued(*job));
}
pub fn own(&mut self, job: u64) {
let waits = [self.memory, self.cpu];
if waits.iter().flatten().any(|wait| wait.job == job) {
self.owner = Some(job);
}
}
pub fn started(&mut self) -> bool {
let served = self.served || self.owner.is_some();
let newly = served && !self.served;
*self = Waits {
served,
cpu_held: self.cpu_held,
..Waits::default()
};
newly
}
pub fn stopped(&mut self) {
*self = Waits::default();
}
pub fn set_cpu_held(&mut self, held: bool) {
self.cpu_held = held;
}
pub fn cpu_held(&self) -> bool {
self.cpu_held
}
pub fn cpu(&self) -> Option<Wait> {
self.cpu
}
pub fn emptied(&mut self) {
self.served = false;
}
fn limit(&self) -> Duration {
if self.served {
SERVED_PRIORITY_AFTER
} else {
PRIORITY_AFTER
}
}
pub fn deadlines(&self) -> impl Iterator<Item = SystemTime> {
let limit = self.limit();
[self.memory, self.cpu]
.into_iter()
.flatten()
.map(move |wait| wait.since + limit)
}
pub(super) fn matured(&self, job: u64, now: SystemTime) -> Option<SystemTime> {
let limit = self.limit();
[self.memory, self.cpu]
.into_iter()
.flatten()
.filter(|wait| wait.job == job)
.map(|wait| wait.since + limit)
.filter(|reached| *reached <= now)
.min()
}
}
#[cfg(test)]
impl Waits {
pub(crate) fn with_memory(mut self, wait: impl Into<Option<Wait>>) -> Self {
self.memory = wait.into();
self
}
pub(crate) fn with_cpu(mut self, wait: impl Into<Option<Wait>>) -> Self {
self.cpu = wait.into();
self
}
pub(crate) fn with_served(mut self, served: bool) -> Self {
self.served = served;
self
}
pub(crate) fn memory(&self) -> Option<Wait> {
self.memory
}
pub(crate) fn owner(&self) -> Option<u64> {
self.owner
}
pub(crate) fn served(&self) -> bool {
self.served
}
pub(crate) fn memory_mut(&mut self) -> Option<&mut Wait> {
self.memory.as_mut()
}
pub(crate) fn cpu_mut(&mut self) -> Option<&mut Wait> {
self.cpu.as_mut()
}
}