wasm_bindgen/lib.rs
1//! Runtime support for the `wasm-bindgen` tool
2//!
3//! This crate contains the runtime support necessary for `wasm-bindgen` the
4//! attribute and tool. Crates pull in the `#[wasm_bindgen]` attribute through
5//! this crate and this crate also provides JS bindings through the `JsValue`
6//! interface.
7//!
8//! ## Features
9//!
10//! ### `enable-interning`
11//!
12//! Enables the internal cache for [`wasm_bindgen::intern`].
13//!
14//! This feature currently enables the `std` feature, meaning that it is not
15//! compatible with `no_std` environments.
16//!
17//! ### `std` (default)
18//!
19//! Enabling this feature will make the crate depend on the Rust standard library.
20//!
21//! Disable this feature to use this crate in `no_std` environments.
22//!
23//! ### `strict-macro`
24//!
25//! All warnings the `#[wasm_bindgen]` macro emits are turned into hard errors.
26//! This mainly affects unused attribute options.
27//!
28//! ### Deprecated features
29//!
30//! #### `serde-serialize`
31//!
32//! **Deprecated:** Use the [`serde-wasm-bindgen`](https://docs.rs/serde-wasm-bindgen/latest/serde_wasm_bindgen/) crate instead.
33//!
34//! Enables the `JsValue::from_serde` and `JsValue::into_serde` methods for
35//! serializing and deserializing Rust types to and from JavaScript.
36//!
37//! #### `spans`
38//!
39//! **Deprecated:** This feature became a no-op in wasm-bindgen v0.2.20 (Sep 7, 2018).
40
41#![no_std]
42#![cfg_attr(wasm_bindgen_unstable_test_coverage, feature(coverage_attribute))]
43#![cfg_attr(target_feature = "atomics", feature(thread_local))]
44#![cfg_attr(
45 any(target_feature = "atomics", wasm_bindgen_unstable_test_coverage),
46 feature(allow_internal_unstable),
47 allow(internal_features)
48)]
49#![cfg_attr(
50 all(not(debug_assertions), not(feature = "std"), target_arch = "wasm64"),
51 feature(simd_wasm64)
52)]
53#![doc(html_root_url = "https://docs.rs/wasm-bindgen/0.2")]
54
55extern crate alloc;
56#[cfg(feature = "std")]
57extern crate std;
58
59use crate::convert::{TryFromJsValue, UpcastFrom, VectorIntoWasmAbi};
60use crate::sys::Promising;
61use alloc::boxed::Box;
62use alloc::string::String;
63use alloc::vec::Vec;
64use core::convert::TryFrom;
65use core::marker::PhantomData;
66use core::ops::{
67 Add, BitAnd, BitOr, BitXor, Deref, DerefMut, Div, Mul, Neg, Not, Rem, Shl, Shr, Sub,
68};
69use core::ptr::NonNull;
70
71const _: () = {
72 /// Dummy empty function provided in order to detect linker-injected functions like `__wasm_call_ctors` and others that should be skipped by the wasm-bindgen interpreter.
73 ///
74 /// ## About `__wasm_call_ctors`
75 ///
76 /// There are several ways `__wasm_call_ctors` is introduced by the linker:
77 ///
78 /// * Using `#[link_section = ".init_array"]`;
79 /// * Linking with a C library that uses `__attribute__((constructor))`.
80 ///
81 /// The Wasm linker will insert a call to the `__wasm_call_ctors` function at the beginning of every
82 /// function that your module exports if it regards a module as having "command-style linkage".
83 /// Specifically, it regards a module as having "command-style linkage" if:
84 ///
85 /// * it is not relocatable;
86 /// * it is not a position-independent executable;
87 /// * and it does not call `__wasm_call_ctors`, directly or indirectly, from any
88 /// exported function.
89 #[no_mangle]
90 pub extern "C" fn __wbindgen_skip_interpret_calls() {}
91
92 /// A custom data section used to detect Emscripten.
93 #[cfg(target_os = "emscripten")]
94 #[link_section = "__wasm_bindgen_emscripten_marker"]
95 static __WASM_BINDGEN_EMSCRIPTEN_MARKER: [u8; 1] = [1];
96
97 /// A custom data section telling the CLI that the runtime was built with
98 /// `--cfg wasm_bindgen_unstable_jspi`, so JSPI on Emscripten goes through
99 /// its lifecycle hooks rather than wasm-bindgen's own stack management.
100 #[cfg(all(target_os = "emscripten", wasm_bindgen_unstable_jspi))]
101 #[link_section = "__wasm_bindgen_emscripten_jspi_marker"]
102 static __WASM_BINDGEN_EMSCRIPTEN_JSPI_MARKER: [u8; 1] = [1];
103};
104
105macro_rules! externs {
106 ($(#[$attr:meta])* extern "C" { $(fn $name:ident($($args:tt)*) -> $ret:ty;)* }) => (
107 #[cfg(all(target_family = "wasm", not(target_os = "wasi")))]
108 $(#[$attr])*
109 extern "C" {
110 $(fn $name($($args)*) -> $ret;)*
111 }
112
113 $(
114 #[cfg(not(all(target_family = "wasm", not(target_os = "wasi"))))]
115 #[allow(unused_variables)]
116 unsafe extern "C" fn $name($($args)*) -> $ret {
117 panic!("function not implemented on non-wasm32 targets")
118 }
119 )*
120 )
121}
122
123/// A module which is typically glob imported.
124///
125/// ```
126/// use wasm_bindgen::prelude::*;
127/// ```
128pub mod prelude {
129 pub use crate::closure::{Closure, ScopedClosure};
130 pub use crate::convert::Upcast; // provides upcast() and upcast_ref()
131 pub use crate::JsCast;
132 pub use crate::JsValue;
133 pub use crate::UnwrapThrowExt;
134 #[doc(hidden)]
135 pub use wasm_bindgen_macro::__wasm_bindgen_class_marker;
136 pub use wasm_bindgen_macro::wasm_bindgen;
137
138 pub use crate::JsError;
139}
140
141pub use wasm_bindgen_macro::link_to;
142
143pub mod closure;
144pub mod convert;
145pub mod describe;
146mod link;
147pub mod sys;
148
149#[cfg(wbg_reference_types)]
150mod externref;
151#[cfg(wbg_reference_types)]
152use externref::__wbindgen_externref_heap_live_count;
153
154pub use crate::__rt::marker::ErasableGeneric;
155pub use crate::convert::{IntoJsGeneric, JsGeneric, JsStringLike};
156
157#[doc(hidden)]
158pub mod handler;
159
160mod cast;
161pub use crate::cast::JsCast;
162
163mod parent;
164pub use crate::parent::Parent;
165
166mod cache;
167pub use cache::intern::{intern, unintern};
168
169#[doc(hidden)]
170#[path = "rt/mod.rs"]
171pub mod __rt;
172use __rt::wbg_cast;
173
174/// Representation of an object owned by JS.
175///
176/// A `JsValue` doesn't actually live in Rust right now but actually in a table
177/// owned by the `wasm-bindgen` generated JS glue code. Eventually the ownership
178/// will transfer into Wasm directly and this will likely become more efficient,
179/// but for now it may be slightly slow.
180pub struct JsValue {
181 idx: u32,
182 _marker: PhantomData<*mut u8>, // not at all threadsafe
183}
184
185#[cfg(not(target_feature = "atomics"))]
186unsafe impl Send for JsValue {}
187#[cfg(not(target_feature = "atomics"))]
188unsafe impl Sync for JsValue {}
189
190unsafe impl ErasableGeneric for JsValue {
191 type Repr = JsValue;
192}
193
194impl Promising for JsValue {
195 type Resolution = JsValue;
196}
197
198impl JsValue {
199 /// The `null` JS value constant.
200 pub const NULL: JsValue = JsValue::_new(__rt::JSIDX_NULL);
201
202 /// The `undefined` JS value constant.
203 pub const UNDEFINED: JsValue = JsValue::_new(__rt::JSIDX_UNDEFINED);
204
205 /// The `true` JS value constant.
206 pub const TRUE: JsValue = JsValue::_new(__rt::JSIDX_TRUE);
207
208 /// The `false` JS value constant.
209 pub const FALSE: JsValue = JsValue::_new(__rt::JSIDX_FALSE);
210
211 #[inline]
212 const fn _new(idx: u32) -> JsValue {
213 JsValue {
214 idx,
215 _marker: PhantomData,
216 }
217 }
218
219 /// Creates a new JS value which is a string.
220 ///
221 /// The utf-8 string provided is copied to the JS heap and the string will
222 /// be owned by the JS garbage collector.
223 #[allow(clippy::should_implement_trait)] // cannot fix without breaking change
224 #[inline]
225 pub fn from_str(s: &str) -> JsValue {
226 wbg_cast(s)
227 }
228
229 /// Creates a new JS value which is a number.
230 ///
231 /// This function creates a JS value representing a number (a heap
232 /// allocated number) and returns a handle to the JS version of it.
233 #[inline]
234 pub fn from_f64(n: f64) -> JsValue {
235 wbg_cast(n)
236 }
237
238 /// Creates a new JS value which is a bigint from a string representing a number.
239 ///
240 /// This function creates a JS value representing a bigint (a heap
241 /// allocated large integer) and returns a handle to the JS version of it.
242 #[inline]
243 pub fn bigint_from_str(s: &str) -> JsValue {
244 __wbindgen_bigint_from_str(s)
245 }
246
247 /// Creates a new JS value which is a boolean.
248 ///
249 /// This function creates a JS object representing a boolean (a heap
250 /// allocated boolean) and returns a handle to the JS version of it.
251 #[inline]
252 pub const fn from_bool(b: bool) -> JsValue {
253 if b {
254 JsValue::TRUE
255 } else {
256 JsValue::FALSE
257 }
258 }
259
260 /// Creates a new JS value representing `undefined`.
261 #[inline]
262 pub const fn undefined() -> JsValue {
263 JsValue::UNDEFINED
264 }
265
266 /// Creates a new JS value representing `null`.
267 #[inline]
268 pub const fn null() -> JsValue {
269 JsValue::NULL
270 }
271
272 /// Creates a new JS symbol with the optional description specified.
273 ///
274 /// This function will invoke the `Symbol` constructor in JS and return the
275 /// JS object corresponding to the symbol created.
276 pub fn symbol(description: Option<&str>) -> JsValue {
277 __wbindgen_symbol_new(description)
278 }
279
280 /// Creates a new `JsValue` from the JSON serialization of the object `t`
281 /// provided.
282 ///
283 /// **This function is deprecated**, due to [creating a dependency cycle in
284 /// some circumstances][dep-cycle-issue]. Use [`serde-wasm-bindgen`] or
285 /// [`gloo_utils::format::JsValueSerdeExt`] instead.
286 ///
287 /// [dep-cycle-issue]: https://github.com/wasm-bindgen/wasm-bindgen/issues/2770
288 /// [`serde-wasm-bindgen`]: https://docs.rs/serde-wasm-bindgen
289 /// [`gloo_utils::format::JsValueSerdeExt`]: https://docs.rs/gloo-utils/latest/gloo_utils/format/trait.JsValueSerdeExt.html
290 ///
291 /// This function will serialize the provided value `t` to a JSON string,
292 /// send the JSON string to JS, parse it into a JS object, and then return
293 /// a handle to the JS object. This is unlikely to be super speedy so it's
294 /// not recommended for large payloads, but it's a nice to have in some
295 /// situations!
296 ///
297 /// Usage of this API requires activating the `serde-serialize` feature of
298 /// the `wasm-bindgen` crate.
299 ///
300 /// # Errors
301 ///
302 /// Returns any error encountered when serializing `T` into JSON.
303 #[cfg(feature = "serde-serialize")]
304 #[deprecated = "causes dependency cycles, use `serde-wasm-bindgen` or `gloo_utils::format::JsValueSerdeExt` instead"]
305 pub fn from_serde<T>(t: &T) -> serde_json::Result<JsValue>
306 where
307 T: serde::ser::Serialize + ?Sized,
308 {
309 let s = serde_json::to_string(t)?;
310 Ok(__wbindgen_json_parse(s))
311 }
312
313 /// Invokes `JSON.stringify` on this value and then parses the resulting
314 /// JSON into an arbitrary Rust value.
315 ///
316 /// **This function is deprecated**, due to [creating a dependency cycle in
317 /// some circumstances][dep-cycle-issue]. Use [`serde-wasm-bindgen`] or
318 /// [`gloo_utils::format::JsValueSerdeExt`] instead.
319 ///
320 /// [dep-cycle-issue]: https://github.com/wasm-bindgen/wasm-bindgen/issues/2770
321 /// [`serde-wasm-bindgen`]: https://docs.rs/serde-wasm-bindgen
322 /// [`gloo_utils::format::JsValueSerdeExt`]: https://docs.rs/gloo-utils/latest/gloo_utils/format/trait.JsValueSerdeExt.html
323 ///
324 /// This function will first call `JSON.stringify` on the `JsValue` itself.
325 /// The resulting string is then passed into Rust which then parses it as
326 /// JSON into the resulting value.
327 ///
328 /// Usage of this API requires activating the `serde-serialize` feature of
329 /// the `wasm-bindgen` crate.
330 ///
331 /// # Errors
332 ///
333 /// Returns any error encountered when parsing the JSON into a `T`.
334 #[cfg(feature = "serde-serialize")]
335 #[deprecated = "causes dependency cycles, use `serde-wasm-bindgen` or `gloo_utils::format::JsValueSerdeExt` instead"]
336 pub fn into_serde<T>(&self) -> serde_json::Result<T>
337 where
338 T: for<'a> serde::de::Deserialize<'a>,
339 {
340 let s = __wbindgen_json_serialize(self);
341 // Turns out `JSON.stringify(undefined) === undefined`, so if
342 // we're passed `undefined` reinterpret it as `null` for JSON
343 // purposes.
344 serde_json::from_str(s.as_deref().unwrap_or("null"))
345 }
346
347 /// Returns the `f64` value of this JS value if it's an instance of a
348 /// number.
349 ///
350 /// If this JS value is not an instance of a number then this returns
351 /// `None`.
352 #[inline]
353 pub fn as_f64(&self) -> Option<f64> {
354 __wbindgen_number_get(self)
355 }
356
357 /// Tests whether this JS value is a JS string.
358 #[inline]
359 pub fn is_string(&self) -> bool {
360 __wbindgen_is_string(self)
361 }
362
363 /// If this JS value is a string value, this function copies the JS string
364 /// value into Wasm linear memory, encoded as UTF-8, and returns it as a
365 /// Rust `String`.
366 ///
367 /// To avoid the copying and re-encoding, consider the
368 /// `JsString::try_from()` function from [js-sys](https://docs.rs/js-sys)
369 /// instead.
370 ///
371 /// If this JS value is not an instance of a string or if it's not valid
372 /// utf-8 then this returns `None`.
373 ///
374 /// # UTF-16 vs UTF-8
375 ///
376 /// JavaScript strings in general are encoded as UTF-16, but Rust strings
377 /// are encoded as UTF-8. This can cause the Rust string to look a bit
378 /// different than the JS string sometimes. For more details see the
379 /// [documentation about the `str` type][caveats] which contains a few
380 /// caveats about the encodings.
381 ///
382 /// [caveats]: https://wasm-bindgen.github.io/wasm-bindgen/reference/types/str.html
383 #[inline]
384 pub fn as_string(&self) -> Option<String> {
385 __wbindgen_string_get(self)
386 }
387
388 /// Returns the `bool` value of this JS value if it's an instance of a
389 /// boolean.
390 ///
391 /// If this JS value is not an instance of a boolean then this returns
392 /// `None`.
393 #[inline]
394 pub fn as_bool(&self) -> Option<bool> {
395 __wbindgen_boolean_get(self)
396 }
397
398 /// Tests whether this JS value is `null`
399 #[inline]
400 pub fn is_null(&self) -> bool {
401 __wbindgen_is_null(self)
402 }
403
404 /// Tests whether this JS value is `undefined`
405 #[inline]
406 pub fn is_undefined(&self) -> bool {
407 __wbindgen_is_undefined(self)
408 }
409
410 /// Tests whether this JS value is `null` or `undefined`
411 #[inline]
412 pub fn is_null_or_undefined(&self) -> bool {
413 __wbindgen_is_null_or_undefined(self)
414 }
415
416 /// Tests whether the type of this JS value is `symbol`
417 #[inline]
418 pub fn is_symbol(&self) -> bool {
419 __wbindgen_is_symbol(self)
420 }
421
422 /// Tests whether `typeof self == "object" && self !== null`.
423 #[inline]
424 pub fn is_object(&self) -> bool {
425 __wbindgen_is_object(self)
426 }
427
428 /// Tests whether this JS value is an instance of Array.
429 #[inline]
430 pub fn is_array(&self) -> bool {
431 __wbindgen_is_array(self)
432 }
433
434 /// Tests whether the type of this JS value is `function`.
435 #[inline]
436 pub fn is_function(&self) -> bool {
437 __wbindgen_is_function(self)
438 }
439
440 /// Tests whether the type of this JS value is `bigint`.
441 #[inline]
442 pub fn is_bigint(&self) -> bool {
443 __wbindgen_is_bigint(self)
444 }
445
446 /// Applies the unary `typeof` JS operator on a `JsValue`.
447 ///
448 /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof)
449 #[inline]
450 pub fn js_typeof(&self) -> JsValue {
451 __wbindgen_typeof(self)
452 }
453
454 /// Applies the binary `in` JS operator on the two `JsValue`s.
455 ///
456 /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in)
457 #[inline]
458 pub fn js_in(&self, obj: &JsValue) -> bool {
459 __wbindgen_in(self, obj)
460 }
461
462 /// Tests whether the value is ["truthy"].
463 ///
464 /// ["truthy"]: https://developer.mozilla.org/en-US/docs/Glossary/Truthy
465 #[inline]
466 pub fn is_truthy(&self) -> bool {
467 !self.is_falsy()
468 }
469
470 /// Tests whether the value is ["falsy"].
471 ///
472 /// ["falsy"]: https://developer.mozilla.org/en-US/docs/Glossary/Falsy
473 #[inline]
474 pub fn is_falsy(&self) -> bool {
475 __wbindgen_is_falsy(self)
476 }
477
478 /// Get a string representation of the JavaScript object for debugging.
479 fn as_debug_string(&self) -> String {
480 __wbindgen_debug_string(self)
481 }
482
483 /// Compare two `JsValue`s for equality, using the `==` operator in JS.
484 ///
485 /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality)
486 #[inline]
487 pub fn loose_eq(&self, other: &Self) -> bool {
488 __wbindgen_jsval_loose_eq(self, other)
489 }
490
491 /// Applies the unary `~` JS operator on a `JsValue`.
492 ///
493 /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_NOT)
494 #[inline]
495 pub fn bit_not(&self) -> JsValue {
496 __wbindgen_bit_not(self)
497 }
498
499 /// Applies the binary `>>>` JS operator on the two `JsValue`s.
500 ///
501 /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unsigned_right_shift)
502 #[inline]
503 pub fn unsigned_shr(&self, rhs: &Self) -> u32 {
504 __wbindgen_unsigned_shr(self, rhs)
505 }
506
507 /// Applies the binary `/` JS operator on two `JsValue`s, catching and returning any `RangeError` thrown.
508 ///
509 /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Division)
510 #[inline]
511 pub fn checked_div(&self, rhs: &Self) -> Self {
512 __wbindgen_checked_div(self, rhs)
513 }
514
515 /// Applies the binary `**` JS operator on the two `JsValue`s.
516 ///
517 /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Exponentiation)
518 #[inline]
519 pub fn pow(&self, rhs: &Self) -> Self {
520 __wbindgen_pow(self, rhs)
521 }
522
523 /// Applies the binary `<` JS operator on the two `JsValue`s.
524 ///
525 /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Less_than)
526 #[inline]
527 pub fn lt(&self, other: &Self) -> bool {
528 __wbindgen_lt(self, other)
529 }
530
531 /// Applies the binary `<=` JS operator on the two `JsValue`s.
532 ///
533 /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Less_than_or_equal)
534 #[inline]
535 pub fn le(&self, other: &Self) -> bool {
536 __wbindgen_le(self, other)
537 }
538
539 /// Applies the binary `>=` JS operator on the two `JsValue`s.
540 ///
541 /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Greater_than_or_equal)
542 #[inline]
543 pub fn ge(&self, other: &Self) -> bool {
544 __wbindgen_ge(self, other)
545 }
546
547 /// Applies the binary `>` JS operator on the two `JsValue`s.
548 ///
549 /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Greater_than)
550 #[inline]
551 pub fn gt(&self, other: &Self) -> bool {
552 __wbindgen_gt(self, other)
553 }
554
555 /// Applies the unary `+` JS operator on a `JsValue`. Can throw.
556 ///
557 /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus)
558 #[inline]
559 pub fn unchecked_into_f64(&self) -> f64 {
560 // Can't use `wbg_cast` here because it expects that the value already has a correct type
561 // and will fail with an assertion error in debug mode.
562 __wbindgen_as_number(self)
563 }
564}
565
566impl PartialEq for JsValue {
567 /// Compares two `JsValue`s for equality, using the `===` operator in JS.
568 ///
569 /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality)
570 #[inline]
571 fn eq(&self, other: &Self) -> bool {
572 __wbindgen_jsval_eq(self, other)
573 }
574}
575
576impl PartialEq<bool> for JsValue {
577 #[inline]
578 fn eq(&self, other: &bool) -> bool {
579 self.as_bool() == Some(*other)
580 }
581}
582
583impl PartialEq<str> for JsValue {
584 #[inline]
585 fn eq(&self, other: &str) -> bool {
586 *self == JsValue::from_str(other)
587 }
588}
589
590impl<'a> PartialEq<&'a str> for JsValue {
591 #[inline]
592 fn eq(&self, other: &&'a str) -> bool {
593 <JsValue as PartialEq<str>>::eq(self, other)
594 }
595}
596
597impl PartialEq<String> for JsValue {
598 #[inline]
599 fn eq(&self, other: &String) -> bool {
600 <JsValue as PartialEq<str>>::eq(self, other)
601 }
602}
603impl<'a> PartialEq<&'a String> for JsValue {
604 #[inline]
605 fn eq(&self, other: &&'a String) -> bool {
606 <JsValue as PartialEq<str>>::eq(self, other)
607 }
608}
609
610macro_rules! forward_deref_unop {
611 (impl $imp:ident, $method:ident for $t:ty) => {
612 impl $imp for $t {
613 type Output = <&'static $t as $imp>::Output;
614
615 #[inline]
616 fn $method(self) -> <&'static $t as $imp>::Output {
617 $imp::$method(&self)
618 }
619 }
620 };
621}
622
623macro_rules! forward_deref_binop {
624 (impl $imp:ident, $method:ident for $t:ty) => {
625 impl<'a> $imp<$t> for &'a $t {
626 type Output = <&'static $t as $imp<&'static $t>>::Output;
627
628 #[inline]
629 fn $method(self, other: $t) -> <&'static $t as $imp<&'static $t>>::Output {
630 $imp::$method(self, &other)
631 }
632 }
633
634 impl $imp<&$t> for $t {
635 type Output = <&'static $t as $imp<&'static $t>>::Output;
636
637 #[inline]
638 fn $method(self, other: &$t) -> <&'static $t as $imp<&'static $t>>::Output {
639 $imp::$method(&self, other)
640 }
641 }
642
643 impl $imp<$t> for $t {
644 type Output = <&'static $t as $imp<&'static $t>>::Output;
645
646 #[inline]
647 fn $method(self, other: $t) -> <&'static $t as $imp<&'static $t>>::Output {
648 $imp::$method(&self, &other)
649 }
650 }
651 };
652}
653
654impl Not for &JsValue {
655 type Output = bool;
656
657 /// Applies the `!` JS operator on a `JsValue`.
658 ///
659 /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_NOT)
660 #[inline]
661 fn not(self) -> Self::Output {
662 JsValue::is_falsy(self)
663 }
664}
665
666forward_deref_unop!(impl Not, not for JsValue);
667
668impl TryFrom<JsValue> for f64 {
669 type Error = JsValue;
670
671 /// Applies the unary `+` JS operator on a `JsValue`.
672 /// Returns the numeric result on success, or the JS error value on error.
673 ///
674 /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus)
675 #[inline]
676 fn try_from(val: JsValue) -> Result<Self, Self::Error> {
677 f64::try_from(&val)
678 }
679}
680
681impl TryFrom<&JsValue> for f64 {
682 type Error = JsValue;
683
684 /// Applies the unary `+` JS operator on a `JsValue`.
685 /// Returns the numeric result on success, or the JS error value on error.
686 ///
687 /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus)
688 #[inline]
689 fn try_from(val: &JsValue) -> Result<Self, Self::Error> {
690 let jsval = __wbindgen_try_into_number(val);
691 match jsval.as_f64() {
692 Some(num) => Ok(num),
693 None => Err(jsval),
694 }
695 }
696}
697
698impl Neg for &JsValue {
699 type Output = JsValue;
700
701 /// Applies the unary `-` JS operator on a `JsValue`.
702 ///
703 /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_negation)
704 #[inline]
705 fn neg(self) -> Self::Output {
706 __wbindgen_neg(self)
707 }
708}
709
710forward_deref_unop!(impl Neg, neg for JsValue);
711
712impl BitAnd for &JsValue {
713 type Output = JsValue;
714
715 /// Applies the binary `&` JS operator on two `JsValue`s.
716 ///
717 /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_AND)
718 #[inline]
719 fn bitand(self, rhs: Self) -> Self::Output {
720 __wbindgen_bit_and(self, rhs)
721 }
722}
723
724forward_deref_binop!(impl BitAnd, bitand for JsValue);
725
726impl BitOr for &JsValue {
727 type Output = JsValue;
728
729 /// Applies the binary `|` JS operator on two `JsValue`s.
730 ///
731 /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_OR)
732 #[inline]
733 fn bitor(self, rhs: Self) -> Self::Output {
734 __wbindgen_bit_or(self, rhs)
735 }
736}
737
738forward_deref_binop!(impl BitOr, bitor for JsValue);
739
740impl BitXor for &JsValue {
741 type Output = JsValue;
742
743 /// Applies the binary `^` JS operator on two `JsValue`s.
744 ///
745 /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_XOR)
746 #[inline]
747 fn bitxor(self, rhs: Self) -> Self::Output {
748 __wbindgen_bit_xor(self, rhs)
749 }
750}
751
752forward_deref_binop!(impl BitXor, bitxor for JsValue);
753
754impl Shl for &JsValue {
755 type Output = JsValue;
756
757 /// Applies the binary `<<` JS operator on two `JsValue`s.
758 ///
759 /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Left_shift)
760 #[inline]
761 fn shl(self, rhs: Self) -> Self::Output {
762 __wbindgen_shl(self, rhs)
763 }
764}
765
766forward_deref_binop!(impl Shl, shl for JsValue);
767
768impl Shr for &JsValue {
769 type Output = JsValue;
770
771 /// Applies the binary `>>` JS operator on two `JsValue`s.
772 ///
773 /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Right_shift)
774 #[inline]
775 fn shr(self, rhs: Self) -> Self::Output {
776 __wbindgen_shr(self, rhs)
777 }
778}
779
780forward_deref_binop!(impl Shr, shr for JsValue);
781
782impl Add for &JsValue {
783 type Output = JsValue;
784
785 /// Applies the binary `+` JS operator on two `JsValue`s.
786 ///
787 /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Addition)
788 #[inline]
789 fn add(self, rhs: Self) -> Self::Output {
790 __wbindgen_add(self, rhs)
791 }
792}
793
794forward_deref_binop!(impl Add, add for JsValue);
795
796impl Sub for &JsValue {
797 type Output = JsValue;
798
799 /// Applies the binary `-` JS operator on two `JsValue`s.
800 ///
801 /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Subtraction)
802 #[inline]
803 fn sub(self, rhs: Self) -> Self::Output {
804 __wbindgen_sub(self, rhs)
805 }
806}
807
808forward_deref_binop!(impl Sub, sub for JsValue);
809
810impl Div for &JsValue {
811 type Output = JsValue;
812
813 /// Applies the binary `/` JS operator on two `JsValue`s.
814 ///
815 /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Division)
816 #[inline]
817 fn div(self, rhs: Self) -> Self::Output {
818 __wbindgen_div(self, rhs)
819 }
820}
821
822forward_deref_binop!(impl Div, div for JsValue);
823
824impl Mul for &JsValue {
825 type Output = JsValue;
826
827 /// Applies the binary `*` JS operator on two `JsValue`s.
828 ///
829 /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Multiplication)
830 #[inline]
831 fn mul(self, rhs: Self) -> Self::Output {
832 __wbindgen_mul(self, rhs)
833 }
834}
835
836forward_deref_binop!(impl Mul, mul for JsValue);
837
838impl Rem for &JsValue {
839 type Output = JsValue;
840
841 /// Applies the binary `%` JS operator on two `JsValue`s.
842 ///
843 /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder)
844 #[inline]
845 fn rem(self, rhs: Self) -> Self::Output {
846 __wbindgen_rem(self, rhs)
847 }
848}
849
850forward_deref_binop!(impl Rem, rem for JsValue);
851
852impl<'a> From<&'a str> for JsValue {
853 #[inline]
854 fn from(s: &'a str) -> JsValue {
855 JsValue::from_str(s)
856 }
857}
858
859impl<T> From<*mut T> for JsValue {
860 #[inline]
861 fn from(s: *mut T) -> JsValue {
862 JsValue::from(s as usize)
863 }
864}
865
866impl<T> From<*const T> for JsValue {
867 #[inline]
868 fn from(s: *const T) -> JsValue {
869 JsValue::from(s as usize)
870 }
871}
872
873impl<T> From<NonNull<T>> for JsValue {
874 #[inline]
875 fn from(s: NonNull<T>) -> JsValue {
876 JsValue::from(s.as_ptr() as usize)
877 }
878}
879
880impl<'a> From<&'a String> for JsValue {
881 #[inline]
882 fn from(s: &'a String) -> JsValue {
883 JsValue::from_str(s)
884 }
885}
886
887impl From<String> for JsValue {
888 #[inline]
889 fn from(s: String) -> JsValue {
890 JsValue::from_str(&s)
891 }
892}
893
894impl TryFrom<JsValue> for String {
895 type Error = JsValue;
896
897 fn try_from(value: JsValue) -> Result<Self, Self::Error> {
898 match value.as_string() {
899 Some(s) => Ok(s),
900 None => Err(value),
901 }
902 }
903}
904
905impl TryFromJsValue for String {
906 fn try_from_js_value_ref(value: &JsValue) -> Option<Self> {
907 value.as_string()
908 }
909}
910
911impl From<bool> for JsValue {
912 #[inline]
913 fn from(s: bool) -> JsValue {
914 JsValue::from_bool(s)
915 }
916}
917
918impl TryFromJsValue for bool {
919 fn try_from_js_value_ref(value: &JsValue) -> Option<Self> {
920 value.as_bool()
921 }
922}
923
924impl TryFromJsValue for char {
925 fn try_from_js_value_ref(value: &JsValue) -> Option<Self> {
926 let s = value.as_string()?;
927 if s.len() == 1 {
928 Some(s.chars().nth(0).unwrap())
929 } else {
930 None
931 }
932 }
933}
934
935impl<'a, T> From<&'a T> for JsValue
936where
937 T: JsCast,
938{
939 #[inline]
940 fn from(s: &'a T) -> JsValue {
941 s.as_ref().clone()
942 }
943}
944
945impl<T> From<Option<T>> for JsValue
946where
947 JsValue: From<T>,
948{
949 #[inline]
950 fn from(s: Option<T>) -> JsValue {
951 match s {
952 Some(s) => s.into(),
953 None => JsValue::undefined(),
954 }
955 }
956}
957
958// everything is a `JsValue`!
959impl JsCast for JsValue {
960 #[inline]
961 fn instanceof(_val: &JsValue) -> bool {
962 true
963 }
964 #[inline]
965 fn unchecked_from_js(val: JsValue) -> Self {
966 val
967 }
968 #[inline]
969 fn unchecked_from_js_ref(val: &JsValue) -> &Self {
970 val
971 }
972}
973
974impl AsRef<JsValue> for JsValue {
975 #[inline]
976 fn as_ref(&self) -> &JsValue {
977 self
978 }
979}
980
981impl UpcastFrom<JsValue> for JsValue {}
982
983// Loosely based on toInt32 in ecma-272 for abi semantics
984// with restriction that it only applies for numbers
985fn to_uint_32(v: &JsValue) -> Option<u32> {
986 v.as_f64().map(|n| {
987 if n.is_infinite() {
988 0
989 } else {
990 (n as i64) as u32
991 }
992 })
993}
994
995macro_rules! integers {
996 ($($n:ident)*) => ($(
997 impl PartialEq<$n> for JsValue {
998 #[inline]
999 fn eq(&self, other: &$n) -> bool {
1000 self.as_f64() == Some(f64::from(*other))
1001 }
1002 }
1003
1004 impl From<$n> for JsValue {
1005 #[inline]
1006 fn from(n: $n) -> JsValue {
1007 JsValue::from_f64(n.into())
1008 }
1009 }
1010
1011 // Follows semantics of https://www.w3.org/TR/wasm-js-api-2/#towebassemblyvalue
1012 impl TryFromJsValue for $n {
1013 #[inline]
1014 fn try_from_js_value_ref(val: &JsValue) -> Option<$n> {
1015 to_uint_32(val).map(|n| n as $n)
1016 }
1017 }
1018 )*)
1019}
1020
1021integers! { i8 u8 i16 u16 i32 u32 }
1022
1023macro_rules! floats {
1024 ($($n:ident)*) => ($(
1025 impl PartialEq<$n> for JsValue {
1026 #[inline]
1027 fn eq(&self, other: &$n) -> bool {
1028 self.as_f64() == Some(f64::from(*other))
1029 }
1030 }
1031
1032 impl From<$n> for JsValue {
1033 #[inline]
1034 fn from(n: $n) -> JsValue {
1035 JsValue::from_f64(n.into())
1036 }
1037 }
1038
1039 impl TryFromJsValue for $n {
1040 #[inline]
1041 fn try_from_js_value_ref(val: &JsValue) -> Option<$n> {
1042 val.as_f64().map(|n| n as $n)
1043 }
1044 }
1045 )*)
1046}
1047
1048floats! { f32 f64 }
1049
1050macro_rules! big_integers {
1051 ($($n:ident)*) => ($(
1052 impl PartialEq<$n> for JsValue {
1053 #[inline]
1054 fn eq(&self, other: &$n) -> bool {
1055 self == &JsValue::from(*other)
1056 }
1057 }
1058
1059 impl From<$n> for JsValue {
1060 #[inline]
1061 fn from(arg: $n) -> JsValue {
1062 wbg_cast(arg)
1063 }
1064 }
1065
1066 impl TryFrom<JsValue> for $n {
1067 type Error = JsValue;
1068
1069 #[inline]
1070 fn try_from(v: JsValue) -> Result<Self, JsValue> {
1071 Self::try_from_js_value(v)
1072 }
1073 }
1074
1075 impl TryFromJsValue for $n {
1076 #[inline]
1077 fn try_from_js_value_ref(val: &JsValue) -> Option<$n> {
1078 let as_i64 = __wbindgen_bigint_get_as_i64(&val)?;
1079 // Reinterpret bits; ABI-wise this is safe to do and allows us to avoid
1080 // having separate intrinsics per signed/unsigned types.
1081 let as_self = as_i64 as $n;
1082 // Double-check that we didn't truncate the bigint to 64 bits.
1083 if val == &as_self {
1084 Some(as_self)
1085 } else {
1086 None
1087 }
1088 }
1089 }
1090 )*)
1091}
1092
1093big_integers! { i64 u64 }
1094
1095macro_rules! num128 {
1096 ($ty:ty, $hi_ty:ty) => {
1097 impl PartialEq<$ty> for JsValue {
1098 #[inline]
1099 fn eq(&self, other: &$ty) -> bool {
1100 self == &JsValue::from(*other)
1101 }
1102 }
1103
1104 impl From<$ty> for JsValue {
1105 #[inline]
1106 fn from(arg: $ty) -> JsValue {
1107 wbg_cast(arg)
1108 }
1109 }
1110
1111 impl TryFrom<JsValue> for $ty {
1112 type Error = JsValue;
1113
1114 #[inline]
1115 fn try_from(v: JsValue) -> Result<Self, JsValue> {
1116 Self::try_from_js_value(v)
1117 }
1118 }
1119
1120 impl TryFromJsValue for $ty {
1121 // This is a non-standard Wasm bindgen conversion, supported equally
1122 fn try_from_js_value_ref(v: &JsValue) -> Option<$ty> {
1123 // Truncate the bigint to 64 bits, this will give us the lower part.
1124 // The lower part must be interpreted as unsigned in both i128 and u128.
1125 let lo = __wbindgen_bigint_get_as_i64(&v)? as u64;
1126 // Now we know it's a bigint, so we can safely use `>> 64n` without
1127 // worrying about a JS exception on type mismatch.
1128 let hi = v >> JsValue::from(64_u64);
1129 // The high part is the one we want checked against a 64-bit range.
1130 // If it fits, then our original number is in the 128-bit range.
1131 <$hi_ty>::try_from_js_value_ref(&hi).map(|hi| Self::from(hi) << 64 | Self::from(lo))
1132 }
1133 }
1134 };
1135}
1136
1137num128!(i128, i64);
1138
1139num128!(u128, u64);
1140
1141impl TryFromJsValue for () {
1142 fn try_from_js_value_ref(value: &JsValue) -> Option<Self> {
1143 if value.is_undefined() {
1144 Some(())
1145 } else {
1146 None
1147 }
1148 }
1149}
1150
1151impl<T: TryFromJsValue> TryFromJsValue for Option<T> {
1152 fn try_from_js_value_ref(value: &JsValue) -> Option<Self> {
1153 if value.is_undefined() {
1154 Some(None)
1155 } else {
1156 T::try_from_js_value_ref(value).map(Some)
1157 }
1158 }
1159}
1160
1161// Converts a JS `Array` whose elements all convert via `T::try_from_js_value`.
1162// Rejects non-array values and arrays containing any element that fails to
1163// convert. Mirrors the `Array`-shaped representation used by the static ABI
1164// path in `js_value_vector_from_abi`.
1165impl<T: TryFromJsValue> TryFromJsValue for Vec<T> {
1166 fn try_from_js_value_ref(value: &JsValue) -> Option<Self> {
1167 if !__wbindgen_is_array(value) {
1168 return None;
1169 }
1170 let len = __wbindgen_reflect_get(value, &JsValue::from_str("length")).as_f64()? as u32;
1171 let mut out = Vec::with_capacity(len as usize);
1172 for i in 0..len {
1173 let elem = __wbindgen_reflect_get(value, &JsValue::from_f64(i as f64));
1174 out.push(T::try_from_js_value(elem).ok()?);
1175 }
1176 Some(out)
1177 }
1178}
1179
1180// `usize` and `isize` use the public pointer-sized JS number ABI, which is
1181// `u32`/`i32` on wasm32 and `f64` on wasm64.
1182impl PartialEq<usize> for JsValue {
1183 #[inline]
1184 fn eq(&self, other: &usize) -> bool {
1185 *self == (*other as crate::__rt::WasmWordRepr)
1186 }
1187}
1188
1189impl From<usize> for JsValue {
1190 #[inline]
1191 fn from(n: usize) -> Self {
1192 Self::from(n as crate::__rt::WasmWordRepr)
1193 }
1194}
1195
1196impl PartialEq<isize> for JsValue {
1197 #[inline]
1198 fn eq(&self, other: &isize) -> bool {
1199 *self == (*other as crate::__rt::WasmSignedWordRepr)
1200 }
1201}
1202
1203impl From<isize> for JsValue {
1204 #[inline]
1205 fn from(n: isize) -> Self {
1206 Self::from(n as crate::__rt::WasmSignedWordRepr)
1207 }
1208}
1209
1210// Follows semantics of https://www.w3.org/TR/wasm-js-api-2/#towebassemblyvalue
1211impl TryFromJsValue for isize {
1212 #[inline]
1213 fn try_from_js_value_ref(val: &JsValue) -> Option<isize> {
1214 val.as_f64().map(|n| n as isize)
1215 }
1216}
1217
1218// Follows semantics of https://www.w3.org/TR/wasm-js-api-2/#towebassemblyvalue
1219impl TryFromJsValue for usize {
1220 #[inline]
1221 fn try_from_js_value_ref(val: &JsValue) -> Option<usize> {
1222 val.as_f64().map(|n| n as usize)
1223 }
1224}
1225
1226// Intrinsics that are simply JS function bindings and can be self-hosted via the macro.
1227#[wasm_bindgen_macro::wasm_bindgen(wasm_bindgen = crate)]
1228extern "C" {
1229 #[wasm_bindgen(js_namespace = Array, js_name = isArray)]
1230 fn __wbindgen_is_array(v: &JsValue) -> bool;
1231
1232 #[wasm_bindgen(js_namespace = Reflect, js_name = get)]
1233 fn __wbindgen_reflect_get(target: &JsValue, key: &JsValue) -> JsValue;
1234
1235 #[wasm_bindgen(js_name = BigInt)]
1236 fn __wbindgen_bigint_from_str(s: &str) -> JsValue;
1237
1238 #[wasm_bindgen(js_name = Symbol)]
1239 fn __wbindgen_symbol_new(description: Option<&str>) -> JsValue;
1240
1241 #[wasm_bindgen(js_name = Error)]
1242 fn __wbindgen_error_new(msg: &str) -> JsValue;
1243
1244 #[wasm_bindgen(js_namespace = JSON, js_name = parse)]
1245 fn __wbindgen_json_parse(json: String) -> JsValue;
1246
1247 #[wasm_bindgen(js_namespace = JSON, js_name = stringify)]
1248 fn __wbindgen_json_serialize(v: &JsValue) -> Option<String>;
1249
1250 #[wasm_bindgen(js_name = Number)]
1251 fn __wbindgen_as_number(v: &JsValue) -> f64;
1252}
1253
1254// Intrinsics which are handled by cli-support but for which we can use
1255// standard wasm-bindgen ABI conversions.
1256#[wasm_bindgen_macro::wasm_bindgen(wasm_bindgen = crate, raw_module = "__wbindgen_placeholder__")]
1257extern "C" {
1258 #[cfg(not(wbg_reference_types))]
1259 fn __wbindgen_externref_heap_live_count() -> u32;
1260
1261 fn __wbindgen_is_null(js: &JsValue) -> bool;
1262 fn __wbindgen_is_undefined(js: &JsValue) -> bool;
1263 fn __wbindgen_is_null_or_undefined(js: &JsValue) -> bool;
1264 fn __wbindgen_is_symbol(js: &JsValue) -> bool;
1265 fn __wbindgen_is_object(js: &JsValue) -> bool;
1266 fn __wbindgen_is_function(js: &JsValue) -> bool;
1267 fn __wbindgen_is_string(js: &JsValue) -> bool;
1268 fn __wbindgen_is_bigint(js: &JsValue) -> bool;
1269 fn __wbindgen_typeof(js: &JsValue) -> JsValue;
1270
1271 fn __wbindgen_in(prop: &JsValue, obj: &JsValue) -> bool;
1272
1273 fn __wbindgen_is_falsy(js: &JsValue) -> bool;
1274 fn __wbindgen_try_into_number(js: &JsValue) -> JsValue;
1275 fn __wbindgen_neg(js: &JsValue) -> JsValue;
1276 fn __wbindgen_bit_and(a: &JsValue, b: &JsValue) -> JsValue;
1277 fn __wbindgen_bit_or(a: &JsValue, b: &JsValue) -> JsValue;
1278 fn __wbindgen_bit_xor(a: &JsValue, b: &JsValue) -> JsValue;
1279 fn __wbindgen_bit_not(js: &JsValue) -> JsValue;
1280 fn __wbindgen_shl(a: &JsValue, b: &JsValue) -> JsValue;
1281 fn __wbindgen_shr(a: &JsValue, b: &JsValue) -> JsValue;
1282 fn __wbindgen_unsigned_shr(a: &JsValue, b: &JsValue) -> u32;
1283 fn __wbindgen_add(a: &JsValue, b: &JsValue) -> JsValue;
1284 fn __wbindgen_sub(a: &JsValue, b: &JsValue) -> JsValue;
1285 fn __wbindgen_div(a: &JsValue, b: &JsValue) -> JsValue;
1286 fn __wbindgen_checked_div(a: &JsValue, b: &JsValue) -> JsValue;
1287 fn __wbindgen_mul(a: &JsValue, b: &JsValue) -> JsValue;
1288 fn __wbindgen_rem(a: &JsValue, b: &JsValue) -> JsValue;
1289 fn __wbindgen_pow(a: &JsValue, b: &JsValue) -> JsValue;
1290 fn __wbindgen_lt(a: &JsValue, b: &JsValue) -> bool;
1291 fn __wbindgen_le(a: &JsValue, b: &JsValue) -> bool;
1292 fn __wbindgen_ge(a: &JsValue, b: &JsValue) -> bool;
1293 fn __wbindgen_gt(a: &JsValue, b: &JsValue) -> bool;
1294
1295 fn __wbindgen_number_get(js: &JsValue) -> Option<f64>;
1296 fn __wbindgen_boolean_get(js: &JsValue) -> Option<bool>;
1297 fn __wbindgen_string_get(js: &JsValue) -> Option<String>;
1298 fn __wbindgen_bigint_get_as_i64(js: &JsValue) -> Option<i64>;
1299
1300 fn __wbindgen_debug_string(js: &JsValue) -> String;
1301
1302 fn __wbindgen_throw(msg: &str) /* -> ! */;
1303 fn __wbindgen_rethrow(js: JsValue) /* -> ! */;
1304
1305 fn __wbindgen_jsval_eq(a: &JsValue, b: &JsValue) -> bool;
1306 fn __wbindgen_jsval_loose_eq(a: &JsValue, b: &JsValue) -> bool;
1307
1308 fn __wbindgen_copy_to_typed_array(data: &[u8], js: &JsValue);
1309
1310 fn __wbindgen_init_externref_table();
1311
1312 fn __wbindgen_exports() -> JsValue;
1313 fn __wbindgen_memory() -> JsValue;
1314 fn __wbindgen_module() -> JsValue;
1315 fn __wbindgen_instance() -> JsValue;
1316 fn __wbindgen_function_table() -> JsValue;
1317
1318 fn __wbindgen_reinit();
1319}
1320
1321// Intrinsics that have to use raw imports because they're matched by other
1322// parts of the transform codebase instead of just generating JS.
1323externs! {
1324 #[link(wasm_import_module = "__wbindgen_placeholder__")]
1325 extern "C" {
1326 fn __wbindgen_object_clone_ref(idx: u32) -> u32;
1327 fn __wbindgen_object_drop_ref(idx: u32) -> ();
1328
1329 fn __wbindgen_describe(v: u32) -> ();
1330 // Marker terminating a descriptor function, signaling to the CLI that
1331 // the parent function is a monomorphisation to be discovered,
1332 // interpreted, and rewritten to a manufactured JS binding. The
1333 // descriptor stream preceding this call carries a length-prefixed
1334 // `shim` key followed by the concrete `FUNCTION` signature for this
1335 // monomorphisation. A non-empty key identifies which generic-import AST
1336 // entry supplies the JS binding metadata; an empty key marks a `wbg_cast`
1337 // identity adapter (see `__rt::wbg_cast`).
1338 fn __wbindgen_describe_generic_import(func: *const (), prims: *const ()) -> *const ();
1339 }
1340}
1341
1342impl Clone for JsValue {
1343 #[inline]
1344 fn clone(&self) -> JsValue {
1345 JsValue::_new(unsafe { __wbindgen_object_clone_ref(self.idx) })
1346 }
1347}
1348
1349impl core::fmt::Debug for JsValue {
1350 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1351 write!(f, "JsValue({})", self.as_debug_string())
1352 }
1353}
1354
1355impl Drop for JsValue {
1356 #[inline]
1357 fn drop(&mut self) {
1358 unsafe {
1359 // We definitely should never drop anything in the stack area
1360 debug_assert!(
1361 self.idx >= __rt::JSIDX_OFFSET,
1362 "free of stack slot {}",
1363 self.idx
1364 );
1365
1366 // Otherwise if we're not dropping one of our reserved values,
1367 // actually call the intrinsic. See #1054 for eventually removing
1368 // this branch.
1369 if self.idx >= __rt::JSIDX_RESERVED {
1370 __wbindgen_object_drop_ref(self.idx);
1371 }
1372 }
1373 }
1374}
1375
1376impl Default for JsValue {
1377 fn default() -> Self {
1378 Self::UNDEFINED
1379 }
1380}
1381
1382/// Wrapper type for imported statics.
1383///
1384/// This type is used whenever a `static` is imported from a JS module, for
1385/// example this import:
1386///
1387/// ```ignore
1388/// #[wasm_bindgen]
1389/// extern "C" {
1390/// static console: JsValue;
1391/// }
1392/// ```
1393///
1394/// will generate in Rust a value that looks like:
1395///
1396/// ```ignore
1397/// static console: JsStatic<JsValue> = ...;
1398/// ```
1399///
1400/// This type implements `Deref` to the inner type so it's typically used as if
1401/// it were `&T`.
1402#[cfg(feature = "std")]
1403#[deprecated = "use with `#[wasm_bindgen(thread_local_v2)]` instead"]
1404pub struct JsStatic<T: 'static> {
1405 #[doc(hidden)]
1406 pub __inner: &'static std::thread::LocalKey<T>,
1407}
1408
1409#[cfg(feature = "std")]
1410#[allow(deprecated)]
1411#[cfg(not(target_feature = "atomics"))]
1412impl<T: crate::convert::FromWasmAbi + 'static> Deref for JsStatic<T> {
1413 type Target = T;
1414 fn deref(&self) -> &T {
1415 unsafe { self.__inner.with(|ptr| &*(ptr as *const T)) }
1416 }
1417}
1418
1419/// Wrapper type for imported statics.
1420///
1421/// This type is used whenever a `static` is imported from a JS module, for
1422/// example this import:
1423///
1424/// ```ignore
1425/// #[wasm_bindgen]
1426/// extern "C" {
1427/// #[wasm_bindgen(thread_local_v2)]
1428/// static console: JsValue;
1429/// }
1430/// ```
1431///
1432/// will generate in Rust a value that looks like:
1433///
1434/// ```ignore
1435/// static console: JsThreadLocal<JsValue> = ...;
1436/// ```
1437pub struct JsThreadLocal<T: 'static> {
1438 #[doc(hidden)]
1439 #[cfg(not(target_feature = "atomics"))]
1440 pub __inner: &'static __rt::LazyCell<T>,
1441 #[doc(hidden)]
1442 #[cfg(target_feature = "atomics")]
1443 pub __inner: fn() -> *const T,
1444}
1445
1446impl<T> JsThreadLocal<T> {
1447 pub fn with<F, R>(&'static self, f: F) -> R
1448 where
1449 F: FnOnce(&T) -> R,
1450 {
1451 #[cfg(not(target_feature = "atomics"))]
1452 return f(self.__inner);
1453 #[cfg(target_feature = "atomics")]
1454 f(unsafe { &*(self.__inner)() })
1455 }
1456}
1457
1458#[cold]
1459#[inline(never)]
1460#[deprecated(note = "renamed to `throw_str`")]
1461#[doc(hidden)]
1462pub fn throw(s: &str) -> ! {
1463 throw_str(s)
1464}
1465
1466/// Throws a JS exception.
1467///
1468/// This function will throw a JS exception with the message provided. The
1469/// function will not return as the Wasm stack will be popped when the exception
1470/// is thrown.
1471///
1472/// Note that it is very easy to leak memory with this function because this
1473/// function, unlike `panic!` on other platforms, **will not run destructors**.
1474/// It's recommended to return a `Result` where possible to avoid the worry of
1475/// leaks.
1476///
1477/// If you need destructors to run, consider using `panic!` when building with
1478/// `-Cpanic=unwind`. If the `std` feature is used panics will be caught at the
1479/// JavaScript boundary and converted to JavaScript exceptions.
1480#[cold]
1481#[inline(never)]
1482pub fn throw_str(s: &str) -> ! {
1483 __wbindgen_throw(s);
1484 unsafe { core::hint::unreachable_unchecked() }
1485}
1486
1487/// Rethrow a JS exception
1488///
1489/// This function will throw a JS exception with the JS value provided. This
1490/// function will not return and the Wasm stack will be popped until the point
1491/// of entry of Wasm itself.
1492///
1493/// Note that it is very easy to leak memory with this function because this
1494/// function, unlike `panic!` on other platforms, **will not run destructors**.
1495/// It's recommended to return a `Result` where possible to avoid the worry of
1496/// leaks.
1497///
1498/// If you need destructors to run, consider using `panic!` when building with
1499/// `-Cpanic=unwind`. If the `std` feature is used panics will be caught at the
1500/// JavaScript boundary and converted to JavaScript exceptions.
1501#[cold]
1502#[inline(never)]
1503pub fn throw_val(s: JsValue) -> ! {
1504 __wbindgen_rethrow(s);
1505 unsafe { core::hint::unreachable_unchecked() }
1506}
1507
1508/// Get the count of live `externref`s / `JsValue`s in `wasm-bindgen`'s heap.
1509///
1510/// ## Usage
1511///
1512/// This is intended for debugging and writing tests.
1513///
1514/// To write a test that asserts against unnecessarily keeping `anref`s /
1515/// `JsValue`s alive:
1516///
1517/// * get an initial live count,
1518///
1519/// * perform some series of operations or function calls that should clean up
1520/// after themselves, and should not keep holding onto `externref`s / `JsValue`s
1521/// after completion,
1522///
1523/// * get the final live count,
1524///
1525/// * and assert that the initial and final counts are the same.
1526///
1527/// ## What is Counted
1528///
1529/// Note that this only counts the *owned* `externref`s / `JsValue`s that end up in
1530/// `wasm-bindgen`'s heap. It does not count borrowed `externref`s / `JsValue`s
1531/// that are on its stack.
1532///
1533/// For example, these `JsValue`s are accounted for:
1534///
1535/// ```ignore
1536/// #[wasm_bindgen]
1537/// pub fn my_function(this_is_counted: JsValue) {
1538/// let also_counted = JsValue::from_str("hi");
1539/// assert!(wasm_bindgen::externref_heap_live_count() >= 2);
1540/// }
1541/// ```
1542///
1543/// While this borrowed `JsValue` ends up on the stack, not the heap, and
1544/// therefore is not accounted for:
1545///
1546/// ```ignore
1547/// #[wasm_bindgen]
1548/// pub fn my_other_function(this_is_not_counted: &JsValue) {
1549/// // ...
1550/// }
1551/// ```
1552pub fn externref_heap_live_count() -> u32 {
1553 __wbindgen_externref_heap_live_count()
1554}
1555
1556#[doc(hidden)]
1557pub fn anyref_heap_live_count() -> u32 {
1558 externref_heap_live_count()
1559}
1560
1561/// An extension trait for `Option<T>` and `Result<T, E>` for unwrapping the `T`
1562/// value, or throwing a JS error if it is not available.
1563///
1564/// These methods should have a smaller code size footprint than the normal
1565/// `Option::unwrap` and `Option::expect` methods, but they are specific to
1566/// working with Wasm and JS.
1567///
1568/// On non-wasm32 targets, defaults to the normal unwrap/expect calls.
1569///
1570/// # Example
1571///
1572/// ```
1573/// use wasm_bindgen::prelude::*;
1574///
1575/// // If the value is `Option::Some` or `Result::Ok`, then we just get the
1576/// // contained `T` value.
1577/// let x = Some(42);
1578/// assert_eq!(x.unwrap_throw(), 42);
1579///
1580/// let y: Option<i32> = None;
1581///
1582/// // This call would throw an error to JS!
1583/// //
1584/// // y.unwrap_throw()
1585/// //
1586/// // And this call would throw an error to JS with a custom error message!
1587/// //
1588/// // y.expect_throw("woopsie daisy!")
1589/// ```
1590pub trait UnwrapThrowExt<T>: Sized {
1591 /// Unwrap this `Option` or `Result`, but instead of panicking on failure,
1592 /// throw an exception to JavaScript.
1593 #[cfg_attr(
1594 any(
1595 debug_assertions,
1596 not(all(target_family = "wasm", not(target_os = "wasi")))
1597 ),
1598 track_caller
1599 )]
1600 fn unwrap_throw(self) -> T {
1601 if cfg!(all(
1602 debug_assertions,
1603 all(target_family = "wasm", not(target_os = "wasi"))
1604 )) {
1605 let loc = core::panic::Location::caller();
1606 let msg = alloc::format!(
1607 "called `{}::unwrap_throw()` ({}:{}:{})",
1608 core::any::type_name::<Self>(),
1609 loc.file(),
1610 loc.line(),
1611 loc.column()
1612 );
1613 self.expect_throw(&msg)
1614 } else {
1615 self.expect_throw("called `unwrap_throw()`")
1616 }
1617 }
1618
1619 /// Unwrap this container's `T` value, or throw an error to JS with the
1620 /// given message if the `T` value is unavailable (e.g. an `Option<T>` is
1621 /// `None`).
1622 #[cfg_attr(
1623 any(
1624 debug_assertions,
1625 not(all(target_family = "wasm", not(target_os = "wasi")))
1626 ),
1627 track_caller
1628 )]
1629 fn expect_throw(self, message: &str) -> T;
1630}
1631
1632impl<T> UnwrapThrowExt<T> for Option<T> {
1633 fn unwrap_throw(self) -> T {
1634 const MSG: &str = "called `Option::unwrap_throw()` on a `None` value";
1635
1636 if cfg!(all(target_family = "wasm", not(target_os = "wasi"))) {
1637 if let Some(val) = self {
1638 val
1639 } else if cfg!(debug_assertions) {
1640 let loc = core::panic::Location::caller();
1641 let msg = alloc::format!("{MSG} ({}:{}:{})", loc.file(), loc.line(), loc.column(),);
1642
1643 throw_str(&msg)
1644 } else {
1645 throw_str(MSG)
1646 }
1647 } else {
1648 self.expect(MSG)
1649 }
1650 }
1651
1652 fn expect_throw(self, message: &str) -> T {
1653 if cfg!(all(target_family = "wasm", not(target_os = "wasi"))) {
1654 if let Some(val) = self {
1655 val
1656 } else if cfg!(debug_assertions) {
1657 let loc = core::panic::Location::caller();
1658 let msg =
1659 alloc::format!("{message} ({}:{}:{})", loc.file(), loc.line(), loc.column(),);
1660
1661 throw_str(&msg)
1662 } else {
1663 throw_str(message)
1664 }
1665 } else {
1666 self.expect(message)
1667 }
1668 }
1669}
1670
1671impl<T, E> UnwrapThrowExt<T> for Result<T, E>
1672where
1673 E: core::fmt::Debug,
1674{
1675 fn unwrap_throw(self) -> T {
1676 const MSG: &str = "called `Result::unwrap_throw()` on an `Err` value";
1677
1678 if cfg!(all(target_family = "wasm", not(target_os = "wasi"))) {
1679 match self {
1680 Ok(val) => val,
1681 Err(err) => {
1682 if cfg!(debug_assertions) {
1683 let loc = core::panic::Location::caller();
1684 let msg = alloc::format!(
1685 "{MSG} ({}:{}:{}): {err:?}",
1686 loc.file(),
1687 loc.line(),
1688 loc.column(),
1689 );
1690
1691 throw_str(&msg)
1692 } else {
1693 throw_str(MSG)
1694 }
1695 }
1696 }
1697 } else {
1698 self.expect(MSG)
1699 }
1700 }
1701
1702 fn expect_throw(self, message: &str) -> T {
1703 if cfg!(all(target_family = "wasm", not(target_os = "wasi"))) {
1704 match self {
1705 Ok(val) => val,
1706 Err(err) => {
1707 if cfg!(debug_assertions) {
1708 let loc = core::panic::Location::caller();
1709 let msg = alloc::format!(
1710 "{message} ({}:{}:{}): {err:?}",
1711 loc.file(),
1712 loc.line(),
1713 loc.column(),
1714 );
1715
1716 throw_str(&msg)
1717 } else {
1718 throw_str(message)
1719 }
1720 }
1721 }
1722 } else {
1723 self.expect(message)
1724 }
1725 }
1726}
1727
1728/// Returns a handle to this Wasm instance's `WebAssembly.Module`.
1729/// This is only available when the final Wasm app is built with
1730/// `--target no-modules`, `--target web`, `--target deno` or `--target nodejs`.
1731/// It is unavailable for `--target bundler`.
1732pub fn module() -> JsValue {
1733 __wbindgen_module()
1734}
1735
1736/// Returns a handle to this Wasm instance's `WebAssembly.Instance`.
1737/// This is only available when the final Wasm app is built with
1738/// `--target no-modules`, `--target web`, `--target deno` or `--target nodejs`.
1739/// It is unavailable for `--target bundler`.
1740pub fn instance() -> JsValue {
1741 __wbindgen_instance()
1742}
1743
1744// TODO: deprecate next major
1745/// Returns a handle to this Wasm instance's `WebAssembly.Instance.prototype.exports`
1746pub fn exports() -> JsValue {
1747 __wbindgen_exports()
1748}
1749
1750/// Returns a handle to this Wasm instance's `WebAssembly.Memory`
1751pub fn memory() -> JsValue {
1752 __wbindgen_memory()
1753}
1754
1755/// Returns a handle to this Wasm instance's `WebAssembly.Table` which is the
1756/// indirect function table used by Rust
1757pub fn function_table() -> JsValue {
1758 __wbindgen_function_table()
1759}
1760
1761/// A wrapper type around slices and vectors for binding the `Uint8ClampedArray`
1762/// array in JS.
1763///
1764/// If you need to invoke a JS API which must take `Uint8ClampedArray` array,
1765/// then you can define it as taking one of these types:
1766///
1767/// * `Clamped<&[u8]>`
1768/// * `Clamped<&mut [u8]>`
1769/// * `Clamped<Vec<u8>>`
1770///
1771/// All of these types will show up as `Uint8ClampedArray` in JS and will have
1772/// different forms of ownership in Rust.
1773#[derive(Copy, Clone, PartialEq, Debug, Eq)]
1774pub struct Clamped<T>(pub T);
1775
1776impl<T> Deref for Clamped<T> {
1777 type Target = T;
1778
1779 fn deref(&self) -> &T {
1780 &self.0
1781 }
1782}
1783
1784impl<T> DerefMut for Clamped<T> {
1785 fn deref_mut(&mut self) -> &mut T {
1786 &mut self.0
1787 }
1788}
1789
1790/// Convenience type for use on exported `fn() -> Result<T, JsError>` functions, where you wish to
1791/// throw a JavaScript `Error` object.
1792///
1793/// You can get wasm_bindgen to throw basic errors by simply returning
1794/// `Err(JsError::new("message"))` from such a function.
1795///
1796/// For more complex error handling, `JsError` implements `From<T> where T: std::error::Error` by
1797/// converting it to a string, so you can use it with `?`. Many Rust error types already do this,
1798/// and you can use [`thiserror`](https://crates.io/crates/thiserror) to derive Display
1799/// implementations easily or use any number of boxed error types that implement it already.
1800///
1801///
1802/// To allow JavaScript code to catch only your errors, you may wish to add a subclass of `Error`
1803/// in a JS module, and then implement `Into<JsValue>` directly on a type and instantiate that
1804/// subclass. In that case, you would not need `JsError` at all.
1805///
1806/// ### Basic example
1807///
1808/// ```rust,no_run
1809/// use wasm_bindgen::prelude::*;
1810///
1811/// #[wasm_bindgen]
1812/// pub fn throwing_function() -> Result<(), JsError> {
1813/// Err(JsError::new("message"))
1814/// }
1815/// ```
1816///
1817/// ### Complex Example
1818///
1819/// ```rust,no_run
1820/// use wasm_bindgen::prelude::*;
1821///
1822/// #[derive(Debug, Clone)]
1823/// enum MyErrorType {
1824/// SomeError,
1825/// }
1826///
1827/// use core::fmt;
1828/// impl std::error::Error for MyErrorType {}
1829/// impl fmt::Display for MyErrorType {
1830/// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1831/// write!(f, "display implementation becomes the error message")
1832/// }
1833/// }
1834///
1835/// fn internal_api() -> Result<(), MyErrorType> {
1836/// Err(MyErrorType::SomeError)
1837/// }
1838///
1839/// #[wasm_bindgen]
1840/// pub fn throwing_function() -> Result<(), JsError> {
1841/// internal_api()?;
1842/// Ok(())
1843/// }
1844///
1845/// ```
1846#[derive(Clone, Debug)]
1847#[repr(transparent)]
1848pub struct JsError {
1849 value: JsValue,
1850}
1851
1852impl JsError {
1853 /// Construct a JavaScript `Error` object with a string message
1854 #[inline]
1855 pub fn new(s: &str) -> JsError {
1856 Self {
1857 value: __wbindgen_error_new(s),
1858 }
1859 }
1860}
1861
1862impl<E> From<E> for JsError
1863where
1864 E: core::error::Error,
1865{
1866 fn from(error: E) -> Self {
1867 use alloc::string::ToString;
1868
1869 JsError::new(&error.to_string())
1870 }
1871}
1872
1873impl From<JsError> for JsValue {
1874 fn from(error: JsError) -> Self {
1875 error.value
1876 }
1877}
1878
1879impl<T: VectorIntoWasmAbi> From<Box<[T]>> for JsValue {
1880 fn from(vector: Box<[T]>) -> Self {
1881 wbg_cast(vector)
1882 }
1883}
1884
1885impl<T: VectorIntoWasmAbi> From<Clamped<Box<[T]>>> for JsValue {
1886 fn from(vector: Clamped<Box<[T]>>) -> Self {
1887 wbg_cast(vector)
1888 }
1889}
1890
1891impl<T: VectorIntoWasmAbi> From<Vec<T>> for JsValue {
1892 fn from(vector: Vec<T>) -> Self {
1893 JsValue::from(vector.into_boxed_slice())
1894 }
1895}
1896
1897impl<T: VectorIntoWasmAbi> From<Clamped<Vec<T>>> for JsValue {
1898 fn from(vector: Clamped<Vec<T>>) -> Self {
1899 JsValue::from(Clamped(vector.0.into_boxed_slice()))
1900 }
1901}