Skip to main content

runes_core/
symbol.rs

1use std::collections::HashMap;
2
3/// An interned symbol identifier. Two symbols with the same name
4/// have the same SymbolId — identity comparison, not string comparison.
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
6pub struct SymbolId(pub u32);
7
8/// Interns symbol names to SymbolIds for fast equality checks.
9#[derive(Debug, Default)]
10pub struct SymbolTable {
11    names: Vec<String>,
12    lookup: HashMap<String, SymbolId>,
13}
14
15impl SymbolTable {
16    pub fn new() -> Self {
17        Self::default()
18    }
19
20    /// Intern a symbol name, returning its unique ID.
21    /// If already interned, returns the existing ID.
22    pub fn intern(&mut self, name: &str) -> SymbolId {
23        if let Some(&id) = self.lookup.get(name) {
24            return id;
25        }
26        let id = SymbolId(self.names.len() as u32);
27        self.names.push(name.to_owned());
28        self.lookup.insert(name.to_owned(), id);
29        id
30    }
31
32    /// Resolve a SymbolId back to its name.
33    /// Panics if the ID is invalid.
34    pub fn resolve(&self, id: SymbolId) -> &str {
35        &self.names[id.0 as usize]
36    }
37
38    /// Try to resolve a SymbolId, returning None if invalid.
39    pub fn try_resolve(&self, id: SymbolId) -> Option<&str> {
40        self.names.get(id.0 as usize).map(|s| s.as_str())
41    }
42
43    /// Look up a symbol by name without interning it.
44    pub fn lookup(&self, name: &str) -> Option<SymbolId> {
45        self.lookup.get(name).copied()
46    }
47
48    /// Number of interned symbols.
49    pub fn len(&self) -> usize {
50        self.names.len()
51    }
52
53    pub fn is_empty(&self) -> bool {
54        self.names.is_empty()
55    }
56}