use std::collections::HashMap;
use std::fmt;
use crate::index::Idx;
#[derive(Debug)]
pub struct SymbolTable;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Symbol(Idx<SymbolTable>);
impl Symbol {
#[inline]
pub const fn raw(self) -> u32 {
self.0.raw()
}
#[inline]
#[must_use]
pub const fn from_raw(raw: u32) -> Symbol {
Symbol(Idx::new(raw))
}
}
#[derive(Default)]
pub struct Interner {
buf: String,
spans: Vec<(u32, u32)>,
map: HashMap<Box<str>, Symbol>,
}
impl Interner {
pub fn new() -> Self {
Self::default()
}
pub fn with_capacity(cap: usize) -> Self {
Self {
buf: String::with_capacity(cap * 8),
spans: Vec::with_capacity(cap),
map: HashMap::with_capacity(cap),
}
}
pub fn intern(&mut self, s: &str) -> Symbol {
if let Some(&sym) = self.map.get(s) {
return sym;
}
let start = u32::try_from(self.buf.len()).expect("interner buffer overflow");
self.buf.push_str(s);
let end = u32::try_from(self.buf.len()).expect("interner buffer overflow");
let sym = Symbol(Idx::from_usize(self.spans.len()));
self.spans.push((start, end));
self.map.insert(s.into(), sym);
sym
}
pub fn resolve(&self, sym: Symbol) -> &str {
let (start, end) = self.spans[sym.0.index()];
&self.buf[start as usize..end as usize]
}
pub fn len(&self) -> usize {
self.spans.len()
}
pub fn is_empty(&self) -> bool {
self.spans.is_empty()
}
pub fn bytes(&self) -> usize {
self.buf.len()
}
}
impl fmt::Debug for Interner {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Interner")
.field("symbols", &self.spans.len())
.field("bytes", &self.buf.len())
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_same_string_gets_the_same_symbol() {
let mut i = Interner::new();
let a = i.intern("static_assert");
let b = i.intern("static_assert");
assert_eq!(a, b);
assert_eq!(i.len(), 1);
}
#[test]
fn different_strings_get_different_symbols() {
let mut i = Interner::new();
assert_ne!(i.intern("int"), i.intern("long"));
assert_eq!(i.len(), 2);
}
#[test]
fn resolves_back_to_the_text() {
let mut i = Interner::new();
let s = i.intern("__builtin_constant_p");
assert_eq!(i.resolve(s), "__builtin_constant_p");
}
#[test]
fn symbols_are_numbered_in_allocation_order() {
let mut i = Interner::new();
let first = i.intern("a");
let second = i.intern("b");
assert!(first < second, "symbol order must be allocation order, not hash order");
}
#[test]
fn the_empty_string_is_internable() {
let mut i = Interner::new();
let s = i.intern("");
assert_eq!(i.resolve(s), "");
assert_eq!(i.bytes(), 0);
}
#[test]
fn a_symbol_is_four_bytes() {
assert_eq!(size_of::<Symbol>(), 4);
assert_eq!(size_of::<Option<Symbol>>(), 4);
}
}