strata_primitives/
entity.rs1use std::sync::atomic::{AtomicU64, Ordering};
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
8pub struct EntityId(pub u64);
9
10impl EntityId {
11 pub const NONE: Self = Self(0);
13
14 #[inline]
16 pub const fn new(id: u64) -> Self {
17 Self(id)
18 }
19
20 #[inline]
22 pub fn next() -> Self {
23 static COUNTER: AtomicU64 = AtomicU64::new(1);
24 Self(COUNTER.fetch_add(1, Ordering::Relaxed))
25 }
26
27 #[inline]
29 pub const fn raw(&self) -> u64 {
30 self.0
31 }
32
33 #[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}