#[cfg(feature = "enable-interning")]
use crate::JsValue;
#[cfg(feature = "enable-interning")]
use std::borrow::ToOwned;
#[cfg(feature = "enable-interning")]
use std::cell::RefCell;
#[cfg(feature = "enable-interning")]
use std::collections::HashMap;
#[cfg(feature = "enable-interning")]
use std::string::String;
#[cfg(feature = "enable-interning")]
use std::thread_local;
#[cfg(feature = "enable-interning")]
struct Cache {
entries: RefCell<HashMap<String, JsValue>>,
}
#[cfg(feature = "enable-interning")]
thread_local! {
static CACHE: Cache = Cache {
entries: RefCell::new(HashMap::new()),
};
}
#[cfg(feature = "enable-interning")]
pub(crate) fn unsafe_get_str(s: &str) -> Option<u64> {
CACHE.with(|cache| {
let cache = cache.entries.borrow();
cache.get(s).map(|x| x.idx)
})
}
#[cfg(all(test, feature = "enable-interning"))]
pub(crate) fn insert_for_test(key: &str, id: u64) {
CACHE.with(|cache| {
cache
.entries
.borrow_mut()
.insert(key.to_owned(), JsValue::from_id(id));
});
}
#[cfg(feature = "enable-interning")]
fn intern_str(key: &str) {
CACHE.with(|cache| {
let entries = &cache.entries;
if !entries.borrow().contains_key(key) {
let value = JsValue::from(key);
entries.borrow_mut().insert(key.to_owned(), value);
}
})
}
#[cfg(feature = "enable-interning")]
fn unintern_str(key: &str) {
CACHE.with(|cache| {
let mut cache = cache.entries.borrow_mut();
cache.remove(key);
})
}
#[inline]
pub fn intern(s: &str) -> &str {
#[cfg(feature = "enable-interning")]
intern_str(s);
s
}
#[allow(unused_variables)]
#[inline]
pub fn unintern(s: &str) {
#[cfg(feature = "enable-interning")]
unintern_str(s);
}