use std::fmt;
use std::sync::atomic::{AtomicU64, Ordering};
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "devtools", derive(serde::Serialize, serde::Deserialize))]
pub struct ElementId(pub(crate) u64);
static STABLE_COUNTER: AtomicU64 = AtomicU64::new(1);
impl ElementId {
pub const SENTINEL: Self = Self(u64::MAX);
#[inline]
pub(crate) fn from_parts(index: u32, generation: u32) -> Self {
Self(((index as u64) << 32) | (generation as u64))
}
#[inline]
pub fn index(&self) -> u32 {
(self.0 >> 32) as u32
}
#[inline]
pub fn generation(&self) -> u32 {
self.0 as u32
}
#[inline]
pub fn to_u64(self) -> u64 {
self.0
}
#[inline]
pub(crate) fn from_u64(raw: u64) -> Self {
Self(raw)
}
pub fn allocate() -> Self {
Self(STABLE_COUNTER.fetch_add(1, Ordering::Relaxed))
}
}
impl Default for ElementId {
fn default() -> Self {
Self::SENTINEL
}
}
impl fmt::Debug for ElementId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if *self == Self::SENTINEL {
write!(f, "ElementId(SENTINEL)")
} else {
write!(
f,
"ElementId(idx={},gen={})",
self.index(),
self.generation()
)
}
}
}
impl fmt::Display for ElementId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if *self == Self::SENTINEL {
write!(f, "#SENTINEL")
} else {
write!(f, "#{}:{}", self.index(), self.generation())
}
}
}