wasm-bindgen 0.2.118

Easy support for interacting between JS and Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
//! Support for closures in `wasm-bindgen`
//!
//! This module defines the [`ScopedClosure`] type which is used to pass Rust closures
//! to JavaScript. All closures are unwind safe by default: panics are caught and converted to
//! JavaScript exceptions when built with `panic=unwind`.
//!
//! # Immutable by Default
//!
//! The closure API defaults to **immutable** (`Fn`) closures because they are more
//! likely to satisfy `UnwindSafe` automatically:
//!
//! - `&T` where `T: RefUnwindSafe` is `UnwindSafe`
//! - `&mut T` is **never** `UnwindSafe` regardless of `T`
//!
//! This means:
//! - [`ScopedClosure::borrow`] creates an immutable `Fn` closure
//! - [`ScopedClosure::borrow_mut`] creates a mutable `FnMut` closure
//!
//! Immutable closures can be upcasted to mutable closures using [`upcast_ref`](crate::Upcast::upcast_ref).
//!
//! # Type Aliases
//!
//! - [`ScopedClosure<'a, T>`] — The unified closure type with a lifetime parameter
//! - [`Closure<T>`] — Alias for `ScopedClosure<'static, T>` (for backwards compatibility)
//!
//! # Unwind Safety
//!
//! For immediate/synchronous callbacks, use `&dyn FnMut` / `&dyn Fn`, when you are
//! **absolutely sure** the code will support unwind safety.
//!
//! For [`ScopedClosure`], the default constructors (`borrow`, `borrow_mut`, `own`) catch
//! panics, while the `_aborting` variants (`borrow_aborting`, `borrow_mut_aborting`, etc.) do not.
//!
//! # Ownership Model
//!
//! `ScopedClosure` follows the same ownership model as other wasm-bindgen types:
//! the JavaScript reference remains valid until the Rust value is dropped. When
//! dropped, the closure is invalidated and any subsequent calls from JavaScript
//! will throw an exception.
//!
//! For borrowed closures created with `borrow`/`borrow_mut`, Rust's borrow checker
//! ensures the `ScopedClosure` cannot outlive the closure's captured data.
//!
//! See the [`ScopedClosure`] type documentation for detailed examples.

#![allow(clippy::fn_to_numeric_cast)]
use alloc::boxed::Box;
use alloc::string::String;
use core::fmt;
use core::mem::{self, ManuallyDrop};

use crate::__rt::marker::ErasableGeneric;
use crate::__rt::marker::MaybeUnwindSafe;
use crate::describe::*;
use crate::JsValue;
use crate::{convert::*, JsCast};
use core::marker::PhantomData;
use core::panic::AssertUnwindSafe;

#[wasm_bindgen_macro::wasm_bindgen(wasm_bindgen = crate)]
extern "C" {
    type JsClosure;

    #[wasm_bindgen(method)]
    fn _wbg_cb_unref(js: &JsClosure);
}

/// A closure with a lifetime parameter that represents a Rust closure passed to JavaScript.
///
/// `ScopedClosure<'a, T>` is the unified closure type. The lifetime `'a` indicates
/// how long the closure is valid:
///
/// - **`ScopedClosure<'static, T>`** - An owned closure with heap-allocated data. Requires
///   `'static` captures. Use for long-lived closures like event listeners and timers.
///   Created with [`Closure::new`] or [`ScopedClosure::own`]. May transfer ownership to the
///   JS GC using finalizers.
///
/// - **`ScopedClosure<'a, T>`** (non-`'static`) - A borrowed closure referencing stack data.
///   Allows non-`'static` captures. Use for immediate/synchronous callbacks. Created with
///   [`ScopedClosure::borrow`] (for `FnMut`) or [`ScopedClosure::borrow_immutable`] (for `Fn`).
///   Cannot transfer ownership to JS GC.
///
/// [`Closure<T>`] is currently a type alias for `ScopedClosure<'static, T>`. In
/// a future release, a lifetime argument will be added to this alias.
///
/// # Ownership Model
///
/// `ScopedClosure` follows the same ownership model as other wasm-bindgen types:
/// the JavaScript reference remains valid until the Rust value is dropped. When
/// dropped, the closure is invalidated and any subsequent calls from JavaScript
/// will throw: "closure invoked recursively or after being dropped".
///
/// For `'static` closures, you can also:
/// - Pass by value to transfer ownership to JS (implements [`IntoWasmAbi`])
/// - Call [`forget()`](Self::forget) to leak the closure (JS can use it indefinitely)
/// - Call [`into_js_value()`](Self::into_js_value) to transfer to JS GC management
///
/// # Lifetime Safety
///
/// For borrowed closures, Rust's borrow checker ensures that `ScopedClosure` cannot
/// be held longer than the closure's captured data:
///
/// ```ignore
/// let mut sum = 0;
/// let mut f = |x: u32| { sum += x; };  // f borrows sum
/// let closure = ScopedClosure::borrow(&mut f);  // closure borrows f
/// // closure cannot outlive f, and f cannot outlive sum
/// ```
///
/// # Examples
///
/// ## Borrowed closures with `ScopedClosure::borrow`
///
/// Use for immediate/synchronous callbacks where JS calls the closure right away:
///
/// ```ignore
/// use wasm_bindgen::prelude::*;
///
/// #[wasm_bindgen]
/// extern "C" {
///     fn call_immediately(cb: &ScopedClosure<dyn FnMut(u32)>);
/// }
///
/// let mut sum = 0;
/// {
///     let mut f = |x: u32| { sum += x; };
///     let closure = ScopedClosure::borrow(&mut f);
///     call_immediately(&closure);
/// }  // closure dropped here, JS function invalidated
/// assert_eq!(sum, 42);
/// ```
///
/// ## Owned closures with `Closure::new`
///
/// Use for long-lived callbacks like event listeners and timers:
///
/// ```ignore
/// use wasm_bindgen::prelude::*;
///
/// #[wasm_bindgen]
/// extern "C" {
///     fn setInterval(closure: &Closure<dyn FnMut()>, time: u32) -> i32;
/// }
///
/// // Closure::new requires 'static, so use `move` to capture by value
/// let cb = Closure::new(move || {
///     // ...
/// });
/// setInterval(&cb, 1000);
/// // Must keep `cb` alive or call `cb.forget()` to transfer to JS
/// ```
///
/// ## Transferring ownership to JS
///
/// Pass a `ScopedClosure<'static, T>` by value to transfer ownership:
///
/// ```ignore
/// use wasm_bindgen::prelude::*;
///
/// #[wasm_bindgen]
/// extern "C" {
///     fn set_one_shot_callback(cb: ScopedClosure<dyn FnMut()>);
/// }
///
/// let cb = ScopedClosure::own(|| { /* ... */ });
/// set_one_shot_callback(cb);  // Ownership transferred, no need to store
/// ```
pub struct ScopedClosure<'a, T: ?Sized> {
    js: JsClosure,
    // careful: must be Box<T> not just T because unsized PhantomData
    // seems to have weird interaction with Pin<>
    _marker: PhantomData<Box<T>>,
    _lifetime: PhantomData<&'a ()>,
}

/// Alias for [`ScopedClosure<'static, T>`] for backwards compatibility.
///
/// In a future major version, `Closure` will become `ScopedClosure<'a, T>` with a
/// lifetime parameter.
pub type Closure<T> = ScopedClosure<'static, T>;

// ScopedClosure is Unpin because it only contains a JsValue (which is just a u32)
// and PhantomData markers. The closure data is either on the heap (owned) or
// referenced through a raw pointer (borrowed), neither of which is stored inline.
impl<T: ?Sized> Unpin for ScopedClosure<'_, T> {}

fn _assert_compiles<T>(pin: core::pin::Pin<&mut ScopedClosure<'static, T>>) {
    let _ = &mut *pin.get_mut();
}

impl<T: ?Sized> Drop for ScopedClosure<'_, T> {
    fn drop(&mut self) {
        // Invalidate the closure on the JS side.
        //
        // The JS bindings distinguish owned vs borrowed closures via the `dtor_idx`
        // encoded in `WasmDescribe`: owned closures pass a non-zero destructor
        // function pointer, borrowed closures pass `0`.
        //
        // For owned closures (`Closure::new`/`ScopedClosure::own`), this decreases
        // the refcount and frees the Rust heap data when the count reaches zero.
        //
        // For borrowed closures (`ScopedClosure::borrow`/`borrow_mut`), this sets
        // state.a = state.b = 0 to prevent any further calls to the closure.
        self.js._wbg_cb_unref();
    }
}

impl<'a, T> ScopedClosure<'a, T>
where
    T: ?Sized + WasmClosure,
{
    /// Obtain a `&JsValue` reference for this closure
    pub fn as_js_value(&self) -> &JsValue {
        self.js.unchecked_ref()
    }
}

/// Methods for creating and managing `'static` closures.
///
/// These methods are only available on `ScopedClosure<'static, T>`
/// not on borrowed `ScopedClosure<'a, T>` where `'a` is not `'static`.
impl<T> ScopedClosure<'static, T>
where
    T: ?Sized + WasmClosure,
{
    /// Alias for [`Closure::own`].
    ///
    /// Creates a new static owned `ScopedClosure<'static, T>` from the provided
    /// Rust function, with panic unwind support.
    ///
    /// The type parameter `T` determines whether the closure is `Fn` or `FnMut`.
    ///
    /// Supports unwind via its UnwindSafe bound when building with panic=unwind.
    /// Alternatively, pass `Closure::own(AssertUnwindSafe(...))` to assert unwind
    /// safety, or use [`own_assert_unwind_safe`](Self::own_assert_unwind_safe) or
    /// [`own_aborting`](Self::own_aborting).
    ///
    /// When provided to a JS function as an own value, to be managed by the JS GC.
    ///
    /// See [`borrow`](Self::borrow) for creating a borrowed `ScopedClosure` with
    /// an associated lifetime (defaults to immutable `Fn`).
    pub fn new<F>(t: F) -> Self
    where
        F: IntoWasmClosure<T> + MaybeUnwindSafe + 'static,
    {
        Self::own(t)
    }

    /// Creates a new static owned `ScopedClosure<'static, T>` from the provided
    /// Rust function, with panic unwind support.
    ///
    /// The type parameter `T` determines whether the closure is `Fn` or `FnMut`.
    ///
    /// Supports unwind via its UnwindSafe bound when building with panic=unwind.
    /// Alternatively, pass `Closure::own(AssertUnwindSafe(...))` to assert unwind
    /// safety, or use [`own_assert_unwind_safe`](Self::own_assert_unwind_safe) or
    /// [`own_aborting`](Self::own_aborting).
    ///
    /// When provided to a JS function as an own value, to be managed by the JS GC.
    ///
    /// See [`borrow`](Self::borrow) for creating a borrowed `ScopedClosure` with
    /// an associated lifetime (defaults to immutable `Fn`).
    pub fn own<F>(t: F) -> Self
    where
        F: IntoWasmClosure<T> + MaybeUnwindSafe + 'static,
    {
        Self::wrap_maybe_aborting::<true>(Box::new(t))
    }

    /// Creates a new owned `'static` closure that aborts on panic.
    ///
    /// Unlike [`own`](Self::own), this version does NOT catch panics and does NOT
    /// require `UnwindSafe`. If the closure panics, the process will abort.
    ///
    /// The type parameter `T` determines whether the closure is `Fn` or `FnMut`.
    ///
    /// When provided to a JS function as an own value, to be managed by the JS GC.
    ///
    /// See [`borrow_aborting`](Self::borrow_aborting) for creating a borrowed
    /// `ScopedClosure` with an associated lifetime.
    ///
    /// **Note: Not unwind safe. Prefer [`own`](Self::own) or `own` with
    /// [`AssertUnwindSafe`](core::panic::AssertUnwindSafe) when possible.**
    pub fn own_aborting<F>(t: F) -> Self
    where
        F: IntoWasmClosure<T> + 'static,
    {
        Self::wrap_maybe_aborting::<false>(Box::new(t))
    }

    /// Creates a new static owned `ScopedClosure<'static, T>` from the provided
    /// Rust function, with panic unwind support.
    ///
    /// The type parameter `T` determines whether the closure is `Fn` or `FnMut`.
    ///
    /// When provided to a JS function as an own value, to be managed by the JS GC.
    ///
    /// **Safety: Unwind safety is assumed when using this function, like using
    /// `AssertUnwindSafe(...)`, this must be verified explicitly.**
    ///
    /// See [`borrow_aborting`](Self::borrow_aborting) for creating a borrowed
    /// `ScopedClosure` with an associated lifetime.
    pub fn own_assert_unwind_safe<F>(t: F) -> Self
    where
        F: IntoWasmClosure<T> + 'static,
    {
        Self::wrap_maybe_aborting::<true>(Box::new(t))
    }

    /// A more direct version of `Closure::new` which creates a `Closure` from
    /// a `Box<dyn Fn>`/`Box<dyn FnMut>`, which is how it's kept internally.
    ///
    /// Supports unwind via its UnwindSafe bound when building with panic=unwind.
    /// Alternatively, use [`wrap_assert_unwind_safe`](Self::wrap_assert_unwind_safe)
    /// to assert unwind safety, or use [`wrap_aborting`](Self::wrap_aborting).
    ///
    pub fn wrap<F>(data: Box<F>) -> Self
    where
        F: IntoWasmClosure<T> + ?Sized + MaybeUnwindSafe,
    {
        Self::wrap_maybe_aborting::<true>(data)
    }

    /// A more direct version of `Closure::new` which creates a `Closure` from
    /// a `Box<dyn Fn>`/`Box<dyn FnMut>`, which is how it's kept internally.
    ///
    /// This version aborts on panics.
    pub fn wrap_aborting<F>(data: Box<F>) -> Self
    where
        F: IntoWasmClosure<T> + ?Sized,
    {
        Self::wrap_maybe_aborting::<false>(data)
    }

    /// A more direct version of `Closure::new` which creates a `Closure` from
    /// a `Box<dyn Fn>`/`Box<dyn FnMut>`, which is how it's kept internally.
    ///
    /// **Safety: Unwind safety is assumed when using this function, like using
    /// `AssertUnwindSafe(...)`, this must be verified explicitly.**
    ///
    /// This version catches panics when unwinding is available.
    pub fn wrap_assert_unwind_safe<F>(data: Box<F>) -> Self
    where
        F: IntoWasmClosure<T> + ?Sized,
    {
        Self::wrap_maybe_aborting::<true>(data)
    }

    fn wrap_maybe_aborting<const UNWIND_SAFE: bool>(
        data: Box<impl IntoWasmClosure<T> + ?Sized>,
    ) -> Self {
        Self {
            js: crate::__rt::wbg_cast(OwnedClosure::<T, UNWIND_SAFE>(data.unsize())),
            _marker: PhantomData,
            _lifetime: PhantomData,
        }
    }

    /// Creates a scoped closure by borrowing an immutable `Fn` closure with
    /// panic unwind support.
    ///
    /// This is the recommended way to pass closures to JavaScript for immediate/
    /// synchronous use. Unlike [`Closure::own`], this does not require the closure
    /// to be `'static`, allowing you to capture references to local variables.
    ///
    /// Use [`borrow_mut`](Self::borrow_mut) when you need to mutate captured state.
    ///
    /// The returned `ScopedClosure<'a, _>` has lifetime `'a` from the closure
    /// reference, which means it cannot outlive the closure or any data the
    /// closure captures.
    ///
    /// Supports unwind via its UnwindSafe bound when building with panic=unwind.
    /// Wrap with `AssertUnwindSafe` if necessary to achieve this bound, or
    /// use [`borrow_assert_unwind_safe`](Self::borrow_assert_unwind_safe) or
    /// [`borrow_aborting`](Self::borrow_aborting) for non-unwind-safe functions.
    ///
    /// The resulting closure can be upcasted to `FnMut` using [`upcast_ref`](crate::Upcast::upcast_ref).
    ///
    /// # When to use scoped closures
    ///
    /// Use `ScopedClosure::borrow` or `ScopedClosure::borrow_mut` when:
    /// - JavaScript will call the closure immediately and not retain it
    /// - You need to capture non-`'static` references
    /// - You want automatic cleanup when the `ScopedClosure` is dropped
    ///
    /// # Closure lifetime
    ///
    /// The JavaScript function is only valid while the `ScopedClosure` exists.
    /// Once dropped, the JavaScript function is invalidated. If JavaScript retains
    /// a reference and calls it later, it will throw: "closure invoked recursively
    /// or after being dropped".
    ///
    /// Rust's borrow checker ensures `ScopedClosure` cannot outlive the closure's
    /// captured data, preventing use-after-free bugs.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use wasm_bindgen::prelude::*;
    ///
    /// #[wasm_bindgen]
    /// extern "C" {
    ///     fn call_with_value(cb: &ScopedClosure<dyn Fn(u32)>, value: u32);
    ///     fn call_fnmut(cb: &ScopedClosure<dyn FnMut(u32)>, value: u32);
    /// }
    ///
    /// let data = vec![1, 2, 3];
    /// let f = |x| {
    ///     println!("data len: {}, x: {}", data.len(), x);
    /// };
    /// let closure = ScopedClosure::borrow(&f);
    /// call_with_value(&closure, 42);
    /// // Can also upcast to FnMut
    /// call_fnmut(closure.upcast_ref(), 42);
    /// ```
    pub fn borrow<'a, F>(t: &'a F) -> ScopedClosure<'a, T::Static>
    where
        F: IntoWasmClosureRef<T> + MaybeUnwindSafe + ?Sized,
    {
        Self::borrow_assert_unwind_safe(t)
    }

    /// Like [`borrow`](Self::borrow), but does not catch panics.
    ///
    /// If the closure panics, the process will abort. This variant does not
    /// require `UnwindSafe`.
    ///
    /// **Note: Not unwind safe. Prefer [`borrow`](Self::borrow) or
    /// [`borrow_assert_unwind_safe`](Self::borrow_assert_unwind_safe) when possible.**
    pub fn borrow_aborting<'a, F>(t: &'a F) -> ScopedClosure<'a, T::Static>
    where
        F: IntoWasmClosureRef<T> + ?Sized,
    {
        Self::wrap_borrow::<_, false>(t)
    }

    /// Like [`borrow`](Self::borrow), but catches panics without requiring `MaybeUnwindSafe`.
    ///
    /// **Safety: Unwind safety is assumed when using this function, like using
    /// `AssertUnwindSafe(...)`, this must be verified explicitly.**
    pub fn borrow_assert_unwind_safe<'a, F>(t: &'a F) -> ScopedClosure<'a, T::Static>
    where
        F: IntoWasmClosureRef<T> + ?Sized,
    {
        Self::wrap_borrow::<_, true>(t)
    }

    fn wrap_borrow<'a, F, const UNWIND_SAFE: bool>(t: &'a F) -> ScopedClosure<'a, T::Static>
    where
        F: IntoWasmClosureRef<T> + ?Sized,
    {
        let t: &T = t.unsize_closure_ref();
        let (ptr, len): (u32, u32) = unsafe { mem::transmute_copy(&t) };
        ScopedClosure {
            js: crate::__rt::wbg_cast(BorrowedClosure::<T, UNWIND_SAFE> {
                data: WasmSlice { ptr, len },
                _marker: PhantomData,
            }),
            _marker: PhantomData,
            _lifetime: PhantomData,
        }
    }

    /// Creates a scoped closure by mutably borrowing a `FnMut` closure.
    ///
    /// Use this for closures that need to mutate captured state. For closures that
    /// don't need mutation, prefer [`borrow`](Self::borrow) which creates an immutable
    /// `Fn` closure that is more likely to satisfy `UnwindSafe` automatically.
    ///
    /// Supports unwind via its UnwindSafe bound when building with panic=unwind.
    /// Wrap with `AssertUnwindSafe` if necessary to achieve this bound, or
    /// use [`borrow_mut_assert_unwind_safe`](Self::borrow_mut_assert_unwind_safe) or
    /// [`borrow_mut_aborting`](Self::borrow_mut_aborting) for non-unwind-safe functions.
    ///
    /// See [`borrow`](Self::borrow) for full documentation on scoped closures.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use wasm_bindgen::prelude::*;
    ///
    /// #[wasm_bindgen]
    /// extern "C" {
    ///     fn call_three_times(cb: &ScopedClosure<dyn FnMut(u32)>);
    /// }
    ///
    /// let mut sum = 0;
    /// let closure = ScopedClosure::borrow_mut(&mut |x: u32| {
    ///     sum += x;
    /// });
    /// call_three_times(&closure);
    /// // closure dropped, `sum` is accessible again
    /// assert_eq!(sum, 6); // 1 + 2 + 3
    /// ```
    pub fn borrow_mut<'a, F>(t: &'a mut F) -> ScopedClosure<'a, T::Static>
    where
        F: IntoWasmClosureRefMut<T> + MaybeUnwindSafe + ?Sized,
    {
        Self::borrow_mut_assert_unwind_safe(t)
    }

    /// Like [`borrow_mut`](Self::borrow_mut), but does not catch panics.
    ///
    /// If the closure panics, the process will abort. This variant does not
    /// require `UnwindSafe`.
    ///
    /// **Note: Not unwind safe. Prefer [`borrow_mut`](Self::borrow_mut) or
    /// [`borrow_mut_assert_unwind_safe`](Self::borrow_mut_assert_unwind_safe) when possible.**
    pub fn borrow_mut_aborting<'a, F>(t: &'a mut F) -> ScopedClosure<'a, T::Static>
    where
        F: IntoWasmClosureRefMut<T> + ?Sized,
    {
        Self::wrap_borrow_mut::<_, false>(t)
    }

    /// Like [`borrow_mut`](Self::borrow_mut), but catches panics without requiring `MaybeUnwindSafe`.
    ///
    /// **Safety: Unwind safety is assumed when using this function, like using
    /// `AssertUnwindSafe(...)`, this must be verified explicitly.**
    pub fn borrow_mut_assert_unwind_safe<'a, F>(t: &'a mut F) -> ScopedClosure<'a, T::Static>
    where
        F: IntoWasmClosureRefMut<T> + ?Sized,
    {
        Self::wrap_borrow_mut::<_, true>(t)
    }

    fn wrap_borrow_mut<'a, F, const UNWIND_SAFE: bool>(t: &'a mut F) -> ScopedClosure<'a, T::Static>
    where
        F: IntoWasmClosureRefMut<T> + ?Sized,
    {
        let t: &mut T = t.unsize_closure_ref();
        let (ptr, len): (u32, u32) = unsafe { mem::transmute_copy(&t) };
        ScopedClosure {
            js: crate::__rt::wbg_cast(BorrowedClosure::<T, UNWIND_SAFE> {
                data: WasmSlice { ptr, len },
                _marker: PhantomData,
            }),
            _marker: PhantomData,
            _lifetime: PhantomData,
        }
    }

    /// Release memory management of this closure from Rust to the JS GC.
    ///
    /// When a `Closure` is dropped it will release the Rust memory and
    /// invalidate the associated JS closure, but this isn't always desired.
    /// Some callbacks are alive for the entire duration of the program or for a
    /// lifetime dynamically managed by the JS GC. This function can be used
    /// to drop this `Closure` while keeping the associated JS function still
    /// valid.
    ///
    /// If the platform supports weak references, the Rust memory will be
    /// reclaimed when the JS closure is GC'd. If weak references is not
    /// supported, this can be dangerous if this function is called many times
    /// in an application because the memory leak will overwhelm the page
    /// quickly and crash the wasm.
    ///
    /// # Safety Note
    ///
    /// This method is only available on `'static` closures. Calling it on a
    /// borrowed `ScopedClosure` would be unsound because the closure data
    /// would become invalid when the borrow ends.
    pub fn into_js_value(self) -> JsValue {
        let idx = self.js.idx;
        mem::forget(self);
        JsValue::_new(idx)
    }

    /// Same as `mem::forget(self)`.
    ///
    /// This can be used to fully relinquish closure ownership to the JS.
    ///
    /// # Safety Note
    ///
    /// This method is only available on `'static` closures. Calling it on a borrowed
    /// `ScopedClosure` would be unsound because the closure data would become invalid
    /// when the borrow ends.
    pub fn forget(self) {
        mem::forget(self);
    }

    /// Create a `Closure` from a function that can only be called once.
    ///
    /// Since we have no way of enforcing that JS cannot attempt to call this
    /// `FnOne(A...) -> R` more than once, this produces a `Closure<dyn FnMut(A...)
    /// -> R>` that will dynamically throw a JavaScript error if called more
    /// than once.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use wasm_bindgen::prelude::*;
    ///
    /// // Create an non-`Copy`, owned `String`.
    /// let mut s = String::from("Hello");
    ///
    /// // Close over `s`. Since `f` returns `s`, it is `FnOnce` and can only be
    /// // called once. If it was called a second time, it wouldn't have any `s`
    /// // to work with anymore!
    /// let f = move || {
    ///     s += ", World!";
    ///     s
    /// };
    ///
    /// // Create a `Closure` from `f`. Note that the `Closure`'s type parameter
    /// // is `FnMut`, even though `f` is `FnOnce`.
    /// let closure: Closure<dyn FnMut() -> String> = Closure::once(f);
    /// ```
    ///
    /// Note: the `A` and `R` type parameters are here just for backward compat
    /// and will be removed in the future.
    pub fn once<F, A, R>(fn_once: F) -> Self
    where
        F: WasmClosureFnOnce<T, A, R> + MaybeUnwindSafe,
    {
        Closure::wrap_maybe_aborting::<true>(fn_once.into_fn_mut())
    }

    /// Create a `Closure` from a function that can only be called once.
    ///
    /// Unlike `once`, this version does NOT catch panics and does NOT require `UnwindSafe`.
    /// If the closure panics, the process will abort.
    ///
    /// Use this when:
    /// - Your closure captures types that aren't `UnwindSafe` (like `Rc<Cell<T>>`)
    /// - You don't need panic catching across the JS boundary
    /// - You prefer abort-on-panic behavior
    ///
    /// Since we have no way of enforcing that JS cannot attempt to call this
    /// `FnOnce(A...) -> R` more than once, this produces a `Closure<dyn FnMut(A...)
    /// -> R>` that will dynamically throw a JavaScript error if called more
    /// than once.
    ///
    /// **Note: Not unwind safe. Prefer [`once`](Self::once) or `once` with
    /// [`AssertUnwindSafe`](core::panic::AssertUnwindSafe) when possible.**
    ///
    /// Note: the `A` and `R` type parameters are here just for backward compat
    /// and will be removed in the future.
    pub fn once_aborting<F, A, R>(fn_once: F) -> Self
    where
        F: WasmClosureFnOnceAbort<T, A, R>,
    {
        Closure::wrap_maybe_aborting::<false>(fn_once.into_fn_mut())
    }

    /// Create a `Closure` from a function that can only be called once,
    /// with panic unwind support.
    ///
    /// **Safety: Unwind safety is assumed when using this function, like using
    /// `AssertUnwindSafe(...)`, this must be verified explicitly.**
    ///
    /// Use this when:
    /// - Your closure captures types that aren't `UnwindSafe` (like `Rc<Cell<T>>`)
    /// - You still want panics to be caught and converted to JS exceptions
    ///
    /// Since we have no way of enforcing that JS cannot attempt to call this
    /// `FnOnce(A...) -> R` more than once, this produces a `Closure<dyn FnMut(A...)
    /// -> R>` that will dynamically throw a JavaScript error if called more
    /// than once.
    ///
    /// Note: the `A` and `R` type parameters are here just for backward compat
    /// and will be removed in the future.
    pub fn once_assert_unwind_safe<F, A, R>(fn_once: F) -> Self
    where
        F: WasmClosureFnOnceAbort<T, A, R>,
    {
        Closure::wrap_maybe_aborting::<true>(fn_once.into_fn_mut())
    }

    // TODO: Update once closures to be generated on construction as once
    // closures instead of using wrap(). Then we can share the same into_js()
    // function between all closures, and deprecate this method.
    /// Convert a `FnOnce(A...) -> R` into a JavaScript `Function` object.
    ///
    /// If the JavaScript function is invoked more than once, it will throw an
    /// exception.
    ///
    /// Unlike `Closure::once`, this does *not* return a `Closure` that can be
    /// dropped before the function is invoked to deallocate the closure. The
    /// only way the `FnOnce` is deallocated is by calling the JavaScript
    /// function. If the JavaScript function is never called then the `FnOnce`
    /// and everything it closes over will leak.
    ///
    /// ```rust,ignore
    /// use wasm_bindgen::{prelude::*, JsCast};
    ///
    /// let f = Closure::once_into_js(move || {
    ///     // ...
    /// });
    ///
    /// assert!(f.is_instance_of::<js_sys::Function>());
    /// ```
    ///
    /// Note: the `A` and `R` type parameters are here just for backward compat
    /// and will be removed in the future.
    pub fn once_into_js<F, A, R>(fn_once: F) -> JsValue
    where
        F: WasmClosureFnOnce<T, A, R> + MaybeUnwindSafe,
    {
        fn_once.into_js_function()
    }
}

/// A trait for converting an `FnOnce(A...) -> R` into a `FnMut(A...) -> R` that
/// will throw if ever called more than once.
#[doc(hidden)]
pub trait WasmClosureFnOnce<FnMut: ?Sized, A, R>: 'static {
    fn into_fn_mut(self) -> Box<FnMut>;

    fn into_js_function(self) -> JsValue;
}

/// A trait for converting an `FnOnce(A...) -> R` into a `FnMut(A...) -> R` that
/// will throw if ever called more than once. This variant does not require UnwindSafe.
#[doc(hidden)]
pub trait WasmClosureFnOnceAbort<FnMut: ?Sized, A, R>: 'static {
    fn into_fn_mut(self) -> Box<FnMut>;

    fn into_js_function(self) -> JsValue;
}

impl<T: ?Sized> AsRef<JsValue> for ScopedClosure<'_, T> {
    fn as_ref(&self) -> &JsValue {
        &self.js
    }
}

/// Internal representation of an owned closure sent to JS.
/// `UNWIND_SAFE` selects the invoke shim: `true` catches panics, `false` does not.
#[repr(transparent)]
struct OwnedClosure<T: ?Sized, const UNWIND_SAFE: bool>(Box<T>);

/// Internal representation of a borrowed closure sent to JS.
/// `UNWIND_SAFE` selects the invoke shim: `true` catches panics, `false` does not.
struct BorrowedClosure<T: ?Sized, const UNWIND_SAFE: bool> {
    data: WasmSlice,
    _marker: PhantomData<T>,
}

/// Destroys an owned closure by reconstructing and dropping its
/// `Box<dyn Trait>` representation from the raw pointer data `(a, b)`.
///
/// # Safety
///
/// `(a, b)` must be a valid pair previously produced by `Box::into_raw` on a
/// `Box<dyn FnOnce/FnMut/Fn>` closure, or `a` must be zero (in which case this
/// is a no-op).
#[no_mangle]
pub unsafe extern "C" fn __wbindgen_destroy_closure(a: usize, b: usize) {
    if a == 0 {
        return;
    }

    // Usual way to erase any trait details, so we are just left with layout and
    // drop implementation that any dyn trait has.
    // See eg https://doc.rust-lang.org/beta/nightly-rustc/rustc_lint/traits/static.DYN_DROP.html#explanation
    //
    // This allows to use `destroy` in a non-generic way for any closures.
    trait ErasedPlaceholderForDrop {}

    drop(mem::transmute_copy::<_, Box<dyn ErasedPlaceholderForDrop>>(
        &(a, b),
    ));
}

impl<T, const UNWIND_SAFE: bool> WasmDescribe for OwnedClosure<T, UNWIND_SAFE>
where
    T: WasmClosure + ?Sized,
{
    #[cfg_attr(wasm_bindgen_unstable_test_coverage, coverage(off))]
    fn describe() {
        inform(CLOSURE);
        inform(1);
        inform(T::IS_MUT as u32);
        T::describe_invoke::<UNWIND_SAFE>();
    }
}

impl<T, const UNWIND_SAFE: bool> WasmDescribe for BorrowedClosure<T, UNWIND_SAFE>
where
    T: WasmClosure + ?Sized,
{
    #[cfg_attr(wasm_bindgen_unstable_test_coverage, coverage(off))]
    fn describe() {
        inform(CLOSURE);
        inform(0);
        inform(T::IS_MUT as u32);
        T::describe_invoke::<UNWIND_SAFE>();
    }
}

impl<T, const UNWIND_SAFE: bool> IntoWasmAbi for OwnedClosure<T, UNWIND_SAFE>
where
    T: WasmClosure + ?Sized,
{
    type Abi = WasmSlice;

    fn into_abi(self) -> WasmSlice {
        let (a, b): (usize, usize) = unsafe { mem::transmute_copy(&ManuallyDrop::new(self)) };
        WasmSlice {
            ptr: a as u32,
            len: b as u32,
        }
    }
}

impl<T, const UNWIND_SAFE: bool> IntoWasmAbi for BorrowedClosure<T, UNWIND_SAFE>
where
    T: WasmClosure + ?Sized,
{
    type Abi = WasmSlice;
    fn into_abi(self) -> WasmSlice {
        self.data
    }
}

impl<T> WasmDescribe for ScopedClosure<'_, T>
where
    T: WasmClosure + ?Sized,
{
    #[cfg_attr(wasm_bindgen_unstable_test_coverage, coverage(off))]
    fn describe() {
        inform(EXTERNREF);
    }
}

// `ScopedClosure` can be passed by reference to imports (for any lifetime).
impl<T> IntoWasmAbi for &ScopedClosure<'_, T>
where
    T: WasmClosure + ?Sized,
{
    type Abi = u32;

    fn into_abi(self) -> u32 {
        (&self.js).into_abi()
    }
}

impl<T> OptionIntoWasmAbi for &ScopedClosure<'_, T>
where
    T: WasmClosure + ?Sized,
{
    fn none() -> Self::Abi {
        0
    }
}

/// `'static` closures can be passed by value to JS, transferring ownership.
///
/// This is useful for one-shot callbacks where you want JS to own the closure.
/// The closure will be cleaned up by JS GC (if weak references are supported)
/// or will leak (if weak references are not supported).
///
/// # Example
///
/// ```ignore
/// #[wasm_bindgen]
/// extern "C" {
///     fn set_one_shot_callback(cb: Closure<dyn FnMut()>);
/// }
///
/// let cb = Closure::new(|| { /* ... */ });
/// set_one_shot_callback(cb);  // Ownership transferred to JS
/// // No need to store or forget the closure
/// ```
impl<T> IntoWasmAbi for ScopedClosure<'static, T>
where
    T: WasmClosure + ?Sized,
{
    type Abi = u32;

    fn into_abi(self) -> u32 {
        let idx = self.js.idx;
        mem::forget(self);
        idx
    }
}

impl<T> OptionIntoWasmAbi for ScopedClosure<'static, T>
where
    T: WasmClosure + ?Sized,
{
    fn none() -> Self::Abi {
        0
    }
}

fn _check() {
    fn _assert<T: IntoWasmAbi>() {}
    // ScopedClosure by reference (any lifetime)
    _assert::<&ScopedClosure<dyn Fn()>>();
    _assert::<&ScopedClosure<dyn Fn(String)>>();
    _assert::<&ScopedClosure<dyn Fn() -> String>>();
    _assert::<&ScopedClosure<dyn FnMut()>>();
    _assert::<&ScopedClosure<dyn FnMut(String)>>();
    _assert::<&ScopedClosure<dyn FnMut() -> String>>();
    // ScopedClosure by value (only 'static)
    _assert::<ScopedClosure<'static, dyn Fn()>>();
    _assert::<ScopedClosure<'static, dyn FnMut()>>();
    _assert::<Closure<dyn Fn()>>();
    _assert::<Closure<dyn FnMut()>>();
}

impl<T> fmt::Debug for ScopedClosure<'_, T>
where
    T: ?Sized,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Closure {{ ... }}")
    }
}

/// An internal trait for the `Closure` type.
///
/// This trait is not stable and it's not recommended to use this in bounds or
/// implement yourself.
#[doc(hidden)]
pub unsafe trait WasmClosure: WasmDescribe {
    const IS_MUT: bool;
    /// The `'static` version of `Self`. For example, if `Self` is `dyn Fn() + 'a`,
    /// then `Static` is `dyn Fn()` (implicitly `'static`).
    type Static: ?Sized + WasmClosure;
    /// The mutable version of this closure type.
    /// For `dyn Fn(...) -> R` this is `dyn FnMut(...) -> R`.
    /// For `dyn FnMut(...) -> R` this is itself.
    type AsMut: ?Sized;
    /// Emit the FUNCTION descriptor with the invoke shim selected by
    /// `UNWIND_SAFE`: `true` picks the panic-catching shim, `false`
    /// picks the non-catching shim.
    fn describe_invoke<const UNWIND_SAFE: bool>();
}

unsafe impl<T: WasmClosure> WasmClosure for AssertUnwindSafe<T> {
    type Static = T::Static;
    const IS_MUT: bool = T::IS_MUT;
    type AsMut = T::AsMut;
    fn describe_invoke<const UNWIND_SAFE: bool>() {
        T::describe_invoke::<UNWIND_SAFE>();
    }
}

/// An internal trait for the `Closure` type.
///
/// This trait is not stable and it's not recommended to use this in bounds or
/// implement yourself.
#[doc(hidden)]
pub trait IntoWasmClosure<T: ?Sized> {
    fn unsize(self: Box<Self>) -> Box<T>;
}

impl<T: ?Sized + WasmClosure> IntoWasmClosure<T> for T {
    fn unsize(self: Box<Self>) -> Box<T> {
        self
    }
}

/// Trait for converting a reference to a closure into a trait object reference.
///
/// This trait is not stable and it's not recommended to use this in bounds or
/// implement yourself.
#[doc(hidden)]
pub trait IntoWasmClosureRef<T: ?Sized> {
    fn unsize_closure_ref(&self) -> &T;
}

/// Trait for converting a mutable reference to a closure into a trait object reference.
///
/// This trait is not stable and it's not recommended to use this in bounds or
/// implement yourself.
#[doc(hidden)]
pub trait IntoWasmClosureRefMut<T: ?Sized> {
    fn unsize_closure_ref(&mut self) -> &mut T;
}

// Blanket impl for AssertUnwindSafe - delegates to inner type
impl<T: ?Sized, F> IntoWasmClosureRef<T> for AssertUnwindSafe<F>
where
    F: IntoWasmClosureRef<T>,
{
    fn unsize_closure_ref(&self) -> &T {
        self.0.unsize_closure_ref()
    }
}

impl<T: ?Sized, F> IntoWasmClosureRefMut<T> for AssertUnwindSafe<F>
where
    F: IntoWasmClosureRefMut<T>,
{
    fn unsize_closure_ref(&mut self) -> &mut T {
        self.0.unsize_closure_ref()
    }
}

// In ScopedClosure, the Rust closure type is the phantom type that erases.
unsafe impl<T: ?Sized + WasmClosure> ErasableGeneric for ScopedClosure<'_, T> {
    type Repr = ScopedClosure<'static, dyn FnMut()>;
}