1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
use std::fmt::{Debug, Formatter};
use std::mem::transmute;
use std::sync::atomic::{AtomicU32, Ordering};
use crate::util::{gen_mask_64, BitMask, NumberExt};
static NEXT: AtomicU32 = AtomicU32::new(1);
const ID_BITS: BitMask<u64> = BitMask::new(gen_mask_64!(32..=63));
const KIND_BITS: BitMask<u64> = BitMask::new(gen_mask_64!(0..=1));
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
#[repr(u8)]
pub enum Kind
{
Entity = 2,
Component = 1,
}
/// Unique entity/component ID.
#[derive(Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct Uid
{
inner: u64,
}
impl Uid
{
/// Returns a new unique entity/component ID.
pub fn new_unique(kind: Kind) -> Self
{
let id = NEXT.fetch_add(1, Ordering::Relaxed);
Self {
inner: ID_BITS.field_prep(u64::from(id)) | KIND_BITS.field_prep(kind as u64),
}
}
#[must_use]
pub fn id(&self) -> u32
{
let Ok(id) = u32::try_from(self.inner.field_get(ID_BITS)) else {
unreachable!("Uid id does not fit in u32");
};
id
}
#[must_use]
pub fn kind(&self) -> Kind
{
let Ok(kind) = u8::try_from(self.inner.field_get(KIND_BITS)) else {
unreachable!("Uid kind does not fit in u8");
};
// SAFETY: The kind bits cannot be invalid since they are set using the Kind enum
// in the new_unique function
unsafe { transmute::<u8, Kind>(kind) }
}
}
impl Debug for Uid
{
fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result
{
formatter
.debug_struct("Uid")
.field("id", &self.id())
.field("kind", &self.kind())
.finish_non_exhaustive()
}
}
|