Skip to content

Commit

Permalink
Changing from uluru to HashMap
Browse files Browse the repository at this point in the history
  • Loading branch information
Pauan committed Jul 18, 2019
1 parent 4d834ae commit 2481829
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 30 deletions.
3 changes: 1 addition & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ spans = ["wasm-bindgen-macro/spans"]
std = []
serde-serialize = ["serde", "serde_json", "std"]
nightly = []
enable-interning = ["std", "uluru"]
enable-interning = ["std"]

# Whether or not the `#[wasm_bindgen]` macro is strict and generates an error on
# all unused attributes
Expand All @@ -39,7 +39,6 @@ xxx_debug_only_print_generated_code = ["wasm-bindgen-macro/xxx_debug_only_print_
wasm-bindgen-macro = { path = "crates/macro", version = "=0.2.48" }
serde = { version = "1.0", optional = true }
serde_json = { version = "1.0", optional = true }
uluru = { version = "0.3.0", optional = true }
cfg-if = "0.1.9"

[target.'cfg(target_arch = "wasm32")'.dev-dependencies]
Expand Down
36 changes: 8 additions & 28 deletions src/cache/intern.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,57 +7,37 @@ cfg_if! {
use std::string::String;
use std::borrow::ToOwned;
use std::cell::RefCell;
use std::collections::HashMap;
use crate::JsValue;
use crate::convert::IntoWasmAbi;
use uluru::{LRUCache, Entry};


struct Pair {
key: String,
value: JsValue,
}

// TODO figure out a good default capacity
type Entries = LRUCache::<[Entry<Pair>; 1_024]>;

struct Cache {
entries: RefCell<Entries>,
entries: RefCell<HashMap<String, JsValue>>,
}

thread_local! {
static CACHE: Cache = Cache {
entries: RefCell::new(LRUCache::default()),
entries: RefCell::new(HashMap::new()),
};
}

fn get_js_string<'a>(cache: &'a mut Entries, key: &str) -> Option<&'a JsValue> {
cache.find(|p| p.key == key).map(|x| &x.value)
}

/// This returns the raw index of the cached JsValue, so you must take care
/// so that you don't use it after it is freed.
pub(crate) fn unsafe_get_str(s: &str) -> Option<<JsValue as IntoWasmAbi>::Abi> {
CACHE.with(|cache| {
let mut cache = cache.entries.borrow_mut();
let cache = cache.entries.borrow();

if let Some(value) = get_js_string(&mut cache, s) {
Some(value.into_abi())

} else {
None
}
cache.get(s).map(|x| x.into_abi())
})
}

fn intern_str(key: &str) {
CACHE.with(|cache| {
let mut cache = cache.entries.borrow_mut();

if get_js_string(&mut cache, key).is_none() {
cache.insert(Pair {
key: key.to_owned(),
value: JsValue::from(key),
});
// Can't use `entry` because `entry` requires a `String`
if !cache.contains_key(key) {
cache.insert(key.to_owned(), JsValue::from(key));
}
})
}
Expand Down

0 comments on commit 2481829

Please sign in to comment.