Skip to main content

radiate_utils/
intern.rs

1use std::{cell::RefCell, collections::HashSet};
2
3thread_local! {
4    pub static STR_INTERN_CACHE: RefCell<HashSet<&'static str>> = RefCell::new(HashSet::new());
5
6}
7
8#[macro_export]
9macro_rules! intern {
10    ($name:expr) => {{
11        $crate::STR_INTERN_CACHE.with(|interned| {
12            let mut interned = interned.borrow_mut();
13            if let Some(&existing) = interned.get(&*$name) {
14                existing
15            } else {
16                let name = String::from($name);
17                let static_name: &'static str = Box::leak(name.into_boxed_str());
18                interned.insert(static_name);
19                static_name
20            }
21        })
22    }};
23}
24
25pub fn is_str_interned(s: &str) -> bool {
26    STR_INTERN_CACHE.with(|interned| interned.borrow().contains(s))
27}