gbf_core/decompiler/ast/
node_id.rs

1#![deny(missing_docs)]
2
3use std::{
4    fmt::{self, Display, Formatter},
5    sync::atomic::{AtomicUsize, Ordering},
6};
7
8use serde::{Deserialize, Serialize};
9
10/// A unique identifier for an AST node.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
12pub struct NodeId(usize);
13
14static NEXT_NODE_ID: AtomicUsize = AtomicUsize::new(0);
15
16impl NodeId {
17    /// Generates a new, unique NodeId.
18    ///
19    /// This uses a global atomic counter to ensure that each NodeId is unique.
20    pub fn new() -> Self {
21        // Using Relaxed ordering is fine here because we only need atomic uniqueness,
22        // not synchronization with other operations.
23        let id = NEXT_NODE_ID.fetch_add(1, Ordering::Relaxed);
24        NodeId(id)
25    }
26
27    /// Returns the underlying numeric id.
28    pub fn get(self) -> usize {
29        self.0
30    }
31}
32
33impl Default for NodeId {
34    fn default() -> Self {
35        NodeId::new()
36    }
37}
38
39impl Display for NodeId {
40    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
41        write!(f, "N{}", self.0)
42    }
43}