-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterner.rs
79 lines (67 loc) · 1.82 KB
/
interner.rs
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
use std::collections::HashMap;
use std::fmt;
use std::sync::Mutex;
use once_cell::sync::Lazy;
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub struct Symbol(usize);
struct Interner {
map: HashMap<String, Symbol>,
strings: Vec<String>,
}
impl Interner {
fn new() -> Self {
Self {
map: HashMap::new(),
strings: Vec::new(),
}
}
fn intern(&mut self, s: String) -> Symbol {
match self.map.get(&s) {
Some(&sym) => sym,
None => {
let sym = Symbol(self.strings.len());
self.map.insert(s.clone(), sym);
self.strings.push(s);
sym
}
}
}
fn intern_ref(&mut self, s: &str) -> Symbol {
match self.map.get(s) {
Some(&sym) => sym,
None => {
let sym = Symbol(self.strings.len());
self.map.insert(s.to_owned(), sym);
self.strings.push(s.to_owned());
sym
}
}
}
fn resolve(&self, sym: Symbol) -> &str {
&self.strings[sym.0]
}
}
static INTERNER: Lazy<Mutex<Interner>> = Lazy::new(|| Mutex::new(Interner::new()));
impl From<String> for Symbol {
fn from(s: String) -> Self {
INTERNER.lock().unwrap().intern(s)
}
}
impl From<&str> for Symbol {
fn from(s: &str) -> Self {
INTERNER.lock().unwrap().intern_ref(s)
}
}
impl fmt::Display for Symbol {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(INTERNER.lock().unwrap().resolve(*self))
}
}
impl fmt::Debug for Symbol {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Symbol")
.field("index", &self.0)
.field("str", &INTERNER.lock().unwrap().resolve(*self))
.finish()
}
}