use dope_sys::{
io::{reactor::submit::Queue as _, socket::option::tuning},
table::token::{self, Codec, Tuning as _},
};
use o3::base::num::bounded;
use crate::{
driver::{Key, tuning::Table},
reactor::sq,
};
pub trait Progress<T: Codec> {
fn next(&mut self, queue: sq::raw::Queue<'_, T>) -> Option<Option<T::Tuning>>;
fn has_pending(&self) -> bool;
fn cancel_all(&mut self);
fn cancel_at(&mut self, slot: sq::Fixed, target: Option<Key<T>>) -> Option<&mut bool>;
}
impl<T: Codec, const N: usize> Progress<T> for Table<Key<T>, N> {
fn next(&mut self, queue: sq::raw::Queue<'_, T>) -> Option<Option<T::Tuning>> {
let slot = self.ready?;
let state = unsafe { self.admitted(slot).get_unchecked_mut() };
let stopped = state.status.stopped;
if !stopped {
let vacancy = queue.try_acquire().ok()?;
let entry = unsafe { state.connect.assume_init_read() };
entry.submit(vacancy, T::tuning(tune::<T>(slot)));
}
self.ready = state.next.take();
if self.ready.is_none() {
self.tail = None;
}
Some(if stopped { Some(tune::<T>(slot)) } else { None })
}
fn has_pending(&self) -> bool {
self.ready.is_some()
}
fn cancel_all(&mut self) {
for state in unsafe { self.states.as_mut().get_unchecked_mut() } {
if state.target.is_some() {
state.status.stopped = true;
}
}
}
fn cancel_at(&mut self, slot: sq::Fixed, target: Option<Key<T>>) -> Option<&mut bool> {
let state = tuning::Table::get(self, slot.index())?;
let state = unsafe { state.get_unchecked_mut() };
let current = state.target?;
if target.is_some() && target != Some(current) {
return None;
}
Some(&mut state.status.stopped)
}
}
fn tune<T: Codec>(slot: sq::Fixed) -> T::Tuning {
let index: <T::Context as token::Context>::Slot =
bounded::U32::clamp(slot.index() as usize).into();
T::Tuning::new(index)
}