2022-07-20 12:13:06 -05:00
|
|
|
use once_cell::sync::Lazy;
|
|
|
|
use std::{collections::HashMap, sync::Mutex};
|
2022-07-20 11:36:10 -05:00
|
|
|
use tt::SmolStr;
|
|
|
|
|
2022-07-20 12:13:06 -05:00
|
|
|
pub(super) static SYMBOL_INTERNER: Lazy<Mutex<SymbolInterner>> = Lazy::new(|| Default::default());
|
|
|
|
|
|
|
|
// ID for an interned symbol.
|
2022-07-20 11:36:10 -05:00
|
|
|
#[derive(Hash, Eq, PartialEq, Copy, Clone)]
|
|
|
|
pub struct Symbol(u32);
|
|
|
|
|
|
|
|
#[derive(Default)]
|
2022-07-20 12:13:06 -05:00
|
|
|
pub(super) struct SymbolInterner {
|
2022-07-20 11:36:10 -05:00
|
|
|
idents: HashMap<SmolStr, u32>,
|
|
|
|
ident_data: Vec<SmolStr>,
|
|
|
|
}
|
|
|
|
|
2022-07-20 12:13:06 -05:00
|
|
|
impl SymbolInterner {
|
|
|
|
pub(super) fn intern(&mut self, data: &str) -> Symbol {
|
2022-07-20 11:36:10 -05:00
|
|
|
if let Some(index) = self.idents.get(data) {
|
2022-07-20 11:43:59 -05:00
|
|
|
return Symbol(*index);
|
2022-07-20 11:36:10 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
let index = self.idents.len() as u32;
|
2022-07-20 11:43:59 -05:00
|
|
|
let data = SmolStr::from(data);
|
2022-07-20 11:36:10 -05:00
|
|
|
self.ident_data.push(data.clone());
|
2022-07-20 11:43:59 -05:00
|
|
|
self.idents.insert(data, index);
|
|
|
|
Symbol(index)
|
2022-07-20 11:36:10 -05:00
|
|
|
}
|
|
|
|
|
2022-07-20 12:13:06 -05:00
|
|
|
pub(super) fn get(&self, index: &Symbol) -> &SmolStr {
|
|
|
|
&self.ident_data[index.0 as usize]
|
2022-07-20 11:36:10 -05:00
|
|
|
}
|
|
|
|
}
|