cxx_build/
intern.rs

1use crate::syntax::set::UnorderedSet as Set;
2use std::sync::{Mutex, OnceLock, PoisonError};
3
4#[derive(Copy, Clone, Default)]
5pub(crate) struct InternedString(&'static str);
6
7impl InternedString {
8    pub(crate) fn str(self) -> &'static str {
9        self.0
10    }
11}
12
13pub(crate) fn intern(s: &str) -> InternedString {
14    static INTERN: OnceLock<Mutex<Set<&'static str>>> = OnceLock::new();
15
16    let mut set = INTERN
17        .get_or_init(|| Mutex::new(Set::new()))
18        .lock()
19        .unwrap_or_else(PoisonError::into_inner);
20
21    InternedString(match set.get(s) {
22        Some(interned) => *interned,
23        None => {
24            let interned = Box::leak(Box::from(s));
25            set.insert(interned);
26            interned
27        }
28    })
29}