axiolid_model/
id.rs

1//! Typed graph identity.
2
3use core::fmt;
4use core::sync::atomic::{AtomicU64, Ordering};
5
6static NEXT_GRAPH_ID: AtomicU64 = AtomicU64::new(1);
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
9pub(crate) struct GraphId(u64);
10
11impl GraphId {
12    pub(crate) fn fresh() -> Self {
13        let value = NEXT_GRAPH_ID
14            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
15                current.checked_add(1)
16            })
17            .expect("geometry graph identity space exhausted");
18        Self(value)
19    }
20}
21
22/// Stable index owned by one immutable [`crate::GeometryGraph`].
23///
24/// A handle carries its graph's brand. Another builder refuses it
25/// ([`crate::GraphError::ForeignReference`]) and another graph's
26/// [`crate::GeometryGraph::get`] returns `None`, so a graph that references
27/// a node it does not own cannot be built at all rather than being detected
28/// later.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
30pub struct NodeId {
31    graph: GraphId,
32    index: u32,
33}
34
35impl NodeId {
36    pub(crate) fn from_index(graph: GraphId, index: usize) -> Self {
37        Self {
38            graph,
39            index: u32::try_from(index).expect("geometry graph exceeds u32 capacity"),
40        }
41    }
42
43    pub(crate) fn belongs_to(self, graph: GraphId) -> bool {
44        self.graph == graph
45    }
46
47    /// Zero-based graph index.
48    pub const fn index(self) -> usize {
49        self.index as usize
50    }
51}
52
53impl fmt::Display for NodeId {
54    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55        write!(f, "geometry#{}", self.index)
56    }
57}