async_ecs/entity/
entity.rs1use std::cmp::Ordering;
2use std::fmt::{Debug, Display, Formatter, Result as FmtResult};
3use std::hash::{Hash, Hasher};
4
5#[derive(Clone, Copy)]
7pub struct Entity(EntityRaw);
8
9pub type Index = u32;
11
12pub type Generation = u32;
14
15#[repr(C, packed)]
17#[derive(Clone, Copy)]
18union EntityRaw {
19 id: u64,
20 data: EntityData,
21}
22
23#[repr(C, packed)]
24#[derive(Clone, Copy)]
25struct EntityData {
26 index: Index,
27 generation: Generation,
28}
29
30impl Entity {
31 pub fn from_id(id: u64) -> Self {
33 Self(EntityRaw { id })
34 }
35
36 pub fn from_parts(index: Index, generation: Generation) -> Self {
38 Self(EntityRaw {
39 data: EntityData { index, generation },
40 })
41 }
42
43 #[inline]
45 pub fn id(&self) -> u64 {
46 unsafe { self.0.id }
47 }
48
49 #[inline]
51 pub fn index(&self) -> Index {
52 unsafe { self.0.data.index }
53 }
54
55 #[inline]
57 pub fn generation(&self) -> Generation {
58 unsafe { self.0.data.generation }
59 }
60}
61
62impl Display for Entity {
63 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
64 write!(f, "{:08X}", self.id())
65 }
66}
67
68impl Debug for Entity {
69 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
70 write!(f, "{:08X}", self.id())
71 }
72}
73
74impl Hash for Entity {
75 fn hash<H: Hasher>(&self, state: &mut H) {
76 self.index().hash(state);
77 self.generation().hash(state);
78 }
79}
80
81impl Eq for Entity {}
82
83impl PartialEq<Entity> for Entity {
84 fn eq(&self, other: &Entity) -> bool {
85 self.id() == other.id()
86 }
87}
88
89impl Ord for Entity {
90 fn cmp(&self, other: &Self) -> Ordering {
91 if self.generation() < other.generation() {
92 Ordering::Less
93 } else if self.generation() > other.generation() {
94 Ordering::Greater
95 } else if self.index() < other.index() {
96 Ordering::Less
97 } else if self.index() > other.index() {
98 Ordering::Greater
99 } else {
100 Ordering::Equal
101 }
102 }
103}
104
105impl PartialOrd for Entity {
106 fn partial_cmp(&self, other: &Entity) -> Option<Ordering> {
107 Some(Ord::cmp(self, other))
108 }
109}