2022-07-21 06:37:41 -05:00
|
|
|
//! Symbol interner for proc-macro-srv
|
|
|
|
|
2022-07-21 07:57:09 -05:00
|
|
|
use std::{cell::RefCell, collections::HashMap};
|
2022-07-20 11:36:10 -05:00
|
|
|
use tt::SmolStr;
|
|
|
|
|
2022-07-21 07:57:09 -05:00
|
|
|
thread_local! {
|
|
|
|
static SYMBOL_INTERNER: RefCell<SymbolInterner> = Default::default();
|
|
|
|
}
|
2022-07-20 12:13:06 -05:00
|
|
|
|
|
|
|
// 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-21 07:57:09 -05:00
|
|
|
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 {
|
2022-07-21 07:57:09 -05:00
|
|
|
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-21 07:57:09 -05:00
|
|
|
fn get(&self, sym: &Symbol) -> &SmolStr {
|
|
|
|
&self.ident_data[sym.0 as usize]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub(super) struct ThreadLocalSymbolInterner;
|
|
|
|
|
|
|
|
impl ThreadLocalSymbolInterner {
|
|
|
|
pub(super) fn intern(data: &str) -> Symbol {
|
|
|
|
SYMBOL_INTERNER.with(|i| i.borrow_mut().intern(data))
|
|
|
|
}
|
|
|
|
|
|
|
|
pub(super) fn with<T>(sym: &Symbol, f: impl FnOnce(&SmolStr) -> T) -> T {
|
|
|
|
SYMBOL_INTERNER.with(|i| f(i.borrow().get(sym)))
|
|
|
|
}
|
|
|
|
|
|
|
|
pub(super) fn get_cloned(sym: &Symbol) -> SmolStr {
|
|
|
|
Self::with(sym, |s| s.clone())
|
2022-07-20 11:36:10 -05:00
|
|
|
}
|
|
|
|
}
|