use rustc_hash::FxHashMap;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Sym(u32);
impl Sym {
pub const EMPTY: Sym = Sym(0);
pub const fn index(self) -> usize {
self.0 as usize
}
}
#[derive(Debug, Clone)]
pub struct StringPool {
strings: Vec<Box<str>>,
index: FxHashMap<Box<str>, Sym>,
}
impl Default for StringPool {
fn default() -> Self {
let mut pool = Self {
strings: Vec::new(),
index: FxHashMap::default(),
};
pool.intern("");
pool
}
}
impl StringPool {
pub fn new() -> Self {
Self::default()
}
pub fn intern(&mut self, s: &str) -> Sym {
if let Some(&sym) = self.index.get(s) {
return sym;
}
let sym = Sym(u32::try_from(self.strings.len()).expect("fewer than 2^32 distinct strings"));
self.strings.push(s.into());
self.index.insert(s.into(), sym);
sym
}
pub(crate) fn intern_bytes(&mut self, bytes: &[u8]) -> Sym {
match std::str::from_utf8(bytes) {
Ok(s) => self.intern(s),
Err(_) => self.intern(&String::from_utf8_lossy(bytes)),
}
}
pub fn get(&self, sym: Sym) -> &str {
&self.strings[sym.index()]
}
pub fn find(&self, s: &str) -> Option<Sym> {
self.index.get(s).copied()
}
pub fn len(&self) -> usize {
self.strings.len()
}
pub fn is_empty(&self) -> bool {
false
}
pub fn iter(&self) -> impl Iterator<Item = (Sym, &str)> {
self.strings
.iter()
.enumerate()
.map(|(i, s)| (Sym(i as u32), &**s))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn interning_is_stable() {
let mut pool = StringPool::new();
assert_eq!(pool.get(Sym::EMPTY), "");
assert_eq!(pool.intern(""), Sym::EMPTY);
let a = pool.intern("ALA");
let b = pool.intern("GLY");
assert_eq!(pool.intern("ALA"), a);
assert_ne!(a, b);
assert_eq!(pool.get(b), "GLY");
assert_eq!(pool.find("GLY"), Some(b));
assert_eq!(pool.find("SER"), None);
assert_eq!(pool.len(), 3);
assert_eq!(pool.intern_bytes(b"\xffX"), pool.find("\u{fffd}X").unwrap());
}
}