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
use std::fmt;
use std::str::FromStr;
use std::sync::Mutex;
use indexmap::IndexSet;
use once_cell::sync::Lazy;
static STRINGS: Lazy<Mutex<IndexSet<&'static str>>> = Lazy::new(Default::default);
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Symbol(u32);
impl Symbol {
pub fn as_str(self) -> &'static str {
let i = self.0 as usize;
let strings = STRINGS
.lock()
.unwrap_or_else(|err| panic!("Failed to acquire egg's global string cache: {}", err));
strings.get_index(i).unwrap()
}
}
fn leak(s: &str) -> &'static str {
Box::leak(s.to_owned().into_boxed_str())
}
fn intern(s: &str) -> Symbol {
let mut strings = STRINGS
.lock()
.unwrap_or_else(|err| panic!("Failed to acquire egg's global string cache: {}", err));
let i = match strings.get_full(s) {
Some((i, _)) => i,
None => strings.insert_full(leak(s)).0,
};
Symbol(i as u32)
}
impl<S: AsRef<str>> From<S> for Symbol {
fn from(s: S) -> Self {
intern(s.as_ref())
}
}
impl FromStr for Symbol {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(s.into())
}
}
impl fmt::Display for Symbol {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.as_str())
}
}
impl fmt::Debug for Symbol {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self.as_str())
}
}