Making interning manual

This commit is contained in:
Pauan 2019-06-22 23:39:23 +02:00
parent 86a8842f24
commit 0a61e12bd1
2 changed files with 31 additions and 42 deletions

61
src/cache/intern.rs vendored
View File

@ -15,44 +15,33 @@ struct Pair {
type Entries = LRUCache::<[Entry<Pair>; 1_024]>; type Entries = LRUCache::<[Entry<Pair>; 1_024]>;
struct Cache { struct Cache {
enabled: Cell<bool>,
max_str_len: Cell<usize>,
entries: RefCell<Entries>, entries: RefCell<Entries>,
} }
// TODO figure out a good max_str_len // TODO figure out a good max_str_len
thread_local! { thread_local! {
static CACHE: Cache = Cache { static CACHE: Cache = Cache {
enabled: Cell::new(true),
max_str_len: Cell::new(128),
entries: RefCell::new(LRUCache::default()), entries: RefCell::new(LRUCache::default()),
}; };
} }
fn get_js_string(cache: &mut Entries, key: &str) -> JsValue { fn get_js_string<'a>(cache: &'a mut Entries, key: &str) -> Option<&'a JsValue> {
if let Some(p) = cache.find(|p| p.key == key) { cache.find(|p| p.key == key).map(|x| &x.value)
p.value.clone() }
} else {
let value = JsValue::from(key);
fn insert_js_string(cache: &mut Entries, key: &str, value: JsValue) {
cache.insert(Pair { cache.insert(Pair {
key: key.to_owned(), key: key.to_owned(),
value: value.clone(), value,
}); });
value
}
} }
fn cache_str(s: &str) -> JsValue { fn get_str(s: &str) -> JsValue {
CACHE.with(|cache| { CACHE.with(|cache| {
let should_cache = let mut cache = cache.entries.borrow_mut();
cache.enabled.get() &&
s.len() <= cache.max_str_len.get();
if should_cache { if let Some(value) = get_js_string(&mut cache, s) {
get_js_string(&mut cache.entries.borrow_mut(), s) value.clone()
} else { } else {
JsValue::from(s) JsValue::from(s)
@ -60,33 +49,31 @@ fn cache_str(s: &str) -> JsValue {
}) })
} }
fn intern_str(s: &str) {
CACHE.with(|cache| {
let mut cache = cache.entries.borrow_mut();
if get_js_string(&mut cache, s).is_none() {
insert_js_string(&mut cache, s, JsValue::from(s));
}
})
}
#[inline] #[inline]
pub fn str(s: &str) -> JsValue { pub(crate) fn str(s: &str) -> JsValue {
if cfg!(feature = "disable-interning") { if cfg!(feature = "disable-interning") {
JsValue::from(s) JsValue::from(s)
} else { } else {
cache_str(s) get_str(s)
} }
} }
#[inline] #[inline]
pub fn set_max_str_len(len: usize) { pub fn intern(s: &str) -> &str {
if !cfg!(feature = "disable-interning") { if !cfg!(feature = "disable-interning") {
CACHE.with(|cache| cache.max_str_len.set(len)); intern_str(s);
}
} }
#[inline] s
pub fn enable() {
if !cfg!(feature = "disable-interning") {
CACHE.with(|cache| cache.enabled.set(true));
}
}
#[inline]
pub fn disable() {
if !cfg!(feature = "disable-interning") {
CACHE.with(|cache| cache.enabled.set(false));
}
} }

View File

@ -62,6 +62,8 @@ mod cache;
pub mod convert; pub mod convert;
pub mod describe; pub mod describe;
pub use cache::intern::intern;
mod cast; mod cast;
pub use crate::cast::JsCast; pub use crate::cast::JsCast;