freya_core/
node_id.rs

1use std::{
2    num::NonZeroU64,
3    ops::AddAssign,
4    str::FromStr,
5};
6
7#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
8#[derive(PartialEq, Eq, Clone, Copy, Debug, Hash, PartialOrd, Ord)]
9pub struct NodeId(pub NonZeroU64);
10
11impl NodeId {
12    pub const ROOT: NodeId = NodeId(NonZeroU64::MIN);
13    pub const PLACEHOLDER: NodeId = NodeId(NonZeroU64::MAX);
14}
15
16impl AddAssign<u64> for NodeId {
17    fn add_assign(&mut self, other: u64) {
18        self.0 = self.0.saturating_add(other);
19    }
20}
21
22impl torin::prelude::NodeKey for NodeId {}
23impl ragnarok::NodeKey for NodeId {}
24
25impl From<NodeId> for u64 {
26    fn from(value: NodeId) -> Self {
27        value.0.get()
28    }
29}
30impl From<u64> for NodeId {
31    fn from(value: u64) -> Self {
32        Self(NonZeroU64::new(value).unwrap())
33    }
34}
35
36impl FromStr for NodeId {
37    type Err = std::fmt::Error;
38    fn from_str(s: &str) -> Result<Self, Self::Err> {
39        let index = s.parse().map_err(|_| std::fmt::Error)?;
40        Ok(Self(index))
41    }
42}
43
44impl std::fmt::Display for NodeId {
45    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        f.write_str(&self.0.to_string())
47    }
48}