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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
use std::fmt;
use std::hash::Hash;

use crate::raw::root::RED4ext as red;

#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct EntityId(red::ent::EntityID);

impl EntityId {
    #[inline]
    pub const fn is_defined(self) -> bool {
        self.0.hash != 0
    }

    #[inline]
    pub const fn is_static(self) -> bool {
        self.0.hash != 0 && self.0.hash > red::ent::EntityID_DynamicUpperBound
    }

    #[inline]
    pub const fn is_dynamic(self) -> bool {
        self.0.hash != 0 && self.0.hash <= red::ent::EntityID_DynamicUpperBound
    }

    #[inline]
    pub const fn is_persistable(self) -> bool {
        self.0.hash >= red::ent::EntityID_PersistableLowerBound
            && self.0.hash < red::ent::EntityID_PersistableUpperBound
    }

    #[inline]
    pub const fn is_transient(self) -> bool {
        self.0.hash != 0 && !self.is_persistable()
    }
}

impl PartialEq for EntityId {
    fn eq(&self, other: &Self) -> bool {
        self.0.hash == other.0.hash
    }
}

impl Eq for EntityId {}

impl PartialOrd for EntityId {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for EntityId {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.0.hash.cmp(&other.0.hash)
    }
}

impl Hash for EntityId {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.0.hash.hash(state);
    }
}

impl Default for EntityId {
    fn default() -> Self {
        Self(red::ent::EntityID { hash: 0 })
    }
}

impl From<u64> for EntityId {
    fn from(hash: u64) -> Self {
        Self(red::ent::EntityID { hash })
    }
}

impl From<EntityId> for u64 {
    fn from(EntityId(red::ent::EntityID { hash }): EntityId) -> Self {
        hash
    }
}

impl fmt::Debug for EntityId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut attrs = f.debug_set(); // transient and persistable are exclusive
        if self.is_defined() {
            if self.is_dynamic() {
                attrs.entry(&"dynamic");
            } else {
                attrs.entry(&"static");
            }
            if self.is_transient() {
                attrs.entry(&"transient");
            }
        }
        if self.is_persistable() {
            attrs.entry(&"persistable");
        }
        let flags = attrs.finish();
        f.debug_struct("EntityId")
            .field("hash", &self.0.hash)
            .field("flags", &flags)
            .finish_non_exhaustive()
    }
}