use std::num;
use o3::base::num::bounded;
use crate::driver::route::{self, indices::SlotOverflow};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct SlotIndex(bounded::raw::NonZeroU32<1, { route::SLOT_MASK as u32 + 1 }>);
impl From<SlotIndex> for num::NonZero<u32> {
fn from(slot: SlotIndex) -> Self {
slot.stored()
}
}
impl SlotIndex {
pub const ZERO: Self = Self(bounded::raw::NonZeroU32::exact::<1>());
pub const MAX: Self = Self(bounded::raw::NonZeroU32::exact::<
{ route::SLOT_MASK as u32 + 1 },
>());
pub const fn fixed<const RAW: u32>() -> Self {
const { assert!(RAW <= route::SLOT_MASK as u32, "slot bound") };
unsafe { Self::encode(RAW) }
}
pub const fn index(self) -> bounded::raw::U32<0, { route::SLOT_MASK as u32 }> {
self.0.into_index()
}
pub(crate) const fn into_le24(self) -> [u8; 3] {
let bytes = self.raw().to_le_bytes();
[bytes[0], bytes[1], bytes[2]]
}
pub const fn position(self) -> bounded::raw::U32<1, { route::SLOT_MASK as u32 + 1 }> {
self.0.into_u32()
}
pub(crate) const fn from_raw(raw: u64) -> Option<Self> {
if raw > route::SLOT_MASK {
None
} else {
Some(Self::from_field(raw))
}
}
pub(crate) const fn raw(self) -> u32 {
self.0.get() - 1
}
pub(in crate::driver) const fn stored(self) -> num::NonZero<u32> {
self.0.nonzero()
}
fn try_raw(raw: u64, actual: usize) -> Result<Self, SlotOverflow> {
Self::from_raw(raw).ok_or_else(|| SlotOverflow::new(actual))
}
}
impl SlotIndex {
pub(crate) const unsafe fn encode(raw: u32) -> Self {
Self(unsafe { bounded::raw::NonZeroU32::from_proven(num::NonZero::new_unchecked(raw + 1)) })
}
pub(crate) const fn from_field(bits: u64) -> Self {
unsafe { Self::encode((bits & route::SLOT_MASK) as u32) }
}
}
impl TryFrom<u32> for SlotIndex {
type Error = SlotOverflow;
fn try_from(raw: u32) -> Result<Self, Self::Error> {
Self::try_raw(u64::from(raw), raw as usize)
}
}
impl TryFrom<usize> for SlotIndex {
type Error = SlotOverflow;
fn try_from(raw: usize) -> Result<Self, Self::Error> {
Self::try_raw(raw as u64, raw)
}
}
impl Default for SlotIndex {
fn default() -> Self {
Self::ZERO
}
}
impl From<u16> for SlotIndex {
fn from(raw: u16) -> Self {
const { assert!(route::SLOT_MASK >= u16::MAX as u64, "slot bound") };
Self::from_field(u64::from(raw))
}
}
impl From<bounded::raw::U32<0, { route::SLOT_MASK as u32 }>> for SlotIndex {
fn from(index: bounded::raw::U32<0, { route::SLOT_MASK as u32 }>) -> Self {
unsafe { Self::encode(index.get()) }
}
}