rust/crates/proc-macro-srv/src/server/symbol.rs

47 lines
1.1 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);
impl Symbol {
2023-03-29 04:32:36 -05:00
pub(super) fn intern(data: &str) -> Symbol {
SYMBOL_INTERNER.with(|i| i.borrow_mut().intern(data))
}
2023-03-29 04:32:36 -05:00
pub(super) fn text(&self) -> SmolStr {
SYMBOL_INTERNER.with(|i| i.borrow().get(self).clone())
}
}
2022-07-20 11:36:10 -05:00
#[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]
}
}