use std::marker::PhantomData;
use std::u32::MAX;
use std::hash;
use std::fmt;
use std::cmp::Ordering;
#[derive(Serialize, Deserialize)]
pub struct Id<T> {
index: u32,
#[serde(skip)]
marker: PhantomData<T>,
}
impl<T> Id<T> {
pub fn invalid() -> Self {
Self::new(MAX)
}
pub fn is_invalid(&self) -> bool {
self.index == MAX
}
pub fn is_valid(&self) -> bool {
self.index != MAX
}
pub fn cast<U>(&self) -> Id<U> {
Id::new(self.index)
}
fn new(index: u32) -> Self {
Self { index, marker: PhantomData }
}
}
impl<T> Copy for Id<T> {}
impl<T> Clone for Id<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> PartialEq for Id<T> {
fn eq(&self, other: &Self) -> bool {
self.index == other.index
}
}
impl<T> Eq for Id<T> {}
impl<T> PartialOrd for Id<T> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.index.partial_cmp(&other.index)
}
}
impl<T> Ord for Id<T> {
fn cmp(&self, other: &Self) -> Ordering {
self.index.cmp(&other.index)
}
}
impl<T> hash::Hash for Id<T> {
fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
self.index.hash(hasher);
}
}
impl<T> fmt::Debug for Id<T> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "Id[{}]", self.index)
}
}
impl<T> From<usize> for Id<T> {
fn from(index: usize) -> Self {
if index >= MAX as usize {
Self::invalid()
} else {
Self::new(index as u32)
}
}
}
impl<T> Into<usize> for Id<T> {
fn into(self) -> usize {
self.index as usize
}
}