deimos-lang/dmc-lib/src/constants_table.rs
2026-03-08 01:27:09 -06:00

36 lines
1000 B
Rust

use std::collections::HashMap;
use std::rc::Rc;
pub struct ConstantsTable {
string_counter: usize,
strings_to_names: HashMap<Rc<str>, Rc<str>>,
}
impl ConstantsTable {
pub fn new() -> Self {
Self {
string_counter: 0,
strings_to_names: HashMap::new(),
}
}
pub fn get_or_insert(&mut self, s: &str) -> Rc<str> {
if self.strings_to_names.contains_key(s) {
self.strings_to_names.get(s).unwrap().clone()
} else {
let name: Rc<str> = Rc::from(format!("s_{}", self.string_counter).as_str());
self.string_counter += 1;
self.strings_to_names.insert(s.into(), name.clone());
name
}
}
pub fn string_constants(&self) -> HashMap<Rc<str>, Rc<str>> {
let mut constants = HashMap::new();
self.strings_to_names.iter().for_each(|(content, name)| {
constants.insert(name.clone(), content.clone());
});
constants
}
}