use std::{
cell::RefCell,
collections::HashMap,
fmt,
fmt::{Error, Formatter},
rc::Rc,
};
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
pub struct Symbol(usize);
impl Symbol {
pub fn display<'a>(&'a self, pool: &'a SymbolPool) -> SymbolDisplay<'a> {
SymbolDisplay { sym: self, pool }
}
}
pub struct SymbolDisplay<'a> {
sym: &'a Symbol,
pool: &'a SymbolPool,
}
impl<'a> fmt::Display for SymbolDisplay<'a> {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
f.write_str(&self.pool.string(*self.sym))
}
}
#[derive(Debug)]
pub struct SymbolPool {
inner: RefCell<InnerPool>,
}
#[derive(Debug)]
struct InnerPool {
strings: Vec<Rc<String>>,
lookup: HashMap<Rc<String>, usize>,
}
impl SymbolPool {
pub fn new() -> SymbolPool {
SymbolPool {
inner: RefCell::new(InnerPool {
strings: vec![],
lookup: HashMap::new(),
}),
}
}
pub fn make(&self, s: &str) -> Symbol {
let mut pool = self.inner.borrow_mut();
let key = Rc::new(s.to_string());
if let Some(n) = pool.lookup.get(&key) {
return Symbol(*n);
}
let new_sym = pool.strings.len();
pool.strings.push(key.clone());
pool.lookup.insert(key, new_sym);
Symbol(new_sym)
}
pub fn string(&self, sym: Symbol) -> Rc<String> {
self.inner.borrow().strings[sym.0].clone()
}
}
impl Default for SymbolPool {
fn default() -> Self {
Self::new()
}
}