Skip to main content

dope_core/driver/route/token/
control.rs

1use core::{mem, num};
2
3use crate::driver::route::{self, Route, indices, kind, token};
4
5/// One framework control decoded without manufacturing a keyed identity.
6#[derive(Clone, Copy, Eq, PartialEq, Debug)]
7#[repr(transparent)]
8pub struct Control(num::NonZero<u64>);
9
10impl From<Control> for num::NonZero<u64> {
11    fn from(control: Control) -> Self {
12        control.0
13    }
14}
15
16impl Control {
17    pub(crate) const fn new(kind: kind::Code, slot: indices::SlotIndex) -> Self {
18        let raw = token::metadata(Route::FRAMEWORK, kind, slot);
19        // SAFETY: the nonzero framework route occupies the high byte.
20        Self(unsafe { num::NonZero::<u64>::new_unchecked(raw) })
21    }
22
23    pub const fn slot(self) -> indices::SlotIndex {
24        indices::SlotIndex::from_field(self.0.get())
25    }
26}
27
28impl TryFrom<u64> for Control {
29    type Error = u64;
30
31    fn try_from(raw: u64) -> Result<Self, Self::Error> {
32        if (raw >> route::SHIFT) as u8 != route::FRAMEWORK {
33            return Err(raw);
34        }
35        // SAFETY: a framework-tagged high byte makes the complete word nonzero.
36        Ok(Self(unsafe { num::NonZero::<u64>::new_unchecked(raw) }))
37    }
38}
39
40const _: () = {
41    assert!(mem::size_of::<Control>() == mem::size_of::<u64>());
42    assert!(mem::size_of::<Option<Control>>() == mem::size_of::<Control>());
43};