Skip to main content

strata_primitives/
entity.rs

1//! Entity identification primitive for cross-subsystem DOM and layout synchronization.
2
3use std::sync::atomic::{AtomicU64, Ordering};
4
5/// Globally unique 64-bit entity identifier associating reactive blueprints,
6/// DOM elements, computed layout nodes, and spatial indices.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
8pub struct EntityId(pub u64);
9
10impl EntityId {
11    /// Sentinel unassigned entity ID.
12    pub const NONE: Self = Self(0);
13
14    /// Constructs an entity ID from a raw 64-bit integer.
15    #[inline]
16    pub const fn new(id: u64) -> Self {
17        Self(id)
18    }
19
20    /// Allocates the next sequentially unique entity ID across all threads.
21    #[inline]
22    pub fn next() -> Self {
23        static COUNTER: AtomicU64 = AtomicU64::new(1);
24        Self(COUNTER.fetch_add(1, Ordering::Relaxed))
25    }
26
27    /// Returns the raw 64-bit integer.
28    #[inline]
29    pub const fn raw(&self) -> u64 {
30        self.0
31    }
32
33    /// Returns true if this entity ID is valid (non-zero).
34    #[inline]
35    pub const fn is_valid(&self) -> bool {
36        self.0 != 0
37    }
38}
39
40impl std::fmt::Display for EntityId {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        write!(f, "EntityId({})", self.0)
43    }
44}
45
46#[cfg(test)]
47mod tests {
48    use super::*;
49
50    #[test]
51    fn test_entity_id_basics() {
52        assert_eq!(EntityId::NONE.raw(), 0);
53        assert!(!EntityId::NONE.is_valid());
54
55        let id1 = EntityId::new(42);
56        assert_eq!(id1.raw(), 42);
57        assert!(id1.is_valid());
58        assert_eq!(format!("{}", id1), "EntityId(42)");
59
60        let next1 = EntityId::next();
61        let next2 = EntityId::next();
62        assert!(next1.is_valid());
63        assert!(next2.is_valid());
64        assert_eq!(next2.raw(), next1.raw() + 1);
65    }
66}