runes-core 0.1.0

Core types and traits for the Runes language
Documentation
use std::collections::HashMap;

/// An interned symbol identifier. Two symbols with the same name
/// have the same SymbolId — identity comparison, not string comparison.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct SymbolId(pub u32);

/// Interns symbol names to SymbolIds for fast equality checks.
#[derive(Debug, Default)]
pub struct SymbolTable {
    names: Vec<String>,
    lookup: HashMap<String, SymbolId>,
}

impl SymbolTable {
    pub fn new() -> Self {
        Self::default()
    }

    /// Intern a symbol name, returning its unique ID.
    /// If already interned, returns the existing ID.
    pub fn intern(&mut self, name: &str) -> SymbolId {
        if let Some(&id) = self.lookup.get(name) {
            return id;
        }
        let id = SymbolId(self.names.len() as u32);
        self.names.push(name.to_owned());
        self.lookup.insert(name.to_owned(), id);
        id
    }

    /// Resolve a SymbolId back to its name.
    /// Panics if the ID is invalid.
    pub fn resolve(&self, id: SymbolId) -> &str {
        &self.names[id.0 as usize]
    }

    /// Try to resolve a SymbolId, returning None if invalid.
    pub fn try_resolve(&self, id: SymbolId) -> Option<&str> {
        self.names.get(id.0 as usize).map(|s| s.as_str())
    }

    /// Look up a symbol by name without interning it.
    pub fn lookup(&self, name: &str) -> Option<SymbolId> {
        self.lookup.get(name).copied()
    }

    /// Number of interned symbols.
    pub fn len(&self) -> usize {
        self.names.len()
    }

    pub fn is_empty(&self) -> bool {
        self.names.is_empty()
    }
}