Skip to main content

source_vmt/
interner.rs

1#[cfg(feature = "intern_keys")]
2use std::sync::{Arc, LazyLock};
3
4#[cfg(feature = "intern_keys")]
5static KEY_POOL: LazyLock<dashmap::DashSet<Arc<str>>> = LazyLock::new(|| dashmap::DashSet::new());
6
7#[cfg(feature = "intern_keys")]
8pub type VmtKey = Arc<str>;
9
10#[cfg(not(feature = "intern_keys"))]
11pub type VmtKey = String;
12
13/// Interns a string into a global pool if "intern_keys" is enabled.
14/// Converts the key to lowercase for normalized lookups.
15pub fn intern_key(s: &str) -> VmtKey {
16    #[cfg(feature = "intern_keys")]
17    {
18        // First try to find the key without allocating a new lowercase string.
19        if let Some(existing) = KEY_POOL.get(s) {
20            return Arc::clone(&existing);
21        }
22
23        let lower = s.to_lowercase();
24        // Check again after lowercasing (in case it wasn't lowercase)
25        if let Some(existing) = KEY_POOL.get(lower.as_str()) {
26            return Arc::clone(&*existing);
27        }
28
29        let arc: Arc<str> = Arc::from(lower);
30        KEY_POOL.insert(Arc::clone(&arc));
31        arc
32    }
33    #[cfg(not(feature = "intern_keys"))]
34    {
35        s.to_lowercase()
36    }
37}