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
use arraystring::{typenum::U16, ArrayString};
use core::sync::atomic::AtomicU32;
use std::fmt::{self, Formatter};
use std::sync::atomic::Ordering;

type TagStr = ArrayString<U16>;

/// Used to identify components.
#[derive(Copy, Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct ComponentId {
    #[cfg(debug_assertions)]
    tag: TagStr,

    id: u32,
}

impl ComponentId {
    #[cfg(debug_assertions)]
    pub fn new(tag: &str, value: u32) -> ComponentId {
        ComponentId {
            tag: TagStr::from_str_truncate(tag),
            id: value,
        }
    }

    #[cfg(not(debug_assertions))]
    pub fn new(_tag: &str, value: u32) -> ComponentId {
        Oid { id: value }
    }
}

static NEXT_COMPONENT_ID: AtomicU32 = AtomicU32::new(1);

#[doc(hidden)]
#[cfg(debug_assertions)]
pub fn next_component_id(tag: &str) -> ComponentId {
    ComponentId::new(tag, NEXT_COMPONENT_ID.fetch_add(1, Ordering::Relaxed))
}

#[doc(hidden)]
#[cfg(not(debug_assertions))]
pub fn next_component_id(_tag: &str) -> ComponentId {
    ComponentId::new(NEXT_COMPONENT_ID.fetch_add(1, Ordering::Relaxed))
}

impl fmt::Debug for ComponentId {
    #[cfg(debug_assertions)]
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}#{}", self.tag, self.id)
    }

    #[cfg(not(debug_assertions))]
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "#{}", self.id)
    }
}

impl fmt::Display for ComponentId {
    #[cfg(debug_assertions)]
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}#{}", self.tag, self.id)
    }

    #[cfg(not(debug_assertions))]
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "#{}", self.id)
    }
}