//! An element in a [Tree](super::Tree) /// /// Contains a niche, and as such, [`Option>`] is free :D use std::{marker::PhantomData, num::NonZeroUsize}; /// An element of in a [Tree](super::Tree). //? The index of the node is stored as a [NonZeroUsize] for space savings //? Making Refs T-specific helps the user keep track of which Refs belong to which trees. //? This isn't bulletproof, of course, but it'll keep Ref from being used on Tree pub struct Ref(NonZeroUsize, PhantomData); impl Ref { /// Constructs a new [TreeRef] with the given index pub fn new_unchecked(index: usize) -> Self { // Safety: index cannot be zero because we use saturating addition on unsigned type. Self( unsafe { NonZeroUsize::new_unchecked(index.saturating_add(1)) }, PhantomData, ) } } impl From> for usize { fn from(value: Ref) -> Self { usize::from(value.0) - 1 } } /* --- implementations of derivable traits, because we don't need bounds here --- */ impl std::fmt::Debug for Ref { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_tuple("TreeRef").field(&self.0).finish() } } impl std::hash::Hash for Ref { fn hash(&self, state: &mut H) { self.0.hash(state); self.1.hash(state); } } impl PartialEq for Ref { fn eq(&self, other: &Self) -> bool { self.0 == other.0 && self.1 == other.1 } } impl Eq for Ref {} impl PartialOrd for Ref { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl Ord for Ref { fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.0.cmp(&other.0) } } impl Clone for Ref { fn clone(&self) -> Self { *self } } impl Copy for Ref {}