wasm_bindgen/cache/intern.rs
1use cfg_if::cfg_if;
2
3cfg_if! {
4 if #[cfg(feature = "enable-interning")] {
5 use std::thread_local;
6 use std::vec::Vec;
7 use std::cell::RefCell;
8 use std::collections::HashMap;
9 use crate::JsValue;
10
11 // Keyed by bytes so both `&str` and `&[u8]` can probe without
12 // allocating; every key is a valid UTF-8 string since insertion is
13 // only via `intern(&str)`.
14 struct Cache {
15 entries: RefCell<HashMap<Vec<u8>, JsValue>>,
16 }
17
18 thread_local! {
19 static CACHE: Cache = Cache {
20 entries: RefCell::new(HashMap::new()),
21 };
22 }
23
24 /// This returns the raw index of the cached JsValue, so you must take care
25 /// so that you don't use it after it is freed.
26 pub(crate) fn unsafe_get_str(s: &str) -> Option<u32> {
27 CACHE.with(|cache| {
28 let cache = cache.entries.borrow();
29
30 cache.get(s.as_bytes()).map(|x| x.idx)
31 })
32 }
33
34 pub(crate) fn get_bytes(bytes: &[u8]) -> Option<JsValue> {
35 CACHE.with(|cache| {
36 let cache = cache.entries.borrow();
37
38 cache.get(bytes).cloned()
39 })
40 }
41
42 fn intern_str(key: &str) {
43 CACHE.with(|cache| {
44 let entries = &cache.entries;
45
46 // Can't use `entry` because `entry` requires an owned key
47 if !entries.borrow().contains_key(key.as_bytes()) {
48 // Note: we must not hold the borrow while we create the `JsValue`,
49 // because it will try to look up the value in the cache first.
50 let value = JsValue::from(key);
51 entries.borrow_mut().insert(key.as_bytes().to_vec(), value);
52 }
53 })
54 }
55
56 fn unintern_str(key: &str) {
57 CACHE.with(|cache| {
58 let mut cache = cache.entries.borrow_mut();
59
60 cache.remove(key.as_bytes());
61 })
62 }
63 }
64}
65
66/// Interns Rust strings so that it's much faster to send them to JS.
67///
68/// Sending strings from Rust to JS is slow, because it has to do a full `O(n)`
69/// copy and *also* encode from UTF-8 to UTF-16. This must be done every single
70/// time a string is sent to JS.
71///
72/// If you are sending the same string multiple times, you can call this `intern`
73/// function, which simply returns its argument unchanged:
74///
75/// ```rust
76/// # use wasm_bindgen::intern;
77/// intern("foo") // returns "foo"
78/// # ;
79/// ```
80///
81/// However, if you enable the `"enable-interning"` feature for wasm-bindgen,
82/// then it will add the string into an internal cache.
83///
84/// When you send that cached string to JS, it will look it up in the cache,
85/// which completely avoids the `O(n)` copy and encoding. This has a significant
86/// speed boost (as high as 783%)!
87///
88/// However, there is a small cost to this caching, so you shouldn't cache every
89/// string. Only cache strings which have a high likelihood of being sent
90/// to JS multiple times.
91///
92/// Also, keep in mind that this function is a *performance hint*: it's not
93/// *guaranteed* that the string will be cached, and the caching strategy
94/// might change at any time, so don't rely upon it.
95#[inline]
96pub fn intern(s: &str) -> &str {
97 #[cfg(feature = "enable-interning")]
98 intern_str(s);
99
100 s
101}
102
103/// Removes a Rust string from the intern cache.
104///
105/// This does the opposite of the [`intern`](fn.intern.html) function.
106///
107/// If the [`intern`](fn.intern.html) function is called again then it will re-intern the string.
108#[allow(unused_variables)]
109#[inline]
110pub fn unintern(s: &str) {
111 #[cfg(feature = "enable-interning")]
112 unintern_str(s);
113}