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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
use std::ffi::{self, CStr};
use std::fmt;
use std::hash::Hash;

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

/// A hash representing an immutable string stored in a global name pool.
#[derive(Debug, Default, Clone, Copy)]
#[repr(transparent)]
pub struct CName(red::CName);

impl CName {
    /// Creates a new `CName` from the given string.
    /// This function just calculates the hash of the string using the FNV-1a algorithm.
    /// If you want it to be added to the global name pool, use [`CNamePool::add_cstr`].
    #[inline]
    pub const fn new(name: &str) -> Self {
        Self::from_bytes(name.as_bytes())
    }

    pub const fn from_bytes(name: &[u8]) -> Self {
        #[allow(clippy::equatable_if_let)]
        if let b"None" = name {
            return Self::undefined();
        }
        Self(red::CName {
            hash: fnv1a64(name),
        })
    }

    /// Returns a [`CName`] representing an undefined name.
    #[inline]
    pub const fn undefined() -> Self {
        Self(red::CName { hash: 0 })
    }

    pub(super) fn from_raw(raw: red::CName) -> Self {
        Self(raw)
    }

    pub(super) fn to_raw(self) -> red::CName {
        self.0
    }

    /// Returns the string representation of the [`CName`].
    pub fn as_str(&self) -> &'static str {
        unsafe { ffi::CStr::from_ptr(self.0.ToString()) }
            .to_str()
            .unwrap()
    }
}

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

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

impl std::fmt::Display for CName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}",
            if self.0.hash == 0 {
                "None"
            } else {
                self.as_str()
            }
        )
    }
}

impl PartialEq for CName {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.0.hash == other.0.hash
    }
}

impl Eq for CName {}

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

impl Ord for CName {
    #[inline]
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.0.hash.cmp(&other.0.hash)
    }
}

impl Hash for CName {
    #[inline]
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.0.hash.hash(state)
    }
}

/// A global pool containing all [`CName`]s.
#[derive(Debug)]
#[repr(transparent)]
pub struct CNamePool(red::CNamePool);

impl CNamePool {
    pub fn add_cstr(str: &CStr) -> CName {
        unsafe {
            let add_cstr = crate::fn_from_hash!(
                CNamePool_AddCstr,
                unsafe extern "C" fn(&mut CName, *const i8)
            );
            let mut cname = CName::default();
            add_cstr(&mut cname, str.as_ptr());
            cname
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn calculate_hashes() {
        assert_eq!(
            u64::from(CName::new("IScriptable")),
            3_191_163_302_135_919_211
        );
        assert_eq!(u64::from(CName::new("Vector2")), 7_466_804_955_052_523_504);
        assert_eq!(u64::from(CName::new("Color")), 3_769_135_706_557_701_272);
        assert_eq!(u64::from(CName::new("None")), 0);
        assert_eq!(u64::from(CName::new("")), 0xCBF2_9CE4_8422_2325);
    }
}