use std::{mem, num};
use crate::{base::num::bounded, depot::array};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[repr(transparent)]
pub struct Index<const N: usize>(num::NonZero<u8>);
impl<const N: usize> Index<N> {
const fn from_offset(offset: u8) -> Self {
let slot = array::Vacancy::<N>(num::NonZero::<u32>::MIN.saturating_add(offset as u32));
Self(array::raw::compact_position(slot))
}
fn vacancy(self) -> array::Vacancy<N> {
array::Vacancy(self.0.into())
}
pub const fn new(index: usize) -> Option<Self> {
const { assert!(N <= u8::MAX as usize) };
if index >= N {
return None;
}
Some(Self::from_offset(index as u8))
}
pub const fn mask(value: u8) -> Self {
const { assert!(N <= u8::MAX as usize && N.is_power_of_two()) };
Self::from_offset(value & (N - 1) as u8)
}
pub fn from_bit(index: impl array::raw::BitIndex<N>) -> Self {
const { assert!(N <= u8::MAX as usize) };
Self::from_offset(index.index() as u8)
}
pub fn iter() -> impl DoubleEndedIterator<Item = Self> + ExactSizeIterator {
const { assert!(N <= u8::MAX as usize) };
(0..N as u8).map(Self::from_offset)
}
pub const fn at<const I: usize>() -> Self {
const { assert!(N <= u8::MAX as usize) };
const { assert!(I < N) };
Self::from_offset(I as u8)
}
pub fn partition<T, const M: usize>(
self,
values: &[T; M],
test: impl FnMut(&T) -> bool,
) -> Self {
const { assert!(M < N && M + 1 == N && N <= u8::MAX as usize) };
let prefix = array::Len::<M>(self.index() as u32).prefix(values);
Self::from_offset(prefix.partition_point(test) as u8)
}
pub const fn widen<const M: usize>(self) -> Index<M> {
const { assert!(N <= M && M <= u8::MAX as usize) };
Index(self.0)
}
pub fn previous<const M: usize>(self) -> Option<Index<M>> {
const { assert!(M < N && M + 1 == N && N <= u8::MAX as usize) };
num::NonZero::new(self.0.get() - 1).map(Index)
}
pub fn next<const M: usize>(self) -> Index<M> {
const { assert!(N < M && M <= u8::MAX as usize) };
Index::from_offset(self.0.get())
}
pub fn insert<'a, T: Copy, const M: usize>(
self,
values: &[T; M],
value: T,
out: &'a mut mem::MaybeUninit<[T; N]>,
) -> &'a mut [T; N] {
array::raw::insert_at(&self.vacancy(), values, value, out)
}
pub const fn index(self) -> usize {
self.0.get() as usize - 1
}
pub const fn into_u32<const MAX: u32>(self) -> bounded::raw::U32<0, MAX> {
array::raw::position_u32(self)
}
pub fn get<T>(self, values: &[T; N]) -> &T {
array::raw::at(&self.vacancy(), values)
}
pub fn get_mut<T>(self, values: &mut [T; N]) -> &mut T {
self.vacancy().get_mut(values)
}
}
impl<const N: usize> From<array::Vacancy<N>> for Index<N> {
fn from(slot: array::Vacancy<N>) -> Self {
Self(array::raw::compact_position(slot))
}
}
const _: () = {
assert!(mem::size_of::<Index<1>>() == 1);
assert!(mem::size_of::<Option<Index<1>>>() == 1);
};