use {
crate::Linearize,
core::{
cmp::Ordering,
fmt::{Debug, Formatter},
hash::{Hash, Hasher},
marker::PhantomData,
},
};
#[repr(transparent)]
pub struct Linearized<L>
where
L: ?Sized,
{
index: usize,
_phantom: PhantomData<L>,
}
impl<L> Linearized<L>
where
L: ?Sized,
{
pub fn new(l: &L) -> Self
where
L: Linearize,
{
unsafe {
Self::new_unchecked(l.linearize())
}
}
pub const unsafe fn new_unchecked(index: usize) -> Self {
Self {
index,
_phantom: PhantomData,
}
}
pub fn get(self) -> usize {
self.index
}
pub fn delinearize(self) -> L
where
L: Linearize + Sized,
{
unsafe {
L::from_linear_unchecked(self.index)
}
}
}
impl<L> Copy for Linearized<L> where L: ?Sized {}
impl<L> Clone for Linearized<L>
where
L: ?Sized,
{
fn clone(&self) -> Self {
*self
}
}
impl<L> Debug for Linearized<L>
where
L: ?Sized,
{
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
self.index.fmt(f)
}
}
impl<L> Hash for Linearized<L>
where
L: ?Sized,
{
fn hash<H: Hasher>(&self, state: &mut H) {
self.index.hash(state)
}
}
impl<L> PartialEq for Linearized<L>
where
L: ?Sized,
{
fn eq(&self, other: &Self) -> bool {
self.index == other.index
}
}
impl<L> PartialEq<usize> for Linearized<L>
where
L: ?Sized,
{
fn eq(&self, other: &usize) -> bool {
self.index == *other
}
}
impl<L> Eq for Linearized<L> where L: ?Sized {}
impl<L> PartialOrd for Linearized<L>
where
L: ?Sized,
{
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<L> PartialOrd<usize> for Linearized<L>
where
L: ?Sized,
{
fn partial_cmp(&self, other: &usize) -> Option<Ordering> {
self.index.partial_cmp(other)
}
}
impl<L> Ord for Linearized<L>
where
L: ?Sized,
{
fn cmp(&self, other: &Self) -> Ordering {
self.index.cmp(&other.index)
}
}