use core::{hash, marker, mem, num};
use o3::base::marker::ThreadBound;
use crate::driver::{
route,
route::{Epoch, Route, indices, indices::SlotIndex, kind, table},
};
pub(super) mod control;
const fn metadata(route: Route, kind: kind::Code, slot: SlotIndex) -> u64 {
((route.raw() as u64) << route::SHIFT)
| ((kind.raw() as u64) << route::KIND_SHIFT)
| slot.raw() as u64
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[repr(C)]
pub struct Token {
pub(super) epoch: num::NonZero<u64>,
pub(super) thread: ThreadBound,
pub(super) meta: u64,
}
impl hash::Hash for Token {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
hash::Hash::hash(&self.epoch.get(), state);
hash::Hash::hash(&self.meta, state);
}
}
impl Token {
pub(crate) const fn from_flight(
epoch: route::Epoch,
slot: indices::SlotIndex,
kind: kind::Code,
route: route::Route,
) -> Self {
let (epoch, thread) = epoch.into_parts();
Self {
epoch,
thread,
meta: metadata(route, kind, slot),
}
}
pub const fn route(self) -> route::Route {
route::Route::from_bits((self.meta >> route::SHIFT) as u8)
}
pub const fn kind(self) -> Result<kind::Kind, kind::Unknown> {
let raw = self.kind_raw();
match raw {
0 => Ok(kind::Kind::Unspecified),
1 => Ok(kind::Kind::Accept),
2 => Ok(kind::Kind::Recv),
3 => Ok(kind::Kind::Send),
5 => Ok(kind::Kind::Socket),
6 => Ok(kind::Kind::Connect),
7 => Ok(kind::Kind::Shutdown),
11 => Ok(kind::Kind::Open),
19 => Ok(kind::Kind::OneShot),
21 => Ok(kind::Kind::TaskQueue),
25 => Ok(kind::Kind::Tuning),
28 => Ok(kind::Kind::Write),
29 => Ok(kind::Kind::Sync),
30 => Ok(kind::Kind::Read),
unknown => Err(kind::Unknown::new(unknown)),
}
}
pub(crate) const fn kind_raw(self) -> u8 {
(self.meta >> route::KIND_SHIFT) as u8
}
pub const fn slot(self) -> indices::SlotIndex {
SlotIndex::from_field(self.meta)
}
pub const fn epoch(self) -> route::Epoch {
Epoch::new(self.epoch, self.thread)
}
pub(super) const fn encode<Tag, C>(parts: table::Parts<Tag>) -> Self
where
Tag: route::Select<C>,
C: kind::Class,
{
Self::from_flight(parts.epoch(), parts.slot(), C::CODE, Tag::ROUTE)
}
#[doc(hidden)]
pub const fn from_parts<Tag: route::Tag>(parts: table::Parts<Tag>) -> Self {
Self::from_flight(
parts.epoch(),
parts.slot(),
<Tag::Class as kind::Class>::CODE,
Tag::ROUTE,
)
}
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct Brand<'d, Tag> {
pub(super) driver: crate::driver::Invariant<'d>,
tag: marker::PhantomData<*mut Tag>,
}
impl<'d, Tag> Brand<'d, Tag> {
pub(crate) const fn new(driver: crate::driver::Invariant<'d>) -> Self {
Self {
driver,
tag: marker::PhantomData,
}
}
}
const _: () = {
assert!(mem::size_of::<Token>() == 2 * mem::size_of::<u64>());
assert!(mem::size_of::<Option<Token>>() == mem::size_of::<Token>());
};