js_intern/
lib.rs

1//! Stores one copy of each distinct JavaScript primitive.
2//! For example, ```js_intern!("string")``` evaluates to a ```&JsValue``` but uses only one heap allocation
3//! and a one-time translation from the utf-8 Rust string to the utf-16 JavaScript string the first time the expression is evaluated.
4//! Furthermore, strings are de-duplicated across the program.
5//! So, any time ```js_intern!(1.0)``` is used in the program, the same instance of the JavaScript number is used.
6//!
7//! # Supported types
8//! * ```&'static str``` Eg: ```js_intern!("str")```
9//! * ```f64```, ```f32```, ```u8```, ```u16```, ```u32```, ```i8```, ```i16```, ```i32``` Eg: ```js_intern(1.0)```
10//! * ```bool``` Eg: ```js_intern(true)```
11//!
12//! # Related
13//! If you like this, you may like these other crates by Zac Burns (That3Percent)
14//! * [js-object](https://github.com/That3Percent/js-object) A macro for creating JavaScript objects
15//! * [soa-vec](https://github.com/That3Percent/soa-vec) A struct of arrays layout with a Vec of tuple API
16//! * [second-stack](https://github.com/That3Percent/second-stack) A memory allocator for large slices that don't escape the stack.
17pub use js_intern_core::js_intern;
18pub use js_intern_proc_macro::try_js_intern;
19
20#[cfg(test)]
21mod tests {
22	use super::*;
23	use wasm_bindgen_test::*;
24
25	#[wasm_bindgen_test]
26	fn can_convert_f64() {
27		assert_eq!(Some(20.0), js_intern!(20.0).as_f64());
28		assert!(js_intern!(std::f64::NAN).as_f64().unwrap().is_nan());
29	}
30
31	#[wasm_bindgen_test]
32	fn can_convert_int() {
33		assert_eq!(Some(1.0), js_intern!(1).as_f64());
34		assert!(js_intern!(std::f64::NAN).as_f64().unwrap().is_nan());
35	}
36
37	#[wasm_bindgen_test]
38	fn deduplicates_f64() {
39		assert_eq!(js_intern!(15.0) as *const _, js_intern!(15.0) as *const _);
40	}
41
42	#[wasm_bindgen_test]
43	fn can_convert_str() {
44		assert_eq!(js_intern!("b").as_string(), Some(String::from("b")));
45	}
46
47	#[wasm_bindgen_test]
48	fn deduplicates_str() {
49		assert_eq!(js_intern!("a") as *const _, js_intern!("a") as *const _);
50	}
51
52	#[wasm_bindgen_test]
53	fn can_convert_bool() {
54		assert_eq!(js_intern!(true).as_bool(), Some(true))
55	}
56
57	#[wasm_bindgen_test]
58	fn deduplicates_bool() {
59		assert_eq!(js_intern!(true) as *const _, js_intern!(true) as *const _);
60	}
61
62	// TODO: It would be nice to have tests around try_js_intern, but that would require enabling the proc_macro_hygiene feature,
63	// but I'm not sure what effect that would have on crates which would rely only on js_intern and not try_js_intern if they
64	// would also need to upgrade to nightly
65	/*
66	#[wasm_bindgen_test]
67	fn try_deduplicates_str_lit() {
68		assert_eq!(try_js_intern!("a") as *const _, js_intern!("a") as *const _);
69	}
70	*/
71
72}