rust/crates/proc-macro-srv/src/abis/abi_sysroot/ra_server/symbol.rs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

53 lines
1.3 KiB
Rust
Raw Normal View History

2022-07-21 06:37:41 -05:00
//! Symbol interner for proc-macro-srv
use std::{cell::RefCell, collections::HashMap};
2022-07-20 11:36:10 -05:00
use tt::SmolStr;
thread_local! {
static SYMBOL_INTERNER: RefCell<SymbolInterner> = 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)]
struct SymbolInterner {
2022-07-20 11:36:10 -05:00
idents: HashMap<SmolStr, u32>,
ident_data: Vec<SmolStr>,
}
impl SymbolInterner {
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
}
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
}
}