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#![no_std]
9#![cfg_attr(wasm_bindgen_unstable_test_coverage, feature(coverage_attribute))]
10#![allow(coherence_leak_check)]
11#![doc(html_root_url = "https://docs.rs/wasm-bindgen/0.2")]
12
13extern crate alloc;
14
15use alloc::boxed::Box;
16use alloc::string::String;
17use alloc::vec::Vec;
18use core::convert::TryFrom;
19use core::marker;
20use core::mem;
21use core::ops::{
22    Add, BitAnd, BitOr, BitXor, Deref, DerefMut, Div, Mul, Neg, Not, Rem, Shl, Shr, Sub,
23};
24use core::ptr::NonNull;
25
26use crate::convert::{FromWasmAbi, TryFromJsValue, WasmRet, WasmSlice};
27
28macro_rules! if_std {
29    ($($i:item)*) => ($(
30        #[cfg(feature = "std")] $i
31    )*)
32}
33
34macro_rules! externs {
35    ($(#[$attr:meta])* extern "C" { $(fn $name:ident($($args:tt)*) -> $ret:ty;)* }) => (
36        #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
37        $(#[$attr])*
38        extern "C" {
39            $(fn $name($($args)*) -> $ret;)*
40        }
41
42        $(
43            #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
44            #[allow(unused_variables)]
45            unsafe extern fn $name($($args)*) -> $ret {
46                panic!("function not implemented on non-wasm32 targets")
47            }
48        )*
49    )
50}
51
52/// A module which is typically glob imported.
53///
54/// ```
55/// use wasm_bindgen::prelude::*;
56/// ```
57pub mod prelude {
58    pub use crate::closure::Closure;
59    pub use crate::JsCast;
60    pub use crate::JsValue;
61    pub use crate::UnwrapThrowExt;
62    #[doc(hidden)]
63    pub use wasm_bindgen_macro::__wasm_bindgen_class_marker;
64    pub use wasm_bindgen_macro::wasm_bindgen;
65
66    pub use crate::JsError;
67}
68
69pub use wasm_bindgen_macro::link_to;
70
71pub mod closure;
72pub mod convert;
73pub mod describe;
74mod link;
75
76mod cast;
77pub use crate::cast::{JsCast, JsObject};
78
79if_std! {
80    extern crate std;
81    use std::prelude::v1::*;
82    mod externref;
83    mod cache;
84    pub use cache::intern::{intern, unintern};
85}
86
87/// Representation of an object owned by JS.
88///
89/// A `JsValue` doesn't actually live in Rust right now but actually in a table
90/// owned by the `wasm-bindgen` generated JS glue code. Eventually the ownership
91/// will transfer into wasm directly and this will likely become more efficient,
92/// but for now it may be slightly slow.
93pub struct JsValue {
94    idx: u32,
95    _marker: marker::PhantomData<*mut u8>, // not at all threadsafe
96}
97
98const JSIDX_OFFSET: u32 = 128; // keep in sync with js/mod.rs
99const JSIDX_UNDEFINED: u32 = JSIDX_OFFSET;
100const JSIDX_NULL: u32 = JSIDX_OFFSET + 1;
101const JSIDX_TRUE: u32 = JSIDX_OFFSET + 2;
102const JSIDX_FALSE: u32 = JSIDX_OFFSET + 3;
103const JSIDX_RESERVED: u32 = JSIDX_OFFSET + 4;
104
105impl JsValue {
106    /// The `null` JS value constant.
107    pub const NULL: JsValue = JsValue::_new(JSIDX_NULL);
108
109    /// The `undefined` JS value constant.
110    pub const UNDEFINED: JsValue = JsValue::_new(JSIDX_UNDEFINED);
111
112    /// The `true` JS value constant.
113    pub const TRUE: JsValue = JsValue::_new(JSIDX_TRUE);
114
115    /// The `false` JS value constant.
116    pub const FALSE: JsValue = JsValue::_new(JSIDX_FALSE);
117
118    #[inline]
119    const fn _new(idx: u32) -> JsValue {
120        JsValue {
121            idx,
122            _marker: marker::PhantomData,
123        }
124    }
125
126    /// Creates a new JS value which is a string.
127    ///
128    /// The utf-8 string provided is copied to the JS heap and the string will
129    /// be owned by the JS garbage collector.
130    #[allow(clippy::should_implement_trait)] // cannot fix without breaking change
131    #[inline]
132    pub fn from_str(s: &str) -> JsValue {
133        unsafe { JsValue::_new(__wbindgen_string_new(s.as_ptr(), s.len())) }
134    }
135
136    /// Creates a new JS value which is a number.
137    ///
138    /// This function creates a JS value representing a number (a heap
139    /// allocated number) and returns a handle to the JS version of it.
140    #[inline]
141    pub fn from_f64(n: f64) -> JsValue {
142        unsafe { JsValue::_new(__wbindgen_number_new(n)) }
143    }
144
145    /// Creates a new JS value which is a bigint from a string representing a number.
146    ///
147    /// This function creates a JS value representing a bigint (a heap
148    /// allocated large integer) and returns a handle to the JS version of it.
149    #[inline]
150    pub fn bigint_from_str(s: &str) -> JsValue {
151        unsafe { JsValue::_new(__wbindgen_bigint_from_str(s.as_ptr(), s.len())) }
152    }
153
154    /// Creates a new JS value which is a boolean.
155    ///
156    /// This function creates a JS object representing a boolean (a heap
157    /// allocated boolean) and returns a handle to the JS version of it.
158    #[inline]
159    pub const fn from_bool(b: bool) -> JsValue {
160        if b {
161            JsValue::TRUE
162        } else {
163            JsValue::FALSE
164        }
165    }
166
167    /// Creates a new JS value representing `undefined`.
168    #[inline]
169    pub const fn undefined() -> JsValue {
170        JsValue::UNDEFINED
171    }
172
173    /// Creates a new JS value representing `null`.
174    #[inline]
175    pub const fn null() -> JsValue {
176        JsValue::NULL
177    }
178
179    /// Creates a new JS symbol with the optional description specified.
180    ///
181    /// This function will invoke the `Symbol` constructor in JS and return the
182    /// JS object corresponding to the symbol created.
183    pub fn symbol(description: Option<&str>) -> JsValue {
184        unsafe {
185            match description {
186                Some(description) => JsValue::_new(__wbindgen_symbol_named_new(
187                    description.as_ptr(),
188                    description.len(),
189                )),
190                None => JsValue::_new(__wbindgen_symbol_anonymous_new()),
191            }
192        }
193    }
194
195    /// Creates a new `JsValue` from the JSON serialization of the object `t`
196    /// provided.
197    ///
198    /// **This function is deprecated**, due to [creating a dependency cycle in
199    /// some circumstances][dep-cycle-issue]. Use [`serde-wasm-bindgen`] or
200    /// [`gloo_utils::format::JsValueSerdeExt`] instead.
201    ///
202    /// [dep-cycle-issue]: https://github.com/rustwasm/wasm-bindgen/issues/2770
203    /// [`serde-wasm-bindgen`]: https://docs.rs/serde-wasm-bindgen
204    /// [`gloo_utils::format::JsValueSerdeExt`]: https://docs.rs/gloo-utils/latest/gloo_utils/format/trait.JsValueSerdeExt.html
205    ///
206    /// This function will serialize the provided value `t` to a JSON string,
207    /// send the JSON string to JS, parse it into a JS object, and then return
208    /// a handle to the JS object. This is unlikely to be super speedy so it's
209    /// not recommended for large payloads, but it's a nice to have in some
210    /// situations!
211    ///
212    /// Usage of this API requires activating the `serde-serialize` feature of
213    /// the `wasm-bindgen` crate.
214    ///
215    /// # Errors
216    ///
217    /// Returns any error encountered when serializing `T` into JSON.
218    #[cfg(feature = "serde-serialize")]
219    #[deprecated = "causes dependency cycles, use `serde-wasm-bindgen` or `gloo_utils::format::JsValueSerdeExt` instead"]
220    pub fn from_serde<T>(t: &T) -> serde_json::Result<JsValue>
221    where
222        T: serde::ser::Serialize + ?Sized,
223    {
224        let s = serde_json::to_string(t)?;
225        unsafe { Ok(JsValue::_new(__wbindgen_json_parse(s.as_ptr(), s.len()))) }
226    }
227
228    /// Invokes `JSON.stringify` on this value and then parses the resulting
229    /// JSON into an arbitrary Rust value.
230    ///
231    /// **This function is deprecated**, due to [creating a dependency cycle in
232    /// some circumstances][dep-cycle-issue]. Use [`serde-wasm-bindgen`] or
233    /// [`gloo_utils::format::JsValueSerdeExt`] instead.
234    ///
235    /// [dep-cycle-issue]: https://github.com/rustwasm/wasm-bindgen/issues/2770
236    /// [`serde-wasm-bindgen`]: https://docs.rs/serde-wasm-bindgen
237    /// [`gloo_utils::format::JsValueSerdeExt`]: https://docs.rs/gloo-utils/latest/gloo_utils/format/trait.JsValueSerdeExt.html
238    ///
239    /// This function will first call `JSON.stringify` on the `JsValue` itself.
240    /// The resulting string is then passed into Rust which then parses it as
241    /// JSON into the resulting value.
242    ///
243    /// Usage of this API requires activating the `serde-serialize` feature of
244    /// the `wasm-bindgen` crate.
245    ///
246    /// # Errors
247    ///
248    /// Returns any error encountered when parsing the JSON into a `T`.
249    #[cfg(feature = "serde-serialize")]
250    #[deprecated = "causes dependency cycles, use `serde-wasm-bindgen` or `gloo_utils::format::JsValueSerdeExt` instead"]
251    pub fn into_serde<T>(&self) -> serde_json::Result<T>
252    where
253        T: for<'a> serde::de::Deserialize<'a>,
254    {
255        unsafe {
256            let ret = __wbindgen_json_serialize(self.idx);
257            let s = String::from_abi(ret);
258            serde_json::from_str(&s)
259        }
260    }
261
262    /// Returns the `f64` value of this JS value if it's an instance of a
263    /// number.
264    ///
265    /// If this JS value is not an instance of a number then this returns
266    /// `None`.
267    #[inline]
268    pub fn as_f64(&self) -> Option<f64> {
269        unsafe { __wbindgen_number_get(self.idx).join() }
270    }
271
272    /// Tests whether this JS value is a JS string.
273    #[inline]
274    pub fn is_string(&self) -> bool {
275        unsafe { __wbindgen_is_string(self.idx) == 1 }
276    }
277
278    /// If this JS value is a string value, this function copies the JS string
279    /// value into wasm linear memory, encoded as UTF-8, and returns it as a
280    /// Rust `String`.
281    ///
282    /// To avoid the copying and re-encoding, consider the
283    /// `JsString::try_from()` function from [js-sys](https://docs.rs/js-sys)
284    /// instead.
285    ///
286    /// If this JS value is not an instance of a string or if it's not valid
287    /// utf-8 then this returns `None`.
288    ///
289    /// # UTF-16 vs UTF-8
290    ///
291    /// JavaScript strings in general are encoded as UTF-16, but Rust strings
292    /// are encoded as UTF-8. This can cause the Rust string to look a bit
293    /// different than the JS string sometimes. For more details see the
294    /// [documentation about the `str` type][caveats] which contains a few
295    /// caveats about the encodings.
296    ///
297    /// [caveats]: https://rustwasm.github.io/docs/wasm-bindgen/reference/types/str.html
298    #[inline]
299    pub fn as_string(&self) -> Option<String> {
300        unsafe { FromWasmAbi::from_abi(__wbindgen_string_get(self.idx)) }
301    }
302
303    /// Returns the `bool` value of this JS value if it's an instance of a
304    /// boolean.
305    ///
306    /// If this JS value is not an instance of a boolean then this returns
307    /// `None`.
308    #[inline]
309    pub fn as_bool(&self) -> Option<bool> {
310        unsafe {
311            match __wbindgen_boolean_get(self.idx) {
312                0 => Some(false),
313                1 => Some(true),
314                _ => None,
315            }
316        }
317    }
318
319    /// Tests whether this JS value is `null`
320    #[inline]
321    pub fn is_null(&self) -> bool {
322        unsafe { __wbindgen_is_null(self.idx) == 1 }
323    }
324
325    /// Tests whether this JS value is `undefined`
326    #[inline]
327    pub fn is_undefined(&self) -> bool {
328        unsafe { __wbindgen_is_undefined(self.idx) == 1 }
329    }
330
331    /// Tests whether the type of this JS value is `symbol`
332    #[inline]
333    pub fn is_symbol(&self) -> bool {
334        unsafe { __wbindgen_is_symbol(self.idx) == 1 }
335    }
336
337    /// Tests whether `typeof self == "object" && self !== null`.
338    #[inline]
339    pub fn is_object(&self) -> bool {
340        unsafe { __wbindgen_is_object(self.idx) == 1 }
341    }
342
343    /// Tests whether this JS value is an instance of Array.
344    #[inline]
345    pub fn is_array(&self) -> bool {
346        unsafe { __wbindgen_is_array(self.idx) == 1 }
347    }
348
349    /// Tests whether the type of this JS value is `function`.
350    #[inline]
351    pub fn is_function(&self) -> bool {
352        unsafe { __wbindgen_is_function(self.idx) == 1 }
353    }
354
355    /// Tests whether the type of this JS value is `bigint`.
356    #[inline]
357    pub fn is_bigint(&self) -> bool {
358        unsafe { __wbindgen_is_bigint(self.idx) == 1 }
359    }
360
361    /// Applies the unary `typeof` JS operator on a `JsValue`.
362    ///
363    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof)
364    #[inline]
365    pub fn js_typeof(&self) -> JsValue {
366        unsafe { JsValue::_new(__wbindgen_typeof(self.idx)) }
367    }
368
369    /// Applies the binary `in` JS operator on the two `JsValue`s.
370    ///
371    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in)
372    #[inline]
373    pub fn js_in(&self, obj: &JsValue) -> bool {
374        unsafe { __wbindgen_in(self.idx, obj.idx) == 1 }
375    }
376
377    /// Tests whether the value is ["truthy"].
378    ///
379    /// ["truthy"]: https://developer.mozilla.org/en-US/docs/Glossary/Truthy
380    #[inline]
381    pub fn is_truthy(&self) -> bool {
382        !self.is_falsy()
383    }
384
385    /// Tests whether the value is ["falsy"].
386    ///
387    /// ["falsy"]: https://developer.mozilla.org/en-US/docs/Glossary/Falsy
388    #[inline]
389    pub fn is_falsy(&self) -> bool {
390        unsafe { __wbindgen_is_falsy(self.idx) == 1 }
391    }
392
393    /// Get a string representation of the JavaScript object for debugging.
394    #[cfg(feature = "std")]
395    fn as_debug_string(&self) -> String {
396        unsafe {
397            let mut ret = [0; 2];
398            __wbindgen_debug_string(&mut ret, self.idx);
399            let data = Vec::from_raw_parts(ret[0] as *mut u8, ret[1], ret[1]);
400            String::from_utf8_unchecked(data)
401        }
402    }
403
404    /// Compare two `JsValue`s for equality, using the `==` operator in JS.
405    ///
406    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality)
407    #[inline]
408    pub fn loose_eq(&self, other: &Self) -> bool {
409        unsafe { __wbindgen_jsval_loose_eq(self.idx, other.idx) != 0 }
410    }
411
412    /// Applies the unary `~` JS operator on a `JsValue`.
413    ///
414    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_NOT)
415    #[inline]
416    pub fn bit_not(&self) -> JsValue {
417        unsafe { JsValue::_new(__wbindgen_bit_not(self.idx)) }
418    }
419
420    /// Applies the binary `>>>` JS operator on the two `JsValue`s.
421    ///
422    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unsigned_right_shift)
423    #[inline]
424    pub fn unsigned_shr(&self, rhs: &Self) -> u32 {
425        unsafe { __wbindgen_unsigned_shr(self.idx, rhs.idx) }
426    }
427
428    /// Applies the binary `/` JS operator on two `JsValue`s, catching and returning any `RangeError` thrown.
429    ///
430    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Division)
431    #[inline]
432    pub fn checked_div(&self, rhs: &Self) -> Self {
433        unsafe { JsValue::_new(__wbindgen_checked_div(self.idx, rhs.idx)) }
434    }
435
436    /// Applies the binary `**` JS operator on the two `JsValue`s.
437    ///
438    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Exponentiation)
439    #[inline]
440    pub fn pow(&self, rhs: &Self) -> Self {
441        unsafe { JsValue::_new(__wbindgen_pow(self.idx, rhs.idx)) }
442    }
443
444    /// Applies the binary `<` JS operator on the two `JsValue`s.
445    ///
446    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Less_than)
447    #[inline]
448    pub fn lt(&self, other: &Self) -> bool {
449        unsafe { __wbindgen_lt(self.idx, other.idx) == 1 }
450    }
451
452    /// Applies the binary `<=` JS operator on the two `JsValue`s.
453    ///
454    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Less_than_or_equal)
455    #[inline]
456    pub fn le(&self, other: &Self) -> bool {
457        unsafe { __wbindgen_le(self.idx, other.idx) == 1 }
458    }
459
460    /// Applies the binary `>=` JS operator on the two `JsValue`s.
461    ///
462    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Greater_than_or_equal)
463    #[inline]
464    pub fn ge(&self, other: &Self) -> bool {
465        unsafe { __wbindgen_ge(self.idx, other.idx) == 1 }
466    }
467
468    /// Applies the binary `>` JS operator on the two `JsValue`s.
469    ///
470    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Greater_than)
471    #[inline]
472    pub fn gt(&self, other: &Self) -> bool {
473        unsafe { __wbindgen_gt(self.idx, other.idx) == 1 }
474    }
475
476    /// Applies the unary `+` JS operator on a `JsValue`. Can throw.
477    ///
478    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus)
479    #[inline]
480    pub fn unchecked_into_f64(&self) -> f64 {
481        unsafe { __wbindgen_as_number(self.idx) }
482    }
483}
484
485impl PartialEq for JsValue {
486    /// Compares two `JsValue`s for equality, using the `===` operator in JS.
487    ///
488    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality)
489    #[inline]
490    fn eq(&self, other: &Self) -> bool {
491        unsafe { __wbindgen_jsval_eq(self.idx, other.idx) != 0 }
492    }
493}
494
495impl PartialEq<bool> for JsValue {
496    #[inline]
497    fn eq(&self, other: &bool) -> bool {
498        self.as_bool() == Some(*other)
499    }
500}
501
502impl PartialEq<str> for JsValue {
503    #[inline]
504    fn eq(&self, other: &str) -> bool {
505        *self == JsValue::from_str(other)
506    }
507}
508
509impl<'a> PartialEq<&'a str> for JsValue {
510    #[inline]
511    fn eq(&self, other: &&'a str) -> bool {
512        <JsValue as PartialEq<str>>::eq(self, other)
513    }
514}
515
516impl PartialEq<String> for JsValue {
517    #[inline]
518    fn eq(&self, other: &String) -> bool {
519        <JsValue as PartialEq<str>>::eq(self, other)
520    }
521}
522impl<'a> PartialEq<&'a String> for JsValue {
523    #[inline]
524    fn eq(&self, other: &&'a String) -> bool {
525        <JsValue as PartialEq<str>>::eq(self, other)
526    }
527}
528
529macro_rules! forward_deref_unop {
530    (impl $imp:ident, $method:ident for $t:ty) => {
531        impl $imp for $t {
532            type Output = <&'static $t as $imp>::Output;
533
534            #[inline]
535            fn $method(self) -> <&'static $t as $imp>::Output {
536                $imp::$method(&self)
537            }
538        }
539    };
540}
541
542macro_rules! forward_deref_binop {
543    (impl $imp:ident, $method:ident for $t:ty) => {
544        impl<'a> $imp<$t> for &'a $t {
545            type Output = <&'static $t as $imp<&'static $t>>::Output;
546
547            #[inline]
548            fn $method(self, other: $t) -> <&'static $t as $imp<&'static $t>>::Output {
549                $imp::$method(self, &other)
550            }
551        }
552
553        impl $imp<&$t> for $t {
554            type Output = <&'static $t as $imp<&'static $t>>::Output;
555
556            #[inline]
557            fn $method(self, other: &$t) -> <&'static $t as $imp<&'static $t>>::Output {
558                $imp::$method(&self, other)
559            }
560        }
561
562        impl $imp<$t> for $t {
563            type Output = <&'static $t as $imp<&'static $t>>::Output;
564
565            #[inline]
566            fn $method(self, other: $t) -> <&'static $t as $imp<&'static $t>>::Output {
567                $imp::$method(&self, &other)
568            }
569        }
570    };
571}
572
573impl Not for &JsValue {
574    type Output = bool;
575
576    /// Applies the `!` JS operator on a `JsValue`.
577    ///
578    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_NOT)
579    #[inline]
580    fn not(self) -> Self::Output {
581        JsValue::is_falsy(self)
582    }
583}
584
585forward_deref_unop!(impl Not, not for JsValue);
586
587impl TryFrom<JsValue> for f64 {
588    type Error = JsValue;
589
590    /// Applies the unary `+` JS operator on a `JsValue`.
591    /// Returns the numeric result on success, or the JS error value on error.
592    ///
593    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus)
594    #[inline]
595    fn try_from(val: JsValue) -> Result<Self, Self::Error> {
596        f64::try_from(&val)
597    }
598}
599
600impl TryFrom<&JsValue> for f64 {
601    type Error = JsValue;
602
603    /// Applies the unary `+` JS operator on a `JsValue`.
604    /// Returns the numeric result on success, or the JS error value on error.
605    ///
606    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus)
607    #[inline]
608    fn try_from(val: &JsValue) -> Result<Self, Self::Error> {
609        let jsval = unsafe { JsValue::_new(__wbindgen_try_into_number(val.idx)) };
610        match jsval.as_f64() {
611            Some(num) => Ok(num),
612            None => Err(jsval),
613        }
614    }
615}
616
617impl Neg for &JsValue {
618    type Output = JsValue;
619
620    /// Applies the unary `-` JS operator on a `JsValue`.
621    ///
622    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_negation)
623    #[inline]
624    fn neg(self) -> Self::Output {
625        unsafe { JsValue::_new(__wbindgen_neg(self.idx)) }
626    }
627}
628
629forward_deref_unop!(impl Neg, neg for JsValue);
630
631impl BitAnd for &JsValue {
632    type Output = JsValue;
633
634    /// Applies the binary `&` JS operator on two `JsValue`s.
635    ///
636    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_AND)
637    #[inline]
638    fn bitand(self, rhs: Self) -> Self::Output {
639        unsafe { JsValue::_new(__wbindgen_bit_and(self.idx, rhs.idx)) }
640    }
641}
642
643forward_deref_binop!(impl BitAnd, bitand for JsValue);
644
645impl BitOr for &JsValue {
646    type Output = JsValue;
647
648    /// Applies the binary `|` JS operator on two `JsValue`s.
649    ///
650    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_OR)
651    #[inline]
652    fn bitor(self, rhs: Self) -> Self::Output {
653        unsafe { JsValue::_new(__wbindgen_bit_or(self.idx, rhs.idx)) }
654    }
655}
656
657forward_deref_binop!(impl BitOr, bitor for JsValue);
658
659impl BitXor for &JsValue {
660    type Output = JsValue;
661
662    /// Applies the binary `^` JS operator on two `JsValue`s.
663    ///
664    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_XOR)
665    #[inline]
666    fn bitxor(self, rhs: Self) -> Self::Output {
667        unsafe { JsValue::_new(__wbindgen_bit_xor(self.idx, rhs.idx)) }
668    }
669}
670
671forward_deref_binop!(impl BitXor, bitxor for JsValue);
672
673impl Shl for &JsValue {
674    type Output = JsValue;
675
676    /// Applies the binary `<<` JS operator on two `JsValue`s.
677    ///
678    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Left_shift)
679    #[inline]
680    fn shl(self, rhs: Self) -> Self::Output {
681        unsafe { JsValue::_new(__wbindgen_shl(self.idx, rhs.idx)) }
682    }
683}
684
685forward_deref_binop!(impl Shl, shl for JsValue);
686
687impl Shr for &JsValue {
688    type Output = JsValue;
689
690    /// Applies the binary `>>` JS operator on two `JsValue`s.
691    ///
692    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Right_shift)
693    #[inline]
694    fn shr(self, rhs: Self) -> Self::Output {
695        unsafe { JsValue::_new(__wbindgen_shr(self.idx, rhs.idx)) }
696    }
697}
698
699forward_deref_binop!(impl Shr, shr for JsValue);
700
701impl Add for &JsValue {
702    type Output = JsValue;
703
704    /// Applies the binary `+` JS operator on two `JsValue`s.
705    ///
706    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Addition)
707    #[inline]
708    fn add(self, rhs: Self) -> Self::Output {
709        unsafe { JsValue::_new(__wbindgen_add(self.idx, rhs.idx)) }
710    }
711}
712
713forward_deref_binop!(impl Add, add for JsValue);
714
715impl Sub for &JsValue {
716    type Output = JsValue;
717
718    /// Applies the binary `-` JS operator on two `JsValue`s.
719    ///
720    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Subtraction)
721    #[inline]
722    fn sub(self, rhs: Self) -> Self::Output {
723        unsafe { JsValue::_new(__wbindgen_sub(self.idx, rhs.idx)) }
724    }
725}
726
727forward_deref_binop!(impl Sub, sub for JsValue);
728
729impl Div for &JsValue {
730    type Output = JsValue;
731
732    /// Applies the binary `/` JS operator on two `JsValue`s.
733    ///
734    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Division)
735    #[inline]
736    fn div(self, rhs: Self) -> Self::Output {
737        unsafe { JsValue::_new(__wbindgen_div(self.idx, rhs.idx)) }
738    }
739}
740
741forward_deref_binop!(impl Div, div for JsValue);
742
743impl Mul for &JsValue {
744    type Output = JsValue;
745
746    /// Applies the binary `*` JS operator on two `JsValue`s.
747    ///
748    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Multiplication)
749    #[inline]
750    fn mul(self, rhs: Self) -> Self::Output {
751        unsafe { JsValue::_new(__wbindgen_mul(self.idx, rhs.idx)) }
752    }
753}
754
755forward_deref_binop!(impl Mul, mul for JsValue);
756
757impl Rem for &JsValue {
758    type Output = JsValue;
759
760    /// Applies the binary `%` JS operator on two `JsValue`s.
761    ///
762    /// [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder)
763    #[inline]
764    fn rem(self, rhs: Self) -> Self::Output {
765        unsafe { JsValue::_new(__wbindgen_rem(self.idx, rhs.idx)) }
766    }
767}
768
769forward_deref_binop!(impl Rem, rem for JsValue);
770
771impl<'a> From<&'a str> for JsValue {
772    #[inline]
773    fn from(s: &'a str) -> JsValue {
774        JsValue::from_str(s)
775    }
776}
777
778impl<T> From<*mut T> for JsValue {
779    #[inline]
780    fn from(s: *mut T) -> JsValue {
781        JsValue::from(s as usize)
782    }
783}
784
785impl<T> From<*const T> for JsValue {
786    #[inline]
787    fn from(s: *const T) -> JsValue {
788        JsValue::from(s as usize)
789    }
790}
791
792impl<T> From<NonNull<T>> for JsValue {
793    #[inline]
794    fn from(s: NonNull<T>) -> JsValue {
795        JsValue::from(s.as_ptr() as usize)
796    }
797}
798
799impl<'a> From<&'a String> for JsValue {
800    #[inline]
801    fn from(s: &'a String) -> JsValue {
802        JsValue::from_str(s)
803    }
804}
805
806impl From<String> for JsValue {
807    #[inline]
808    fn from(s: String) -> JsValue {
809        JsValue::from_str(&s)
810    }
811}
812
813impl TryFrom<JsValue> for String {
814    type Error = JsValue;
815
816    fn try_from(value: JsValue) -> Result<Self, Self::Error> {
817        match value.as_string() {
818            Some(s) => Ok(s),
819            None => Err(value),
820        }
821    }
822}
823
824impl TryFromJsValue for String {
825    type Error = JsValue;
826
827    fn try_from_js_value(value: JsValue) -> Result<Self, Self::Error> {
828        match value.as_string() {
829            Some(s) => Ok(s),
830            None => Err(value),
831        }
832    }
833}
834
835impl From<bool> for JsValue {
836    #[inline]
837    fn from(s: bool) -> JsValue {
838        JsValue::from_bool(s)
839    }
840}
841
842impl<'a, T> From<&'a T> for JsValue
843where
844    T: JsCast,
845{
846    #[inline]
847    fn from(s: &'a T) -> JsValue {
848        s.as_ref().clone()
849    }
850}
851
852impl<T> From<Option<T>> for JsValue
853where
854    JsValue: From<T>,
855{
856    #[inline]
857    fn from(s: Option<T>) -> JsValue {
858        match s {
859            Some(s) => s.into(),
860            None => JsValue::undefined(),
861        }
862    }
863}
864
865impl JsCast for JsValue {
866    // everything is a `JsValue`!
867    #[inline]
868    fn instanceof(_val: &JsValue) -> bool {
869        true
870    }
871    #[inline]
872    fn unchecked_from_js(val: JsValue) -> Self {
873        val
874    }
875    #[inline]
876    fn unchecked_from_js_ref(val: &JsValue) -> &Self {
877        val
878    }
879}
880
881impl AsRef<JsValue> for JsValue {
882    #[inline]
883    fn as_ref(&self) -> &JsValue {
884        self
885    }
886}
887
888macro_rules! numbers {
889    ($($n:ident)*) => ($(
890        impl PartialEq<$n> for JsValue {
891            #[inline]
892            fn eq(&self, other: &$n) -> bool {
893                self.as_f64() == Some(f64::from(*other))
894            }
895        }
896
897        impl From<$n> for JsValue {
898            #[inline]
899            fn from(n: $n) -> JsValue {
900                JsValue::from_f64(n.into())
901            }
902        }
903    )*)
904}
905
906numbers! { i8 u8 i16 u16 i32 u32 f32 f64 }
907
908macro_rules! big_numbers {
909    (|$arg:ident|, $($n:ident = $handle:expr,)*) => ($(
910        impl PartialEq<$n> for JsValue {
911            #[inline]
912            fn eq(&self, other: &$n) -> bool {
913                self == &JsValue::from(*other)
914            }
915        }
916
917        impl From<$n> for JsValue {
918            #[inline]
919            fn from($arg: $n) -> JsValue {
920                unsafe { JsValue::_new($handle) }
921            }
922        }
923    )*)
924}
925
926fn bigint_get_as_i64(v: &JsValue) -> Option<i64> {
927    unsafe { __wbindgen_bigint_get_as_i64(v.idx).join() }
928}
929
930macro_rules! try_from_for_num64 {
931    ($ty:ty) => {
932        impl TryFrom<JsValue> for $ty {
933            type Error = JsValue;
934
935            #[inline]
936            fn try_from(v: JsValue) -> Result<Self, JsValue> {
937                bigint_get_as_i64(&v)
938                    // Reinterpret bits; ABI-wise this is safe to do and allows us to avoid
939                    // having separate intrinsics per signed/unsigned types.
940                    .map(|as_i64| as_i64 as Self)
941                    // Double-check that we didn't truncate the bigint to 64 bits.
942                    .filter(|as_self| v == *as_self)
943                    // Not a bigint or not in range.
944                    .ok_or(v)
945            }
946        }
947    };
948}
949
950try_from_for_num64!(i64);
951try_from_for_num64!(u64);
952
953macro_rules! try_from_for_num128 {
954    ($ty:ty, $hi_ty:ty) => {
955        impl TryFrom<JsValue> for $ty {
956            type Error = JsValue;
957
958            #[inline]
959            fn try_from(v: JsValue) -> Result<Self, JsValue> {
960                // Truncate the bigint to 64 bits, this will give us the lower part.
961                let lo = match bigint_get_as_i64(&v) {
962                    // The lower part must be interpreted as unsigned in both i128 and u128.
963                    Some(lo) => lo as u64,
964                    // Not a bigint.
965                    None => return Err(v),
966                };
967                // Now we know it's a bigint, so we can safely use `>> 64n` without
968                // worrying about a JS exception on type mismatch.
969                let hi = v >> JsValue::from(64_u64);
970                // The high part is the one we want checked against a 64-bit range.
971                // If it fits, then our original number is in the 128-bit range.
972                let hi = <$hi_ty>::try_from(hi)?;
973                Ok(Self::from(hi) << 64 | Self::from(lo))
974            }
975        }
976    };
977}
978
979try_from_for_num128!(i128, i64);
980try_from_for_num128!(u128, u64);
981
982big_numbers! {
983    |n|,
984    i64 = __wbindgen_bigint_from_i64(n),
985    u64 = __wbindgen_bigint_from_u64(n),
986    i128 = __wbindgen_bigint_from_i128((n >> 64) as i64, n as u64),
987    u128 = __wbindgen_bigint_from_u128((n >> 64) as u64, n as u64),
988}
989
990// `usize` and `isize` have to be treated a bit specially, because we know that
991// they're 32-bit but the compiler conservatively assumes they might be bigger.
992// So, we have to manually forward to the `u32`/`i32` versions.
993impl PartialEq<usize> for JsValue {
994    #[inline]
995    fn eq(&self, other: &usize) -> bool {
996        *self == (*other as u32)
997    }
998}
999
1000impl From<usize> for JsValue {
1001    #[inline]
1002    fn from(n: usize) -> Self {
1003        Self::from(n as u32)
1004    }
1005}
1006
1007impl PartialEq<isize> for JsValue {
1008    #[inline]
1009    fn eq(&self, other: &isize) -> bool {
1010        *self == (*other as i32)
1011    }
1012}
1013
1014impl From<isize> for JsValue {
1015    #[inline]
1016    fn from(n: isize) -> Self {
1017        Self::from(n as i32)
1018    }
1019}
1020
1021externs! {
1022    #[link(wasm_import_module = "__wbindgen_placeholder__")]
1023    extern "C" {
1024        fn __wbindgen_object_clone_ref(idx: u32) -> u32;
1025        fn __wbindgen_object_drop_ref(idx: u32) -> ();
1026
1027        fn __wbindgen_string_new(ptr: *const u8, len: usize) -> u32;
1028        fn __wbindgen_number_new(f: f64) -> u32;
1029        fn __wbindgen_bigint_from_str(ptr: *const u8, len: usize) -> u32;
1030        fn __wbindgen_bigint_from_i64(n: i64) -> u32;
1031        fn __wbindgen_bigint_from_u64(n: u64) -> u32;
1032        fn __wbindgen_bigint_from_i128(hi: i64, lo: u64) -> u32;
1033        fn __wbindgen_bigint_from_u128(hi: u64, lo: u64) -> u32;
1034        fn __wbindgen_symbol_named_new(ptr: *const u8, len: usize) -> u32;
1035        fn __wbindgen_symbol_anonymous_new() -> u32;
1036
1037        fn __wbindgen_externref_heap_live_count() -> u32;
1038
1039        fn __wbindgen_is_null(idx: u32) -> u32;
1040        fn __wbindgen_is_undefined(idx: u32) -> u32;
1041        fn __wbindgen_is_symbol(idx: u32) -> u32;
1042        fn __wbindgen_is_object(idx: u32) -> u32;
1043        fn __wbindgen_is_array(idx: u32) -> u32;
1044        fn __wbindgen_is_function(idx: u32) -> u32;
1045        fn __wbindgen_is_string(idx: u32) -> u32;
1046        fn __wbindgen_is_bigint(idx: u32) -> u32;
1047        fn __wbindgen_typeof(idx: u32) -> u32;
1048
1049        fn __wbindgen_in(prop: u32, obj: u32) -> u32;
1050
1051        fn __wbindgen_is_falsy(idx: u32) -> u32;
1052        fn __wbindgen_as_number(idx: u32) -> f64;
1053        fn __wbindgen_try_into_number(idx: u32) -> u32;
1054        fn __wbindgen_neg(idx: u32) -> u32;
1055        fn __wbindgen_bit_and(a: u32, b: u32) -> u32;
1056        fn __wbindgen_bit_or(a: u32, b: u32) -> u32;
1057        fn __wbindgen_bit_xor(a: u32, b: u32) -> u32;
1058        fn __wbindgen_bit_not(idx: u32) -> u32;
1059        fn __wbindgen_shl(a: u32, b: u32) -> u32;
1060        fn __wbindgen_shr(a: u32, b: u32) -> u32;
1061        fn __wbindgen_unsigned_shr(a: u32, b: u32) -> u32;
1062        fn __wbindgen_add(a: u32, b: u32) -> u32;
1063        fn __wbindgen_sub(a: u32, b: u32) -> u32;
1064        fn __wbindgen_div(a: u32, b: u32) -> u32;
1065        fn __wbindgen_checked_div(a: u32, b: u32) -> u32;
1066        fn __wbindgen_mul(a: u32, b: u32) -> u32;
1067        fn __wbindgen_rem(a: u32, b: u32) -> u32;
1068        fn __wbindgen_pow(a: u32, b: u32) -> u32;
1069        fn __wbindgen_lt(a: u32, b: u32) -> u32;
1070        fn __wbindgen_le(a: u32, b: u32) -> u32;
1071        fn __wbindgen_ge(a: u32, b: u32) -> u32;
1072        fn __wbindgen_gt(a: u32, b: u32) -> u32;
1073
1074        fn __wbindgen_number_get(idx: u32) -> WasmRet<Option<f64>>;
1075        fn __wbindgen_boolean_get(idx: u32) -> u32;
1076        fn __wbindgen_string_get(idx: u32) -> WasmSlice;
1077        fn __wbindgen_bigint_get_as_i64(idx: u32) -> WasmRet<Option<i64>>;
1078
1079        fn __wbindgen_debug_string(ret: *mut [usize; 2], idx: u32) -> ();
1080
1081        fn __wbindgen_throw(a: *const u8, b: usize) -> !;
1082        fn __wbindgen_rethrow(a: u32) -> !;
1083        fn __wbindgen_error_new(a: *const u8, b: usize) -> u32;
1084
1085        fn __wbindgen_cb_drop(idx: u32) -> u32;
1086
1087        fn __wbindgen_describe(v: u32) -> ();
1088        fn __wbindgen_describe_closure(a: u32, b: u32, c: u32) -> u32;
1089
1090        fn __wbindgen_json_parse(ptr: *const u8, len: usize) -> u32;
1091        fn __wbindgen_json_serialize(idx: u32) -> WasmSlice;
1092        fn __wbindgen_jsval_eq(a: u32, b: u32) -> u32;
1093        fn __wbindgen_jsval_loose_eq(a: u32, b: u32) -> u32;
1094
1095        fn __wbindgen_copy_to_typed_array(ptr: *const u8, len: usize, idx: u32) -> ();
1096
1097        fn __wbindgen_uint8_array_new(ptr: *mut u8, len: usize) -> u32;
1098        fn __wbindgen_uint8_clamped_array_new(ptr: *mut u8, len: usize) -> u32;
1099        fn __wbindgen_uint16_array_new(ptr: *mut u16, len: usize) -> u32;
1100        fn __wbindgen_uint32_array_new(ptr: *mut u32, len: usize) -> u32;
1101        fn __wbindgen_biguint64_array_new(ptr: *mut u64, len: usize) -> u32;
1102        fn __wbindgen_int8_array_new(ptr: *mut i8, len: usize) -> u32;
1103        fn __wbindgen_int16_array_new(ptr: *mut i16, len: usize) -> u32;
1104        fn __wbindgen_int32_array_new(ptr: *mut i32, len: usize) -> u32;
1105        fn __wbindgen_bigint64_array_new(ptr: *mut i64, len: usize) -> u32;
1106        fn __wbindgen_float32_array_new(ptr: *mut f32, len: usize) -> u32;
1107        fn __wbindgen_float64_array_new(ptr: *mut f64, len: usize) -> u32;
1108
1109        fn __wbindgen_array_new() -> u32;
1110        fn __wbindgen_array_push(array: u32, value: u32) -> ();
1111
1112        fn __wbindgen_not(idx: u32) -> u32;
1113
1114        fn __wbindgen_exports() -> u32;
1115        fn __wbindgen_memory() -> u32;
1116        fn __wbindgen_module() -> u32;
1117        fn __wbindgen_function_table() -> u32;
1118    }
1119}
1120
1121impl Clone for JsValue {
1122    #[inline]
1123    fn clone(&self) -> JsValue {
1124        unsafe {
1125            let idx = __wbindgen_object_clone_ref(self.idx);
1126            JsValue::_new(idx)
1127        }
1128    }
1129}
1130
1131#[cfg(feature = "std")]
1132impl core::fmt::Debug for JsValue {
1133    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1134        write!(f, "JsValue({})", self.as_debug_string())
1135    }
1136}
1137
1138#[cfg(not(feature = "std"))]
1139impl core::fmt::Debug for JsValue {
1140    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1141        f.write_str("JsValue")
1142    }
1143}
1144
1145impl Drop for JsValue {
1146    #[inline]
1147    fn drop(&mut self) {
1148        unsafe {
1149            // We definitely should never drop anything in the stack area
1150            debug_assert!(self.idx >= JSIDX_OFFSET, "free of stack slot {}", self.idx);
1151
1152            // Otherwise if we're not dropping one of our reserved values,
1153            // actually call the intrinsic. See #1054 for eventually removing
1154            // this branch.
1155            if self.idx >= JSIDX_RESERVED {
1156                __wbindgen_object_drop_ref(self.idx);
1157            }
1158        }
1159    }
1160}
1161
1162impl Default for JsValue {
1163    fn default() -> Self {
1164        Self::UNDEFINED
1165    }
1166}
1167
1168/// Wrapper type for imported statics.
1169///
1170/// This type is used whenever a `static` is imported from a JS module, for
1171/// example this import:
1172///
1173/// ```ignore
1174/// #[wasm_bindgen]
1175/// extern "C" {
1176///     static console: JsValue;
1177/// }
1178/// ```
1179///
1180/// will generate in Rust a value that looks like:
1181///
1182/// ```ignore
1183/// static console: JsStatic<JsValue> = ...;
1184/// ```
1185///
1186/// This type implements `Deref` to the inner type so it's typically used as if
1187/// it were `&T`.
1188#[cfg(feature = "std")]
1189#[deprecated = "use with `#[wasm_bindgen(thread_local)]` instead"]
1190pub struct JsStatic<T: 'static> {
1191    #[doc(hidden)]
1192    pub __inner: &'static std::thread::LocalKey<T>,
1193}
1194
1195#[cfg(feature = "std")]
1196#[allow(deprecated)]
1197#[cfg(not(target_feature = "atomics"))]
1198impl<T: FromWasmAbi + 'static> Deref for JsStatic<T> {
1199    type Target = T;
1200    fn deref(&self) -> &T {
1201        unsafe { self.__inner.with(|ptr| &*(ptr as *const T)) }
1202    }
1203}
1204
1205#[cold]
1206#[inline(never)]
1207#[deprecated(note = "renamed to `throw_str`")]
1208#[doc(hidden)]
1209pub fn throw(s: &str) -> ! {
1210    throw_str(s)
1211}
1212
1213/// Throws a JS exception.
1214///
1215/// This function will throw a JS exception with the message provided. The
1216/// function will not return as the wasm stack will be popped when the exception
1217/// is thrown.
1218///
1219/// Note that it is very easy to leak memory with this function because this
1220/// function, unlike `panic!` on other platforms, **will not run destructors**.
1221/// It's recommended to return a `Result` where possible to avoid the worry of
1222/// leaks.
1223#[cold]
1224#[inline(never)]
1225pub fn throw_str(s: &str) -> ! {
1226    unsafe {
1227        __wbindgen_throw(s.as_ptr(), s.len());
1228    }
1229}
1230
1231/// Rethrow a JS exception
1232///
1233/// This function will throw a JS exception with the JS value provided. This
1234/// function will not return and the wasm stack will be popped until the point
1235/// of entry of wasm itself.
1236///
1237/// Note that it is very easy to leak memory with this function because this
1238/// function, unlike `panic!` on other platforms, **will not run destructors**.
1239/// It's recommended to return a `Result` where possible to avoid the worry of
1240/// leaks.
1241#[cold]
1242#[inline(never)]
1243pub fn throw_val(s: JsValue) -> ! {
1244    unsafe {
1245        let idx = s.idx;
1246        mem::forget(s);
1247        __wbindgen_rethrow(idx);
1248    }
1249}
1250
1251/// Get the count of live `externref`s / `JsValue`s in `wasm-bindgen`'s heap.
1252///
1253/// ## Usage
1254///
1255/// This is intended for debugging and writing tests.
1256///
1257/// To write a test that asserts against unnecessarily keeping `anref`s /
1258/// `JsValue`s alive:
1259///
1260/// * get an initial live count,
1261///
1262/// * perform some series of operations or function calls that should clean up
1263///   after themselves, and should not keep holding onto `externref`s / `JsValue`s
1264///   after completion,
1265///
1266/// * get the final live count,
1267///
1268/// * and assert that the initial and final counts are the same.
1269///
1270/// ## What is Counted
1271///
1272/// Note that this only counts the *owned* `externref`s / `JsValue`s that end up in
1273/// `wasm-bindgen`'s heap. It does not count borrowed `externref`s / `JsValue`s
1274/// that are on its stack.
1275///
1276/// For example, these `JsValue`s are accounted for:
1277///
1278/// ```ignore
1279/// #[wasm_bindgen]
1280/// pub fn my_function(this_is_counted: JsValue) {
1281///     let also_counted = JsValue::from_str("hi");
1282///     assert!(wasm_bindgen::externref_heap_live_count() >= 2);
1283/// }
1284/// ```
1285///
1286/// While this borrowed `JsValue` ends up on the stack, not the heap, and
1287/// therefore is not accounted for:
1288///
1289/// ```ignore
1290/// #[wasm_bindgen]
1291/// pub fn my_other_function(this_is_not_counted: &JsValue) {
1292///     // ...
1293/// }
1294/// ```
1295pub fn externref_heap_live_count() -> u32 {
1296    unsafe { __wbindgen_externref_heap_live_count() }
1297}
1298
1299#[doc(hidden)]
1300pub fn anyref_heap_live_count() -> u32 {
1301    externref_heap_live_count()
1302}
1303
1304/// An extension trait for `Option<T>` and `Result<T, E>` for unwrapping the `T`
1305/// value, or throwing a JS error if it is not available.
1306///
1307/// These methods should have a smaller code size footprint than the normal
1308/// `Option::unwrap` and `Option::expect` methods, but they are specific to
1309/// working with wasm and JS.
1310///
1311/// On non-wasm32 targets, defaults to the normal unwrap/expect calls.
1312///
1313/// # Example
1314///
1315/// ```
1316/// use wasm_bindgen::prelude::*;
1317///
1318/// // If the value is `Option::Some` or `Result::Ok`, then we just get the
1319/// // contained `T` value.
1320/// let x = Some(42);
1321/// assert_eq!(x.unwrap_throw(), 42);
1322///
1323/// let y: Option<i32> = None;
1324///
1325/// // This call would throw an error to JS!
1326/// //
1327/// //     y.unwrap_throw()
1328/// //
1329/// // And this call would throw an error to JS with a custom error message!
1330/// //
1331/// //     y.expect_throw("woopsie daisy!")
1332/// ```
1333pub trait UnwrapThrowExt<T>: Sized {
1334    /// Unwrap this `Option` or `Result`, but instead of panicking on failure,
1335    /// throw an exception to JavaScript.
1336    #[cfg_attr(
1337        any(
1338            debug_assertions,
1339            not(all(target_arch = "wasm32", target_os = "unknown"))
1340        ),
1341        track_caller
1342    )]
1343    fn unwrap_throw(self) -> T {
1344        if cfg!(all(
1345            debug_assertions,
1346            all(target_arch = "wasm32", target_os = "unknown")
1347        )) {
1348            let loc = core::panic::Location::caller();
1349            let msg = alloc::format!(
1350                "called `{}::unwrap_throw()` ({}:{}:{})",
1351                core::any::type_name::<Self>(),
1352                loc.file(),
1353                loc.line(),
1354                loc.column()
1355            );
1356            self.expect_throw(&msg)
1357        } else {
1358            self.expect_throw("called `unwrap_throw()`")
1359        }
1360    }
1361
1362    /// Unwrap this container's `T` value, or throw an error to JS with the
1363    /// given message if the `T` value is unavailable (e.g. an `Option<T>` is
1364    /// `None`).
1365    #[cfg_attr(
1366        any(
1367            debug_assertions,
1368            not(all(target_arch = "wasm32", target_os = "unknown"))
1369        ),
1370        track_caller
1371    )]
1372    fn expect_throw(self, message: &str) -> T;
1373}
1374
1375impl<T> UnwrapThrowExt<T> for Option<T> {
1376    fn unwrap_throw(self) -> T {
1377        const MSG: &str = "called `Option::unwrap_throw()` on a `None` value";
1378
1379        if cfg!(all(target_arch = "wasm32", target_os = "unknown")) {
1380            if let Some(val) = self {
1381                val
1382            } else if cfg!(debug_assertions) {
1383                let loc = core::panic::Location::caller();
1384                let msg =
1385                    alloc::format!("{} ({}:{}:{})", MSG, loc.file(), loc.line(), loc.column(),);
1386
1387                throw_str(&msg)
1388            } else {
1389                throw_str(MSG)
1390            }
1391        } else {
1392            self.expect(MSG)
1393        }
1394    }
1395
1396    fn expect_throw(self, message: &str) -> T {
1397        if cfg!(all(target_arch = "wasm32", target_os = "unknown")) {
1398            if let Some(val) = self {
1399                val
1400            } else if cfg!(debug_assertions) {
1401                let loc = core::panic::Location::caller();
1402                let msg = alloc::format!(
1403                    "{} ({}:{}:{})",
1404                    message,
1405                    loc.file(),
1406                    loc.line(),
1407                    loc.column(),
1408                );
1409
1410                throw_str(&msg)
1411            } else {
1412                throw_str(message)
1413            }
1414        } else {
1415            self.expect(message)
1416        }
1417    }
1418}
1419
1420impl<T, E> UnwrapThrowExt<T> for Result<T, E>
1421where
1422    E: core::fmt::Debug,
1423{
1424    fn unwrap_throw(self) -> T {
1425        const MSG: &str = "called `Result::unwrap_throw()` on an `Err` value";
1426
1427        if cfg!(all(target_arch = "wasm32", target_os = "unknown")) {
1428            match self {
1429                Ok(val) => val,
1430                Err(err) => {
1431                    if cfg!(debug_assertions) {
1432                        let loc = core::panic::Location::caller();
1433                        let msg = alloc::format!(
1434                            "{} ({}:{}:{}): {:?}",
1435                            MSG,
1436                            loc.file(),
1437                            loc.line(),
1438                            loc.column(),
1439                            err
1440                        );
1441
1442                        throw_str(&msg)
1443                    } else {
1444                        throw_str(MSG)
1445                    }
1446                }
1447            }
1448        } else {
1449            self.expect(MSG)
1450        }
1451    }
1452
1453    fn expect_throw(self, message: &str) -> T {
1454        if cfg!(all(target_arch = "wasm32", target_os = "unknown")) {
1455            match self {
1456                Ok(val) => val,
1457                Err(err) => {
1458                    if cfg!(debug_assertions) {
1459                        let loc = core::panic::Location::caller();
1460                        let msg = alloc::format!(
1461                            "{} ({}:{}:{}): {:?}",
1462                            message,
1463                            loc.file(),
1464                            loc.line(),
1465                            loc.column(),
1466                            err
1467                        );
1468
1469                        throw_str(&msg)
1470                    } else {
1471                        throw_str(message)
1472                    }
1473                }
1474            }
1475        } else {
1476            self.expect(message)
1477        }
1478    }
1479}
1480
1481/// Returns a handle to this Wasm instance's `WebAssembly.Module`.
1482/// This is only available when the final Wasm app is built with
1483/// `--target no-modules` or `--target web`.
1484pub fn module() -> JsValue {
1485    unsafe { JsValue::_new(__wbindgen_module()) }
1486}
1487
1488/// Returns a handle to this wasm instance's `WebAssembly.Instance.prototype.exports`
1489pub fn exports() -> JsValue {
1490    unsafe { JsValue::_new(__wbindgen_exports()) }
1491}
1492
1493/// Returns a handle to this wasm instance's `WebAssembly.Memory`
1494pub fn memory() -> JsValue {
1495    unsafe { JsValue::_new(__wbindgen_memory()) }
1496}
1497
1498/// Returns a handle to this wasm instance's `WebAssembly.Table` which is the
1499/// indirect function table used by Rust
1500pub fn function_table() -> JsValue {
1501    unsafe { JsValue::_new(__wbindgen_function_table()) }
1502}
1503
1504#[doc(hidden)]
1505pub mod __rt {
1506    use crate::JsValue;
1507    use core::borrow::{Borrow, BorrowMut};
1508    use core::cell::{Cell, UnsafeCell};
1509    use core::convert::Infallible;
1510    use core::mem;
1511    use core::ops::{Deref, DerefMut};
1512
1513    pub extern crate alloc;
1514    pub extern crate core;
1515    #[cfg(feature = "std")]
1516    pub extern crate std;
1517
1518    use alloc::alloc::{alloc, dealloc, realloc, Layout};
1519    use alloc::boxed::Box;
1520    use alloc::rc::Rc;
1521    pub use once_cell::sync::Lazy;
1522
1523    #[macro_export]
1524    #[doc(hidden)]
1525    #[cfg(feature = "std")]
1526    macro_rules! __wbindgen_if_not_std {
1527        ($($i:item)*) => {};
1528    }
1529
1530    #[macro_export]
1531    #[doc(hidden)]
1532    #[cfg(not(feature = "std"))]
1533    macro_rules! __wbindgen_if_not_std {
1534        ($($i:item)*) => ($($i)*)
1535    }
1536
1537    #[inline]
1538    pub fn assert_not_null<T>(s: *mut T) {
1539        if s.is_null() {
1540            throw_null();
1541        }
1542    }
1543
1544    #[cold]
1545    #[inline(never)]
1546    fn throw_null() -> ! {
1547        super::throw_str("null pointer passed to rust");
1548    }
1549
1550    /// A vendored version of `RefCell` from the standard library.
1551    ///
1552    /// Now why, you may ask, would we do that? Surely `RefCell` in libstd is
1553    /// quite good. And you're right, it is indeed quite good! Functionally
1554    /// nothing more is needed from `RefCell` in the standard library but for
1555    /// now this crate is also sort of optimizing for compiled code size.
1556    ///
1557    /// One major factor to larger binaries in Rust is when a panic happens.
1558    /// Panicking in the standard library involves a fair bit of machinery
1559    /// (formatting, panic hooks, synchronization, etc). It's all worthwhile if
1560    /// you need it but for something like `WasmRefCell` here we don't actually
1561    /// need all that!
1562    ///
1563    /// This is just a wrapper around all Rust objects passed to JS intended to
1564    /// guard accidental reentrancy, so this vendored version is intended solely
1565    /// to not panic in libstd. Instead when it "panics" it calls our `throw`
1566    /// function in this crate which raises an error in JS.
1567    pub struct WasmRefCell<T: ?Sized> {
1568        borrow: Cell<usize>,
1569        value: UnsafeCell<T>,
1570    }
1571
1572    impl<T: ?Sized> WasmRefCell<T> {
1573        pub fn new(value: T) -> WasmRefCell<T>
1574        where
1575            T: Sized,
1576        {
1577            WasmRefCell {
1578                value: UnsafeCell::new(value),
1579                borrow: Cell::new(0),
1580            }
1581        }
1582
1583        pub fn get_mut(&mut self) -> &mut T {
1584            unsafe { &mut *self.value.get() }
1585        }
1586
1587        pub fn borrow(&self) -> Ref<T> {
1588            unsafe {
1589                if self.borrow.get() == usize::MAX {
1590                    borrow_fail();
1591                }
1592                self.borrow.set(self.borrow.get() + 1);
1593                Ref {
1594                    value: &*self.value.get(),
1595                    borrow: &self.borrow,
1596                }
1597            }
1598        }
1599
1600        pub fn borrow_mut(&self) -> RefMut<T> {
1601            unsafe {
1602                if self.borrow.get() != 0 {
1603                    borrow_fail();
1604                }
1605                self.borrow.set(usize::MAX);
1606                RefMut {
1607                    value: &mut *self.value.get(),
1608                    borrow: &self.borrow,
1609                }
1610            }
1611        }
1612
1613        pub fn into_inner(self) -> T
1614        where
1615            T: Sized,
1616        {
1617            self.value.into_inner()
1618        }
1619    }
1620
1621    pub struct Ref<'b, T: ?Sized + 'b> {
1622        value: &'b T,
1623        borrow: &'b Cell<usize>,
1624    }
1625
1626    impl<'b, T: ?Sized> Deref for Ref<'b, T> {
1627        type Target = T;
1628
1629        #[inline]
1630        fn deref(&self) -> &T {
1631            self.value
1632        }
1633    }
1634
1635    impl<'b, T: ?Sized> Borrow<T> for Ref<'b, T> {
1636        #[inline]
1637        fn borrow(&self) -> &T {
1638            self.value
1639        }
1640    }
1641
1642    impl<'b, T: ?Sized> Drop for Ref<'b, T> {
1643        fn drop(&mut self) {
1644            self.borrow.set(self.borrow.get() - 1);
1645        }
1646    }
1647
1648    pub struct RefMut<'b, T: ?Sized + 'b> {
1649        value: &'b mut T,
1650        borrow: &'b Cell<usize>,
1651    }
1652
1653    impl<'b, T: ?Sized> Deref for RefMut<'b, T> {
1654        type Target = T;
1655
1656        #[inline]
1657        fn deref(&self) -> &T {
1658            self.value
1659        }
1660    }
1661
1662    impl<'b, T: ?Sized> DerefMut for RefMut<'b, T> {
1663        #[inline]
1664        fn deref_mut(&mut self) -> &mut T {
1665            self.value
1666        }
1667    }
1668
1669    impl<'b, T: ?Sized> Borrow<T> for RefMut<'b, T> {
1670        #[inline]
1671        fn borrow(&self) -> &T {
1672            self.value
1673        }
1674    }
1675
1676    impl<'b, T: ?Sized> BorrowMut<T> for RefMut<'b, T> {
1677        #[inline]
1678        fn borrow_mut(&mut self) -> &mut T {
1679            self.value
1680        }
1681    }
1682
1683    impl<'b, T: ?Sized> Drop for RefMut<'b, T> {
1684        fn drop(&mut self) {
1685            self.borrow.set(0);
1686        }
1687    }
1688
1689    fn borrow_fail() -> ! {
1690        super::throw_str(
1691            "recursive use of an object detected which would lead to \
1692             unsafe aliasing in rust",
1693        );
1694    }
1695
1696    /// A type that encapsulates an `Rc<WasmRefCell<T>>` as well as a `Ref`
1697    /// to the contents of that `WasmRefCell`.
1698    ///
1699    /// The `'static` requirement is an unfortunate consequence of how this
1700    /// is implemented.
1701    pub struct RcRef<T: ?Sized + 'static> {
1702        // The 'static is a lie.
1703        //
1704        // We could get away without storing this, since we're in the same module as
1705        // `WasmRefCell` and can directly manipulate its `borrow`, but I'm considering
1706        // turning it into a wrapper around `std`'s `RefCell` to reduce `unsafe` in
1707        // which case that would stop working. This also requires less `unsafe` as is.
1708        //
1709        // It's important that this goes before `Rc` so that it gets dropped first.
1710        ref_: Ref<'static, T>,
1711        _rc: Rc<WasmRefCell<T>>,
1712    }
1713
1714    impl<T: ?Sized> RcRef<T> {
1715        pub fn new(rc: Rc<WasmRefCell<T>>) -> Self {
1716            let ref_ = unsafe { (*Rc::as_ptr(&rc)).borrow() };
1717            Self { _rc: rc, ref_ }
1718        }
1719    }
1720
1721    impl<T: ?Sized> Deref for RcRef<T> {
1722        type Target = T;
1723
1724        #[inline]
1725        fn deref(&self) -> &T {
1726            &self.ref_
1727        }
1728    }
1729
1730    impl<T: ?Sized> Borrow<T> for RcRef<T> {
1731        #[inline]
1732        fn borrow(&self) -> &T {
1733            &self.ref_
1734        }
1735    }
1736
1737    /// A type that encapsulates an `Rc<WasmRefCell<T>>` as well as a
1738    /// `RefMut` to the contents of that `WasmRefCell`.
1739    ///
1740    /// The `'static` requirement is an unfortunate consequence of how this
1741    /// is implemented.
1742    pub struct RcRefMut<T: ?Sized + 'static> {
1743        ref_: RefMut<'static, T>,
1744        _rc: Rc<WasmRefCell<T>>,
1745    }
1746
1747    impl<T: ?Sized> RcRefMut<T> {
1748        pub fn new(rc: Rc<WasmRefCell<T>>) -> Self {
1749            let ref_ = unsafe { (*Rc::as_ptr(&rc)).borrow_mut() };
1750            Self { _rc: rc, ref_ }
1751        }
1752    }
1753
1754    impl<T: ?Sized> Deref for RcRefMut<T> {
1755        type Target = T;
1756
1757        #[inline]
1758        fn deref(&self) -> &T {
1759            &self.ref_
1760        }
1761    }
1762
1763    impl<T: ?Sized> DerefMut for RcRefMut<T> {
1764        #[inline]
1765        fn deref_mut(&mut self) -> &mut T {
1766            &mut self.ref_
1767        }
1768    }
1769
1770    impl<T: ?Sized> Borrow<T> for RcRefMut<T> {
1771        #[inline]
1772        fn borrow(&self) -> &T {
1773            &self.ref_
1774        }
1775    }
1776
1777    impl<T: ?Sized> BorrowMut<T> for RcRefMut<T> {
1778        #[inline]
1779        fn borrow_mut(&mut self) -> &mut T {
1780            &mut self.ref_
1781        }
1782    }
1783
1784    #[no_mangle]
1785    pub extern "C" fn __wbindgen_malloc(size: usize, align: usize) -> *mut u8 {
1786        if let Ok(layout) = Layout::from_size_align(size, align) {
1787            unsafe {
1788                if layout.size() > 0 {
1789                    let ptr = alloc(layout);
1790                    if !ptr.is_null() {
1791                        return ptr;
1792                    }
1793                } else {
1794                    return align as *mut u8;
1795                }
1796            }
1797        }
1798
1799        malloc_failure();
1800    }
1801
1802    #[no_mangle]
1803    pub unsafe extern "C" fn __wbindgen_realloc(
1804        ptr: *mut u8,
1805        old_size: usize,
1806        new_size: usize,
1807        align: usize,
1808    ) -> *mut u8 {
1809        debug_assert!(old_size > 0);
1810        debug_assert!(new_size > 0);
1811        if let Ok(layout) = Layout::from_size_align(old_size, align) {
1812            let ptr = realloc(ptr, layout, new_size);
1813            if !ptr.is_null() {
1814                return ptr;
1815            }
1816        }
1817        malloc_failure();
1818    }
1819
1820    #[cold]
1821    fn malloc_failure() -> ! {
1822        cfg_if::cfg_if! {
1823            if #[cfg(debug_assertions)] {
1824                super::throw_str("invalid malloc request")
1825            } else if #[cfg(feature = "std")] {
1826                std::process::abort();
1827            } else if #[cfg(all(
1828                target_arch = "wasm32",
1829                target_os = "unknown"
1830            ))] {
1831                core::arch::wasm32::unreachable();
1832            } else {
1833                unreachable!()
1834            }
1835        }
1836    }
1837
1838    #[no_mangle]
1839    pub unsafe extern "C" fn __wbindgen_free(ptr: *mut u8, size: usize, align: usize) {
1840        // This happens for zero-length slices, and in that case `ptr` is
1841        // likely bogus so don't actually send this to the system allocator
1842        if size == 0 {
1843            return;
1844        }
1845        let layout = Layout::from_size_align_unchecked(size, align);
1846        dealloc(ptr, layout);
1847    }
1848
1849    /// This is a curious function necessary to get wasm-bindgen working today,
1850    /// and it's a bit of an unfortunate hack.
1851    ///
1852    /// The general problem is that somehow we need the above two symbols to
1853    /// exist in the final output binary (__wbindgen_malloc and
1854    /// __wbindgen_free). These symbols may be called by JS for various
1855    /// bindings, so we for sure need to make sure they're exported.
1856    ///
1857    /// The problem arises, though, when what if no Rust code uses the symbols?
1858    /// For all intents and purposes it looks to LLVM and the linker like the
1859    /// above two symbols are dead code, so they're completely discarded!
1860    ///
1861    /// Specifically what happens is this:
1862    ///
1863    /// * The above two symbols are generated into some object file inside of
1864    ///   libwasm_bindgen.rlib
1865    /// * The linker, LLD, will not load this object file unless *some* symbol
1866    ///   is loaded from the object. In this case, if the Rust code never calls
1867    ///   __wbindgen_malloc or __wbindgen_free then the symbols never get linked
1868    ///   in.
1869    /// * Later when `wasm-bindgen` attempts to use the symbols they don't
1870    ///   exist, causing an error.
1871    ///
1872    /// This function is a weird hack for this problem. We inject a call to this
1873    /// function in all generated code. Usage of this function should then
1874    /// ensure that the above two intrinsics are translated.
1875    ///
1876    /// Due to how rustc creates object files this function (and anything inside
1877    /// it) will be placed into the same object file as the two intrinsics
1878    /// above. That means if this function is called and referenced we'll pull
1879    /// in the object file and link the intrinsics.
1880    ///
1881    /// Ideas for how to improve this are most welcome!
1882    #[cfg_attr(wasm_bindgen_unstable_test_coverage, coverage(off))]
1883    pub fn link_mem_intrinsics() {
1884        crate::link::link_intrinsics();
1885    }
1886
1887    if_std! {
1888        std::thread_local! {
1889            static GLOBAL_EXNDATA: Cell<[u32; 2]> = Cell::new([0; 2]);
1890        }
1891
1892        #[no_mangle]
1893        pub unsafe extern "C" fn __wbindgen_exn_store(idx: u32) {
1894            GLOBAL_EXNDATA.with(|data| {
1895                debug_assert_eq!(data.get()[0], 0);
1896                data.set([1, idx]);
1897            });
1898        }
1899
1900        pub fn take_last_exception() -> Result<(), super::JsValue> {
1901            GLOBAL_EXNDATA.with(|data| {
1902                let ret = if data.get()[0] == 1 {
1903                    Err(super::JsValue::_new(data.get()[1]))
1904                } else {
1905                    Ok(())
1906                };
1907                data.set([0, 0]);
1908                ret
1909            })
1910        }
1911    }
1912
1913    /// An internal helper trait for usage in `#[wasm_bindgen]` on `async`
1914    /// functions to convert the return value of the function to
1915    /// `Result<JsValue, JsValue>` which is what we'll return to JS (where an
1916    /// error is a failed future).
1917    pub trait IntoJsResult {
1918        fn into_js_result(self) -> Result<JsValue, JsValue>;
1919    }
1920
1921    impl IntoJsResult for () {
1922        fn into_js_result(self) -> Result<JsValue, JsValue> {
1923            Ok(JsValue::undefined())
1924        }
1925    }
1926
1927    impl<T: Into<JsValue>> IntoJsResult for T {
1928        fn into_js_result(self) -> Result<JsValue, JsValue> {
1929            Ok(self.into())
1930        }
1931    }
1932
1933    impl<T: Into<JsValue>, E: Into<JsValue>> IntoJsResult for Result<T, E> {
1934        fn into_js_result(self) -> Result<JsValue, JsValue> {
1935            match self {
1936                Ok(e) => Ok(e.into()),
1937                Err(e) => Err(e.into()),
1938            }
1939        }
1940    }
1941
1942    impl<E: Into<JsValue>> IntoJsResult for Result<(), E> {
1943        fn into_js_result(self) -> Result<JsValue, JsValue> {
1944            match self {
1945                Ok(()) => Ok(JsValue::undefined()),
1946                Err(e) => Err(e.into()),
1947            }
1948        }
1949    }
1950
1951    /// An internal helper trait for usage in `#[wasm_bindgen(start)]`
1952    /// functions to throw the error (if it is `Err`).
1953    pub trait Start {
1954        fn start(self);
1955    }
1956
1957    impl Start for () {
1958        #[inline]
1959        fn start(self) {}
1960    }
1961
1962    impl<E: Into<JsValue>> Start for Result<(), E> {
1963        #[inline]
1964        fn start(self) {
1965            if let Err(e) = self {
1966                crate::throw_val(e.into());
1967            }
1968        }
1969    }
1970
1971    /// An internal helper struct for usage in `#[wasm_bindgen(main)]`
1972    /// functions to throw the error (if it is `Err`).
1973    pub struct MainWrapper<T>(pub Option<T>);
1974
1975    pub trait Main {
1976        fn __wasm_bindgen_main(&mut self);
1977    }
1978
1979    impl Main for &mut &mut MainWrapper<()> {
1980        #[inline]
1981        fn __wasm_bindgen_main(&mut self) {}
1982    }
1983
1984    impl Main for &mut &mut MainWrapper<Infallible> {
1985        #[inline]
1986        fn __wasm_bindgen_main(&mut self) {}
1987    }
1988
1989    impl<E: Into<JsValue>> Main for &mut &mut MainWrapper<Result<(), E>> {
1990        #[inline]
1991        fn __wasm_bindgen_main(&mut self) {
1992            if let Err(e) = self.0.take().unwrap() {
1993                crate::throw_val(e.into());
1994            }
1995        }
1996    }
1997
1998    impl<E: core::fmt::Debug> Main for &mut MainWrapper<Result<(), E>> {
1999        #[inline]
2000        fn __wasm_bindgen_main(&mut self) {
2001            if let Err(e) = self.0.take().unwrap() {
2002                crate::throw_str(&alloc::format!("{:?}", e));
2003            }
2004        }
2005    }
2006
2007    pub const fn flat_len<T, const SIZE: usize>(slices: [&[T]; SIZE]) -> usize {
2008        let mut len = 0;
2009        let mut i = 0;
2010        while i < slices.len() {
2011            len += slices[i].len();
2012            i += 1;
2013        }
2014        len
2015    }
2016
2017    pub const fn flat_byte_slices<const RESULT_LEN: usize, const SIZE: usize>(
2018        slices: [&[u8]; SIZE],
2019    ) -> [u8; RESULT_LEN] {
2020        let mut result = [0; RESULT_LEN];
2021
2022        let mut slice_index = 0;
2023        let mut result_offset = 0;
2024
2025        while slice_index < slices.len() {
2026            let mut i = 0;
2027            let slice = slices[slice_index];
2028            while i < slice.len() {
2029                result[result_offset] = slice[i];
2030                i += 1;
2031                result_offset += 1;
2032            }
2033            slice_index += 1;
2034        }
2035
2036        result
2037    }
2038
2039    // NOTE: This method is used to encode u32 into a variable-length-integer during the compile-time .
2040    // Generally speaking, the length of the encoded variable-length-integer depends on the size of the integer
2041    // but the maximum capacity can be used here to simplify the amount of code during the compile-time .
2042    pub const fn encode_u32_to_fixed_len_bytes(value: u32) -> [u8; 5] {
2043        let mut result: [u8; 5] = [0; 5];
2044        let mut i = 0;
2045        while i < 4 {
2046            result[i] = ((value >> (7 * i)) | 0x80) as u8;
2047            i += 1;
2048        }
2049        result[4] = (value >> (7 * 4)) as u8;
2050        result
2051    }
2052
2053    /// Trait for element types to implement `Into<JsValue>` for vectors of
2054    /// themselves, which isn't possible directly thanks to the orphan rule.
2055    pub trait VectorIntoJsValue: Sized {
2056        fn vector_into_jsvalue(vector: Box<[Self]>) -> JsValue;
2057    }
2058
2059    impl<T: VectorIntoJsValue> From<Box<[T]>> for JsValue {
2060        fn from(vector: Box<[T]>) -> Self {
2061            T::vector_into_jsvalue(vector)
2062        }
2063    }
2064
2065    pub fn js_value_vector_into_jsvalue<T: Into<JsValue>>(vector: Box<[T]>) -> JsValue {
2066        let result = unsafe { JsValue::_new(super::__wbindgen_array_new()) };
2067        for value in vector.into_vec() {
2068            let js: JsValue = value.into();
2069            unsafe { super::__wbindgen_array_push(result.idx, js.idx) }
2070            // `__wbindgen_array_push` takes ownership over `js` and has already dropped it,
2071            // so don't drop it again.
2072            mem::forget(js);
2073        }
2074        result
2075    }
2076}
2077
2078/// A wrapper type around slices and vectors for binding the `Uint8ClampedArray`
2079/// array in JS.
2080///
2081/// If you need to invoke a JS API which must take `Uint8ClampedArray` array,
2082/// then you can define it as taking one of these types:
2083///
2084/// * `Clamped<&[u8]>`
2085/// * `Clamped<&mut [u8]>`
2086/// * `Clamped<Vec<u8>>`
2087///
2088/// All of these types will show up as `Uint8ClampedArray` in JS and will have
2089/// different forms of ownership in Rust.
2090#[derive(Copy, Clone, PartialEq, Debug, Eq)]
2091pub struct Clamped<T>(pub T);
2092
2093impl<T> Deref for Clamped<T> {
2094    type Target = T;
2095
2096    fn deref(&self) -> &T {
2097        &self.0
2098    }
2099}
2100
2101impl<T> DerefMut for Clamped<T> {
2102    fn deref_mut(&mut self) -> &mut T {
2103        &mut self.0
2104    }
2105}
2106
2107/// Convenience type for use on exported `fn() -> Result<T, JsError>` functions, where you wish to
2108/// throw a JavaScript `Error` object.
2109///
2110/// You can get wasm_bindgen to throw basic errors by simply returning
2111/// `Err(JsError::new("message"))` from such a function.
2112///
2113/// For more complex error handling, `JsError` implements `From<T> where T: std::error::Error` by
2114/// converting it to a string, so you can use it with `?`. Many Rust error types already do this,
2115/// and you can use [`thiserror`](https://crates.io/crates/thiserror) to derive Display
2116/// implementations easily or use any number of boxed error types that implement it already.
2117///
2118///
2119/// To allow JavaScript code to catch only your errors, you may wish to add a subclass of `Error`
2120/// in a JS module, and then implement `Into<JsValue>` directly on a type and instantiate that
2121/// subclass. In that case, you would not need `JsError` at all.
2122///
2123/// ### Basic example
2124///
2125/// ```rust,no_run
2126/// use wasm_bindgen::prelude::*;
2127///
2128/// #[wasm_bindgen]
2129/// pub fn throwing_function() -> Result<(), JsError> {
2130///     Err(JsError::new("message"))
2131/// }
2132/// ```
2133///
2134/// ### Complex Example
2135///
2136/// ```rust,no_run
2137/// use wasm_bindgen::prelude::*;
2138///
2139/// #[derive(Debug, Clone)]
2140/// enum MyErrorType {
2141///     SomeError,
2142/// }
2143///
2144/// use core::fmt;
2145/// impl std::error::Error for MyErrorType {}
2146/// impl fmt::Display for MyErrorType {
2147///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2148///         write!(f, "display implementation becomes the error message")
2149///     }
2150/// }
2151///
2152/// fn internal_api() -> Result<(), MyErrorType> {
2153///     Err(MyErrorType::SomeError)
2154/// }
2155///
2156/// #[wasm_bindgen]
2157/// pub fn throwing_function() -> Result<(), JsError> {
2158///     internal_api()?;
2159///     Ok(())
2160/// }
2161///
2162/// ```
2163#[derive(Clone)]
2164pub struct JsError {
2165    value: JsValue,
2166}
2167
2168impl JsError {
2169    /// Construct a JavaScript `Error` object with a string message
2170    #[inline]
2171    pub fn new(s: &str) -> JsError {
2172        Self {
2173            value: unsafe { JsValue::_new(crate::__wbindgen_error_new(s.as_ptr(), s.len())) },
2174        }
2175    }
2176}
2177
2178if_std! {
2179    impl<E> From<E> for JsError
2180    where
2181        E: std::error::Error,
2182    {
2183        fn from(error: E) -> Self {
2184            JsError::new(&error.to_string())
2185        }
2186    }
2187}
2188
2189impl From<JsError> for JsValue {
2190    fn from(error: JsError) -> Self {
2191        error.value
2192    }
2193}
2194
2195macro_rules! typed_arrays {
2196        ($($ty:ident $ctor:ident $clamped_ctor:ident,)*) => {
2197            $(
2198                impl From<Box<[$ty]>> for JsValue {
2199                    fn from(mut vector: Box<[$ty]>) -> Self {
2200                        let result = unsafe { JsValue::_new($ctor(vector.as_mut_ptr(), vector.len())) };
2201                        mem::forget(vector);
2202                        result
2203                    }
2204                }
2205
2206                impl From<Clamped<Box<[$ty]>>> for JsValue {
2207                    fn from(mut vector: Clamped<Box<[$ty]>>) -> Self {
2208                        let result = unsafe { JsValue::_new($clamped_ctor(vector.as_mut_ptr(), vector.len())) };
2209                        mem::forget(vector);
2210                        result
2211                    }
2212                }
2213            )*
2214        };
2215    }
2216
2217typed_arrays! {
2218    u8 __wbindgen_uint8_array_new __wbindgen_uint8_clamped_array_new,
2219    u16 __wbindgen_uint16_array_new __wbindgen_uint16_array_new,
2220    u32 __wbindgen_uint32_array_new __wbindgen_uint32_array_new,
2221    u64 __wbindgen_biguint64_array_new __wbindgen_biguint64_array_new,
2222    i8 __wbindgen_int8_array_new __wbindgen_int8_array_new,
2223    i16 __wbindgen_int16_array_new __wbindgen_int16_array_new,
2224    i32 __wbindgen_int32_array_new __wbindgen_int32_array_new,
2225    i64 __wbindgen_bigint64_array_new __wbindgen_bigint64_array_new,
2226    f32 __wbindgen_float32_array_new __wbindgen_float32_array_new,
2227    f64 __wbindgen_float64_array_new __wbindgen_float64_array_new,
2228}
2229
2230impl __rt::VectorIntoJsValue for JsValue {
2231    fn vector_into_jsvalue(vector: Box<[JsValue]>) -> JsValue {
2232        __rt::js_value_vector_into_jsvalue::<JsValue>(vector)
2233    }
2234}
2235
2236impl<T: JsObject> __rt::VectorIntoJsValue for T {
2237    fn vector_into_jsvalue(vector: Box<[T]>) -> JsValue {
2238        __rt::js_value_vector_into_jsvalue::<T>(vector)
2239    }
2240}
2241
2242impl __rt::VectorIntoJsValue for String {
2243    fn vector_into_jsvalue(vector: Box<[String]>) -> JsValue {
2244        __rt::js_value_vector_into_jsvalue::<String>(vector)
2245    }
2246}
2247
2248impl<T> From<Vec<T>> for JsValue
2249where
2250    JsValue: From<Box<[T]>>,
2251{
2252    fn from(vector: Vec<T>) -> Self {
2253        JsValue::from(vector.into_boxed_slice())
2254    }
2255}
2256
2257impl<T> From<Clamped<Vec<T>>> for JsValue
2258where
2259    JsValue: From<Clamped<Box<[T]>>>,
2260{
2261    fn from(vector: Clamped<Vec<T>>) -> Self {
2262        JsValue::from(Clamped(vector.0.into_boxed_slice()))
2263    }
2264}