Skip to main content

wasm_bindgen/convert/
impls.rs

1use alloc::boxed::Box;
2use alloc::vec::Vec;
3use core::char;
4use core::mem::{self, ManuallyDrop};
5use core::ptr::NonNull;
6
7use crate::__rt::marker::ErasableGeneric;
8use crate::__rt::{WasmSignedWordRepr, WasmWordRepr};
9use crate::convert::traits::{WasmAbi, WasmPrimitive};
10use crate::convert::{
11    FromWasmAbi, IntoWasmAbi, LongRefFromWasmAbi, MaybeFromWasmAbi, MaybeIntoWasmAbi,
12    NullableFromWasmAbi, NullableIntoWasmAbi, OptionFromWasmAbi, OptionIntoWasmAbi, RefFromWasmAbi,
13    ReturnWasmAbi, TryFromJsValue, UpcastFrom,
14};
15use crate::sys::Promising;
16use crate::sys::{JsNullable, JsOption, Undefined};
17use crate::{throw_str, Clamped, JsError, JsValue, Nullable};
18
19// Primitive types can always be passed over the ABI.
20impl<T: WasmPrimitive> WasmAbi for T {
21    type Prim1 = Self;
22    type Prim2 = ();
23    type Prim3 = ();
24    type Prim4 = ();
25
26    #[inline]
27    fn split(self) -> (Self, (), (), ()) {
28        (self, (), (), ())
29    }
30
31    #[inline]
32    fn join(prim: Self, _: (), _: (), _: ()) -> Self {
33        prim
34    }
35}
36
37impl WasmAbi for i128 {
38    type Prim1 = u64;
39    type Prim2 = u64;
40    type Prim3 = ();
41    type Prim4 = ();
42
43    #[inline]
44    fn split(self) -> (u64, u64, (), ()) {
45        let low = self as u64;
46        let high = (self >> 64) as u64;
47        (low, high, (), ())
48    }
49
50    #[inline]
51    fn join(low: u64, high: u64, _: (), _: ()) -> Self {
52        (((high as u128) << 64) | low as u128) as i128
53    }
54}
55impl WasmAbi for u128 {
56    type Prim1 = u64;
57    type Prim2 = u64;
58    type Prim3 = ();
59    type Prim4 = ();
60
61    #[inline]
62    fn split(self) -> (u64, u64, (), ()) {
63        let low = self as u64;
64        let high = (self >> 64) as u64;
65        (low, high, (), ())
66    }
67
68    #[inline]
69    fn join(low: u64, high: u64, _: (), _: ()) -> Self {
70        ((high as u128) << 64) | low as u128
71    }
72}
73
74/// The ABI of `Option<T>`, `Nullable<T>` and `Nullable<Option<T>>` for a `T`
75/// whose own ABI has no spare value: `tag` is `0` for `None`, `1` for a value
76/// and `2` for `Null`.
77#[doc(hidden)]
78#[derive(Clone, Copy)]
79pub struct MaybeAbi<T> {
80    pub tag: u32,
81    pub value: T,
82}
83
84impl<T: WasmAbi<Prim4 = ()>> WasmAbi for MaybeAbi<T> {
85    type Prim1 = u32;
86    type Prim2 = T::Prim1;
87    type Prim3 = T::Prim2;
88    type Prim4 = T::Prim3;
89
90    #[inline]
91    fn split(self) -> (u32, T::Prim1, T::Prim2, T::Prim3) {
92        let (prim1, prim2, prim3, ()) = self.value.split();
93        (self.tag, prim1, prim2, prim3)
94    }
95
96    #[inline]
97    fn join(tag: u32, prim1: T::Prim1, prim2: T::Prim2, prim3: T::Prim3) -> Self {
98        MaybeAbi {
99            tag,
100            value: T::join(prim1, prim2, prim3, ()),
101        }
102    }
103}
104
105macro_rules! type_wasm_native {
106    ($($t:tt as $c:tt)*) => ($(
107        impl IntoWasmAbi for $t {
108            type Abi = $c;
109
110            #[inline]
111            fn into_abi(self) -> $c { self as $c }
112        }
113
114        impl FromWasmAbi for $t {
115            type Abi = $c;
116
117            #[inline]
118            unsafe fn from_abi(js: $c) -> Self { js as $t }
119        }
120
121        impl MaybeIntoWasmAbi for $t {
122            type MaybeAbi = MaybeAbi<$c>;
123
124            #[inline]
125            fn into_maybe_abi(self) -> MaybeAbi<$c> {
126                MaybeAbi { tag: 1, value: self as $c }
127            }
128
129            #[inline]
130            fn none() -> MaybeAbi<$c> {
131                MaybeAbi { tag: 0, value: 0 as $c }
132            }
133        }
134
135        impl NullableIntoWasmAbi for $t {
136            #[inline]
137            fn null() -> MaybeAbi<$c> {
138                MaybeAbi { tag: 2, value: 0 as $c }
139            }
140        }
141
142        impl MaybeFromWasmAbi for $t {
143            type MaybeAbi = MaybeAbi<$c>;
144
145            #[inline]
146            unsafe fn from_maybe_abi(js: MaybeAbi<$c>) -> Self {
147                js.value as $t
148            }
149
150            #[inline]
151            fn is_none(js: &MaybeAbi<$c>) -> bool {
152                js.tag == 0
153            }
154        }
155
156        impl NullableFromWasmAbi for $t {
157            #[inline]
158            fn is_null(js: &MaybeAbi<$c>) -> bool {
159                js.tag == 2
160            }
161        }
162
163        impl UpcastFrom<$t> for JsValue {}
164        impl UpcastFrom<$t> for JsOption<JsValue> {}
165        impl UpcastFrom<$t> for JsNullable<JsValue> {}
166        impl UpcastFrom<$t> for $t {}
167        impl<Target: UpcastFrom<$t>> UpcastFrom<$t> for Option<Target> {}
168        impl<Target: UpcastFrom<$t>> UpcastFrom<$t> for Nullable<Target> {}
169    )*)
170}
171
172type_wasm_native!(
173    i64 as i64
174    u64 as u64
175    i128 as i128
176    u128 as u128
177    f64 as f64
178);
179
180impl UpcastFrom<u64> for u128 {}
181impl UpcastFrom<u64> for JsOption<u128> {}
182impl UpcastFrom<u64> for JsNullable<u128> {}
183impl UpcastFrom<i64> for i128 {}
184impl UpcastFrom<i64> for JsOption<i128> {}
185impl UpcastFrom<i64> for JsNullable<i128> {}
186
187/// Sentinel value used to encode `None` for optional pointer-sized and
188/// 32-bit numeric values transferred over the JS `number` ABI.
189///
190/// `2^53 - 1` (`Number.MAX_SAFE_INTEGER`) is chosen because it is:
191/// - exactly representable as an `f64` (so JS round-trips it losslessly),
192/// - outside the range of any valid `i32`/`u32`/`f32` value (so it can't
193///   collide with a real `Some(...)` payload from those types), and
194/// - far above any plausible wasm64 pointer (which is bounded by the
195///   memory-64 address space limit, well below `2^53`).
196const F64_ABI_OPTION_SENTINEL: f64 = 9007199254740991_f64;
197
198/// `Nullable::Null` over the JS `number` ABI: the safe integer below
199/// [`F64_ABI_OPTION_SENTINEL`], outside every value range for the same
200/// reasons.
201#[doc(hidden)]
202pub const F64_ABI_NULL_SENTINEL: f64 = 9007199254740990_f64;
203
204macro_rules! type_wasm_native_f64_option {
205    ($($t:tt as $c:tt)*) => ($(
206        impl IntoWasmAbi for $t {
207            type Abi = $c;
208
209            #[inline]
210            fn into_abi(self) -> $c { self as $c }
211        }
212
213        impl FromWasmAbi for $t {
214            type Abi = $c;
215
216            #[inline]
217            unsafe fn from_abi(js: $c) -> Self { js as $t }
218        }
219
220        unsafe impl ErasableGeneric for $t {
221            type Repr = $t;
222        }
223
224        impl Promising for $t {
225            type Resolution = $t;
226        }
227
228        impl MaybeIntoWasmAbi for $t {
229            type MaybeAbi = f64;
230
231            #[inline]
232            fn into_maybe_abi(self) -> f64 {
233                self as $c as f64
234            }
235
236            #[inline]
237            fn none() -> f64 {
238                F64_ABI_OPTION_SENTINEL
239            }
240        }
241
242        impl NullableIntoWasmAbi for $t {
243            #[inline]
244            fn null() -> f64 {
245                F64_ABI_NULL_SENTINEL
246            }
247        }
248
249        impl MaybeFromWasmAbi for $t {
250            type MaybeAbi = f64;
251
252            #[inline]
253            unsafe fn from_maybe_abi(js: f64) -> Self {
254                js as $c as $t
255            }
256
257            #[inline]
258            fn is_none(js: &f64) -> bool {
259                *js == F64_ABI_OPTION_SENTINEL
260            }
261        }
262
263        impl NullableFromWasmAbi for $t {
264            #[inline]
265            fn is_null(js: &f64) -> bool {
266                *js == F64_ABI_NULL_SENTINEL
267            }
268        }
269
270        impl UpcastFrom<$t> for JsValue {}
271        impl UpcastFrom<$t> for JsOption<JsValue> {}
272        impl UpcastFrom<$t> for JsNullable<JsValue> {}
273        impl UpcastFrom<$t> for $t {}
274        impl<Target: UpcastFrom<$t>> UpcastFrom<$t> for Option<Target> {}
275        impl<Target: UpcastFrom<$t>> UpcastFrom<$t> for Nullable<Target> {}
276    )*)
277}
278
279type_wasm_native_f64_option!(
280    i32 as i32
281    u32 as u32
282    f32 as f32
283    isize as WasmSignedWordRepr
284    usize as WasmWordRepr
285);
286
287#[cfg(target_pointer_width = "32")]
288impl UpcastFrom<isize> for i32 {}
289#[cfg(target_pointer_width = "32")]
290impl UpcastFrom<isize> for JsOption<i32> {}
291#[cfg(target_pointer_width = "32")]
292impl UpcastFrom<isize> for JsNullable<i32> {}
293
294impl UpcastFrom<isize> for i64 {}
295impl UpcastFrom<isize> for JsOption<i64> {}
296impl UpcastFrom<isize> for JsNullable<i64> {}
297impl UpcastFrom<isize> for i128 {}
298impl UpcastFrom<isize> for JsOption<i128> {}
299impl UpcastFrom<isize> for JsNullable<i128> {}
300
301impl UpcastFrom<i32> for isize {}
302impl UpcastFrom<i32> for JsOption<isize> {}
303impl UpcastFrom<i32> for JsNullable<isize> {}
304impl UpcastFrom<i32> for i64 {}
305impl UpcastFrom<i32> for JsOption<i64> {}
306impl UpcastFrom<i32> for JsNullable<i64> {}
307impl UpcastFrom<i32> for i128 {}
308impl UpcastFrom<i32> for JsOption<i128> {}
309impl UpcastFrom<i32> for JsNullable<i128> {}
310
311impl UpcastFrom<u32> for usize {}
312impl UpcastFrom<u32> for JsOption<usize> {}
313impl UpcastFrom<u32> for JsNullable<usize> {}
314impl UpcastFrom<u32> for u64 {}
315impl UpcastFrom<u32> for JsOption<u64> {}
316impl UpcastFrom<u32> for JsNullable<u64> {}
317impl UpcastFrom<u32> for u128 {}
318impl UpcastFrom<u32> for JsOption<u128> {}
319impl UpcastFrom<u32> for JsNullable<u128> {}
320
321#[cfg(target_pointer_width = "32")]
322impl UpcastFrom<usize> for u32 {}
323#[cfg(target_pointer_width = "32")]
324impl UpcastFrom<usize> for JsOption<u32> {}
325#[cfg(target_pointer_width = "32")]
326impl UpcastFrom<usize> for JsNullable<u32> {}
327impl UpcastFrom<usize> for u64 {}
328impl UpcastFrom<usize> for JsOption<u64> {}
329impl UpcastFrom<usize> for JsNullable<u64> {}
330impl UpcastFrom<usize> for u128 {}
331impl UpcastFrom<usize> for JsOption<u128> {}
332impl UpcastFrom<usize> for JsNullable<u128> {}
333
334impl UpcastFrom<f32> for f64 {}
335impl UpcastFrom<f32> for JsOption<f64> {}
336impl UpcastFrom<f32> for JsNullable<f64> {}
337
338/// The sentinel value is 0xFF_FFFF for primitives with less than 32 bits.
339///
340/// This value is used, so all small primitive types (`bool`, `i8`, `u8`,
341/// `i16`, `u16`, `char`) can use the same JS glue code. `char::MAX` is
342/// 0x10_FFFF btw.
343const U32_ABI_OPTION_SENTINEL: u32 = 0x00FF_FFFFu32;
344
345/// `Nullable::Null` for the same types, below the `Option` sentinel.
346const U32_ABI_NULL_SENTINEL: u32 = 0x00FF_FFFEu32;
347
348macro_rules! type_abi_as_u32 {
349    ($($t:tt)*) => ($(
350        impl IntoWasmAbi for $t {
351            type Abi = u32;
352
353            #[inline]
354            fn into_abi(self) -> u32 { self as u32 }
355        }
356
357        impl FromWasmAbi for $t {
358            type Abi = u32;
359
360            #[inline]
361            unsafe fn from_abi(js: u32) -> Self { js as $t }
362        }
363
364        impl OptionIntoWasmAbi for $t {
365            #[inline]
366            fn none() -> u32 { U32_ABI_OPTION_SENTINEL }
367        }
368
369        impl OptionFromWasmAbi for $t {
370            #[inline]
371            fn is_none(js: &u32) -> bool { *js == U32_ABI_OPTION_SENTINEL }
372        }
373
374        impl_nullable_into_shared_abi!(null = U32_ABI_NULL_SENTINEL; [] $t);
375        impl_nullable_from_shared_abi!(is_null = |js| *js == U32_ABI_NULL_SENTINEL; [] $t);
376
377        unsafe impl ErasableGeneric for $t {
378            type Repr = $t;
379        }
380
381        impl Promising for $t {
382            type Resolution = $t;
383        }
384
385        impl UpcastFrom<$t> for JsValue {}
386        impl UpcastFrom<$t> for JsOption<JsValue> {}
387        impl UpcastFrom<$t> for JsNullable<JsValue> {}
388        impl UpcastFrom<$t> for $t {}
389        impl<Target: UpcastFrom<$t>> UpcastFrom<$t> for Option<Target> {}
390        impl<Target: UpcastFrom<$t>> UpcastFrom<$t> for Nullable<Target> {}
391    )*)
392}
393
394type_abi_as_u32!(i8 u8 i16 u16);
395
396impl UpcastFrom<i8> for i16 {}
397impl UpcastFrom<i8> for JsOption<i16> {}
398impl UpcastFrom<i8> for JsNullable<i16> {}
399impl UpcastFrom<i8> for i32 {}
400impl UpcastFrom<i8> for JsOption<i32> {}
401impl UpcastFrom<i8> for JsNullable<i32> {}
402impl UpcastFrom<i8> for i64 {}
403impl UpcastFrom<i8> for JsOption<i64> {}
404impl UpcastFrom<i8> for JsNullable<i64> {}
405impl UpcastFrom<i8> for i128 {}
406impl UpcastFrom<i8> for JsOption<i128> {}
407impl UpcastFrom<i8> for JsNullable<i128> {}
408
409impl UpcastFrom<u8> for u16 {}
410impl UpcastFrom<u8> for JsOption<u16> {}
411impl UpcastFrom<u8> for JsNullable<u16> {}
412impl UpcastFrom<u8> for u32 {}
413impl UpcastFrom<u8> for JsOption<u32> {}
414impl UpcastFrom<u8> for JsNullable<u32> {}
415impl UpcastFrom<u8> for u64 {}
416impl UpcastFrom<u8> for JsOption<u64> {}
417impl UpcastFrom<u8> for JsNullable<u64> {}
418impl UpcastFrom<u8> for u128 {}
419impl UpcastFrom<u8> for JsOption<u128> {}
420impl UpcastFrom<u8> for JsNullable<u128> {}
421
422impl UpcastFrom<i16> for i32 {}
423impl UpcastFrom<i16> for JsOption<i32> {}
424impl UpcastFrom<i16> for JsNullable<i32> {}
425impl UpcastFrom<i16> for i64 {}
426impl UpcastFrom<i16> for JsOption<i64> {}
427impl UpcastFrom<i16> for JsNullable<i64> {}
428impl UpcastFrom<i16> for i128 {}
429impl UpcastFrom<i16> for JsOption<i128> {}
430impl UpcastFrom<i16> for JsNullable<i128> {}
431
432impl UpcastFrom<u16> for u32 {}
433impl UpcastFrom<u16> for JsOption<u32> {}
434impl UpcastFrom<u16> for JsNullable<u32> {}
435impl UpcastFrom<u16> for u64 {}
436impl UpcastFrom<u16> for JsOption<u64> {}
437impl UpcastFrom<u16> for JsNullable<u64> {}
438impl UpcastFrom<u16> for u128 {}
439impl UpcastFrom<u16> for JsOption<u128> {}
440impl UpcastFrom<u16> for JsNullable<u128> {}
441
442impl IntoWasmAbi for bool {
443    type Abi = u32;
444
445    #[inline]
446    fn into_abi(self) -> u32 {
447        self as u32
448    }
449}
450
451impl FromWasmAbi for bool {
452    type Abi = u32;
453
454    #[inline]
455    unsafe fn from_abi(js: u32) -> bool {
456        js != 0
457    }
458}
459
460impl OptionIntoWasmAbi for bool {
461    #[inline]
462    fn none() -> u32 {
463        U32_ABI_OPTION_SENTINEL
464    }
465}
466
467impl OptionFromWasmAbi for bool {
468    #[inline]
469    fn is_none(js: &u32) -> bool {
470        *js == U32_ABI_OPTION_SENTINEL
471    }
472}
473
474impl_nullable_into_shared_abi!(null = U32_ABI_NULL_SENTINEL; [] bool);
475impl_nullable_from_shared_abi!(is_null = |js| *js == U32_ABI_NULL_SENTINEL; [] bool);
476
477unsafe impl ErasableGeneric for bool {
478    type Repr = bool;
479}
480
481impl Promising for bool {
482    type Resolution = bool;
483}
484
485impl UpcastFrom<bool> for JsValue {}
486impl UpcastFrom<bool> for JsOption<JsValue> {}
487impl UpcastFrom<bool> for JsNullable<JsValue> {}
488impl UpcastFrom<bool> for bool {}
489impl<Target: UpcastFrom<bool>> UpcastFrom<bool> for Option<Target> {}
490impl<Target: UpcastFrom<bool>> UpcastFrom<bool> for Nullable<Target> {}
491
492impl IntoWasmAbi for char {
493    type Abi = u32;
494
495    #[inline]
496    fn into_abi(self) -> u32 {
497        self as u32
498    }
499}
500
501impl FromWasmAbi for char {
502    type Abi = u32;
503
504    #[inline]
505    unsafe fn from_abi(js: u32) -> char {
506        // SAFETY: Checked in bindings.
507        char::from_u32_unchecked(js)
508    }
509}
510
511impl OptionIntoWasmAbi for char {
512    #[inline]
513    fn none() -> u32 {
514        U32_ABI_OPTION_SENTINEL
515    }
516}
517
518impl OptionFromWasmAbi for char {
519    #[inline]
520    fn is_none(js: &u32) -> bool {
521        *js == U32_ABI_OPTION_SENTINEL
522    }
523}
524
525impl_nullable_into_shared_abi!(null = U32_ABI_NULL_SENTINEL; [] char);
526impl_nullable_from_shared_abi!(is_null = |js| *js == U32_ABI_NULL_SENTINEL; [] char);
527
528unsafe impl ErasableGeneric for char {
529    type Repr = char;
530}
531
532impl Promising for char {
533    type Resolution = char;
534}
535
536impl UpcastFrom<char> for JsValue {}
537impl UpcastFrom<char> for JsOption<JsValue> {}
538impl UpcastFrom<char> for JsNullable<JsValue> {}
539impl UpcastFrom<char> for char {}
540impl<Target: UpcastFrom<char>> UpcastFrom<char> for Option<Target> {}
541impl<Target: UpcastFrom<char>> UpcastFrom<char> for Nullable<Target> {}
542
543impl<T> IntoWasmAbi for *const T {
544    type Abi = WasmWordRepr;
545
546    #[inline]
547    fn into_abi(self) -> Self::Abi {
548        self as usize as WasmWordRepr
549    }
550}
551
552impl<T> FromWasmAbi for *const T {
553    type Abi = WasmWordRepr;
554
555    #[inline]
556    unsafe fn from_abi(js: Self::Abi) -> *const T {
557        js as usize as *const T
558    }
559}
560
561unsafe impl<T: ErasableGeneric> ErasableGeneric for *const T {
562    type Repr = *const T::Repr;
563}
564
565impl<T, Target> UpcastFrom<*const T> for *const Target where Target: UpcastFrom<T> {}
566impl<T, Target> UpcastFrom<*const T> for JsOption<*const Target> where Target: UpcastFrom<T> {}
567impl<T, Target> UpcastFrom<*const T> for JsNullable<*const Target> where Target: UpcastFrom<T> {}
568
569unsafe impl<T: ErasableGeneric> ErasableGeneric for Option<T> {
570    type Repr = Option<<T as ErasableGeneric>::Repr>;
571}
572
573impl<T, Target> UpcastFrom<Option<T>> for Option<Target> where Target: UpcastFrom<T> {}
574// `Nullable<T>` reaches `Nullable<Option<T>>` through the `Nullable` to
575// `Nullable` rule, and an `Option<T>` through this one.
576impl<T, Target> UpcastFrom<Option<T>> for Nullable<Target> where Target: UpcastFrom<Option<T>> {}
577impl<T, Target> UpcastFrom<Option<T>> for JsOption<Option<Target>> where Target: UpcastFrom<T> {}
578impl<T, Target> UpcastFrom<Option<T>> for JsNullable<Option<Target>> where Target: UpcastFrom<T> {}
579// `None` is `undefined`, a JS value, so an optional carrier upcasts to `JsValue`
580// whenever its payload does, as each scalar and string carrier does.
581impl<T> UpcastFrom<Option<T>> for JsValue where JsValue: UpcastFrom<T> {}
582
583/// Pointers in a `Nullable` cross as JS numbers with the `f64` sentinels, as
584/// they do in an `Option`.
585macro_rules! nullable_ptr_abi {
586    ($($t:ty),*) => ($(
587        impl<T> MaybeIntoWasmAbi for $t {
588            type MaybeAbi = f64;
589
590            #[inline]
591            fn into_maybe_abi(self) -> f64 {
592                self as usize as f64
593            }
594
595            #[inline]
596            fn none() -> f64 {
597                F64_ABI_OPTION_SENTINEL
598            }
599        }
600
601        impl<T> NullableIntoWasmAbi for $t {
602            #[inline]
603            fn null() -> f64 {
604                F64_ABI_NULL_SENTINEL
605            }
606        }
607
608        impl<T> MaybeFromWasmAbi for $t {
609            type MaybeAbi = f64;
610
611            #[inline]
612            unsafe fn from_maybe_abi(js: f64) -> Self {
613                js as usize as $t
614            }
615
616            #[inline]
617            fn is_none(js: &f64) -> bool {
618                *js == F64_ABI_OPTION_SENTINEL
619            }
620        }
621
622        impl<T> NullableFromWasmAbi for $t {
623            #[inline]
624            fn is_null(js: &f64) -> bool {
625                *js == F64_ABI_NULL_SENTINEL
626            }
627        }
628    )*)
629}
630
631nullable_ptr_abi!(*const T, *mut T);
632
633impl<T> IntoWasmAbi for *mut T {
634    type Abi = WasmWordRepr;
635
636    #[inline]
637    fn into_abi(self) -> Self::Abi {
638        self as usize as WasmWordRepr
639    }
640}
641
642impl<T> FromWasmAbi for *mut T {
643    type Abi = WasmWordRepr;
644
645    #[inline]
646    unsafe fn from_abi(js: Self::Abi) -> *mut T {
647        js as usize as *mut T
648    }
649}
650
651impl<T> IntoWasmAbi for NonNull<T> {
652    type Abi = WasmWordRepr;
653
654    #[inline]
655    fn into_abi(self) -> Self::Abi {
656        self.as_ptr() as usize as WasmWordRepr
657    }
658}
659
660impl<T> OptionIntoWasmAbi for NonNull<T> {
661    #[inline]
662    fn none() -> Self::Abi {
663        0 as WasmWordRepr
664    }
665}
666
667impl<T> FromWasmAbi for NonNull<T> {
668    type Abi = WasmWordRepr;
669
670    #[inline]
671    unsafe fn from_abi(js: Self::Abi) -> Self {
672        // SAFETY: Checked in bindings.
673        NonNull::new_unchecked(js as usize as *mut T)
674    }
675}
676
677impl<T> OptionFromWasmAbi for NonNull<T> {
678    #[inline]
679    fn is_none(js: &Self::Abi) -> bool {
680        *js == 0 as WasmWordRepr
681    }
682}
683
684impl IntoWasmAbi for JsValue {
685    type Abi = u32;
686
687    #[inline]
688    fn into_abi(self) -> u32 {
689        let ret = self.idx;
690        mem::forget(self);
691        ret
692    }
693}
694
695impl FromWasmAbi for JsValue {
696    type Abi = u32;
697
698    #[inline]
699    unsafe fn from_abi(js: u32) -> JsValue {
700        JsValue::_new(js)
701    }
702}
703
704impl IntoWasmAbi for &JsValue {
705    type Abi = u32;
706
707    #[inline]
708    fn into_abi(self) -> u32 {
709        self.idx
710    }
711}
712
713impl RefFromWasmAbi for JsValue {
714    type Abi = u32;
715    type Anchor = ManuallyDrop<JsValue>;
716
717    #[inline]
718    unsafe fn ref_from_abi(js: u32) -> Self::Anchor {
719        ManuallyDrop::new(JsValue::_new(js))
720    }
721}
722
723impl LongRefFromWasmAbi for JsValue {
724    type Abi = u32;
725    type Anchor = JsValue;
726
727    #[inline]
728    unsafe fn long_ref_from_abi(js: u32) -> Self::Anchor {
729        Self::from_abi(js)
730    }
731}
732
733impl OptionIntoWasmAbi for JsValue {
734    #[inline]
735    fn none() -> u32 {
736        crate::__rt::JSIDX_UNDEFINED
737    }
738}
739
740impl OptionIntoWasmAbi for &JsValue {
741    #[inline]
742    fn none() -> u32 {
743        crate::__rt::JSIDX_UNDEFINED
744    }
745}
746
747impl OptionFromWasmAbi for JsValue {
748    #[inline]
749    fn is_none(js: &u32) -> bool {
750        unsafe { Self::ref_from_abi(*js) }.is_undefined()
751    }
752}
753
754impl_nullable_into_shared_abi!(null = crate::__rt::JSIDX_NULL; [] JsValue);
755impl_nullable_into_shared_abi!(null = crate::__rt::JSIDX_NULL; [] &JsValue);
756// The glue hands `null` over as the fixed handle, so this is an index test
757// rather than a call into JS; a `null` that did arrive in its own slot is an
758// owned `Value` and is dropped as one.
759impl_nullable_from_shared_abi!(is_null = |js| *js == crate::__rt::JSIDX_NULL; [] JsValue);
760
761/// A spare value in `T`'s own ABI is the common case, so `OptionIntoWasmAbi`
762/// supplies the `Option<T>` ABI for every such type; a type without one
763/// implements `MaybeIntoWasmAbi` itself with a wider `MaybeAbi`.
764impl<T: OptionIntoWasmAbi> MaybeIntoWasmAbi for T {
765    type MaybeAbi = T::Abi;
766
767    #[inline]
768    fn into_maybe_abi(self) -> T::Abi {
769        self.into_abi()
770    }
771
772    #[inline]
773    fn none() -> T::Abi {
774        <T as OptionIntoWasmAbi>::none()
775    }
776}
777
778impl<T: OptionFromWasmAbi> MaybeFromWasmAbi for T {
779    type MaybeAbi = T::Abi;
780
781    #[inline]
782    unsafe fn from_maybe_abi(js: T::Abi) -> Self {
783        T::from_abi(js)
784    }
785
786    #[inline]
787    unsafe fn try_from_maybe_abi(js: T::Abi) -> Result<Self, &'static str> {
788        T::try_from_abi(js)
789    }
790
791    #[inline]
792    fn is_none(js: &T::Abi) -> bool {
793        <T as OptionFromWasmAbi>::is_none(js)
794    }
795}
796
797impl<T: MaybeIntoWasmAbi> IntoWasmAbi for Option<T> {
798    type Abi = T::MaybeAbi;
799
800    #[inline]
801    fn into_abi(self) -> T::MaybeAbi {
802        match self {
803            None => T::none(),
804            Some(me) => me.into_maybe_abi(),
805        }
806    }
807}
808
809impl<T: MaybeFromWasmAbi> FromWasmAbi for Option<T> {
810    type Abi = T::MaybeAbi;
811
812    #[inline]
813    unsafe fn from_abi(js: T::MaybeAbi) -> Self {
814        if T::is_none(&js) {
815            None
816        } else {
817            Some(T::from_maybe_abi(js))
818        }
819    }
820
821    #[inline]
822    unsafe fn try_from_abi(js: T::MaybeAbi) -> Result<Self, &'static str> {
823        if T::is_none(&js) {
824            Ok(None)
825        } else {
826            T::try_from_maybe_abi(js).map(Some)
827        }
828    }
829}
830
831impl<T: NullableIntoWasmAbi> IntoWasmAbi for Nullable<T> {
832    type Abi = T::MaybeAbi;
833
834    #[inline]
835    fn into_abi(self) -> T::MaybeAbi {
836        match self {
837            Nullable::Null => T::null(),
838            Nullable::Value(me) => me.into_maybe_abi(),
839        }
840    }
841}
842
843/// `Nullable<Option<T>>` shares `T`'s ABI, `Null` and `None` being its two
844/// spare values.
845impl<T: NullableIntoWasmAbi> IntoWasmAbi for Nullable<Option<T>> {
846    type Abi = T::MaybeAbi;
847
848    #[inline]
849    fn into_abi(self) -> T::MaybeAbi {
850        match self {
851            Nullable::Null => T::null(),
852            Nullable::Value(me) => me.into_abi(),
853        }
854    }
855}
856
857impl<T: NullableFromWasmAbi> FromWasmAbi for Nullable<T> {
858    type Abi = T::MaybeAbi;
859
860    #[inline]
861    unsafe fn from_abi(js: T::MaybeAbi) -> Self {
862        if T::is_null(&js) {
863            Nullable::Null
864        } else {
865            Nullable::Value(T::from_maybe_abi(js))
866        }
867    }
868
869    #[inline]
870    unsafe fn try_from_abi(js: T::MaybeAbi) -> Result<Self, &'static str> {
871        if T::is_null(&js) {
872            Ok(Nullable::Null)
873        } else {
874            T::try_from_maybe_abi(js).map(Nullable::Value)
875        }
876    }
877}
878
879/// `T`'s `undefined` test may cover its `null` sentinel too, as a slice's
880/// does with the null pointer, so `Null` is ruled out before the `Option`
881/// reads the rest.
882impl<T: NullableFromWasmAbi> FromWasmAbi for Nullable<Option<T>> {
883    type Abi = T::MaybeAbi;
884
885    #[inline]
886    unsafe fn from_abi(js: T::MaybeAbi) -> Self {
887        if T::is_null(&js) {
888            Nullable::Null
889        } else {
890            Nullable::Value(Option::from_abi(js))
891        }
892    }
893
894    #[inline]
895    unsafe fn try_from_abi(js: T::MaybeAbi) -> Result<Self, &'static str> {
896        if T::is_null(&js) {
897            Ok(Nullable::Null)
898        } else {
899            Option::try_from_abi(js).map(Nullable::Value)
900        }
901    }
902}
903
904unsafe impl<T: ErasableGeneric> ErasableGeneric for Nullable<T> {
905    type Repr = Nullable<<T as ErasableGeneric>::Repr>;
906}
907
908impl<T, Target> UpcastFrom<Nullable<T>> for Nullable<Target> where Target: UpcastFrom<T> {}
909// An `Option<T>` reads `null` as `None`, so every value of a `Nullable<T>` is one
910// of an `Option<T>`.
911impl<T, Target> UpcastFrom<Nullable<T>> for Option<Target> where Target: UpcastFrom<T> {}
912impl<T, Target> UpcastFrom<Nullable<T>> for JsOption<Nullable<Target>> where Target: UpcastFrom<T> {}
913impl<T, Target> UpcastFrom<Nullable<T>> for JsNullable<Nullable<Target>> where Target: UpcastFrom<T> {}
914impl<T> UpcastFrom<Nullable<T>> for JsValue where JsValue: UpcastFrom<T> {}
915
916impl<T: Promising> Promising for Option<T> {
917    type Resolution = Option<<T as Promising>::Resolution>;
918}
919
920impl<T: Promising> Promising for Nullable<T> {
921    type Resolution = Nullable<<T as Promising>::Resolution>;
922}
923
924impl<T: IntoWasmAbi> IntoWasmAbi for Clamped<T> {
925    type Abi = T::Abi;
926
927    #[inline]
928    fn into_abi(self) -> Self::Abi {
929        self.0.into_abi()
930    }
931}
932
933impl<T: FromWasmAbi> FromWasmAbi for Clamped<T> {
934    type Abi = T::Abi;
935
936    #[inline]
937    unsafe fn from_abi(js: T::Abi) -> Self {
938        Clamped(T::from_abi(js))
939    }
940
941    #[inline]
942    unsafe fn try_from_abi(js: T::Abi) -> Result<Self, &'static str> {
943        T::try_from_abi(js).map(Clamped)
944    }
945}
946
947impl IntoWasmAbi for () {
948    type Abi = ();
949
950    #[inline]
951    fn into_abi(self) {
952        self
953    }
954}
955
956impl FromWasmAbi for () {
957    type Abi = ();
958
959    #[inline]
960    unsafe fn from_abi(_js: ()) {}
961}
962
963impl Promising for () {
964    type Resolution = Undefined;
965}
966
967impl UpcastFrom<()> for JsValue {}
968impl UpcastFrom<()> for () {}
969// `()` crosses as `undefined`, which an `Option<T>` reads as `None`.
970impl<T> UpcastFrom<()> for Option<T> {}
971
972unsafe impl ErasableGeneric for () {
973    type Repr = ();
974}
975
976impl<T: WasmAbi<Prim3 = (), Prim4 = ()>> WasmAbi for Result<T, u32> {
977    type Prim1 = T::Prim1;
978    type Prim2 = T::Prim2;
979    // The order of primitives here is such that we can pop() the possible error
980    // first, deal with it and move on. Later primitives are popped off the
981    // stack first.
982    /// If this `Result` is an `Err`, the error value.
983    type Prim3 = u32;
984    /// Whether this `Result` is an `Err`.
985    type Prim4 = u32;
986
987    #[inline]
988    fn split(self) -> (T::Prim1, T::Prim2, u32, u32) {
989        match self {
990            Ok(value) => {
991                let (prim1, prim2, (), ()) = value.split();
992                (prim1, prim2, 0, 0)
993            }
994            Err(err) => (Default::default(), Default::default(), err, 1),
995        }
996    }
997
998    #[inline]
999    fn join(prim1: T::Prim1, prim2: T::Prim2, err: u32, is_err: u32) -> Self {
1000        if is_err == 0 {
1001            Ok(T::join(prim1, prim2, (), ()))
1002        } else {
1003            Err(err)
1004        }
1005    }
1006}
1007
1008impl<T, E> ReturnWasmAbi for Result<T, E>
1009where
1010    T: IntoWasmAbi,
1011    E: Into<JsValue>,
1012    T::Abi: WasmAbi<Prim3 = (), Prim4 = ()>,
1013{
1014    type Abi = Result<T::Abi, u32>;
1015
1016    #[inline]
1017    fn return_abi(self) -> Self::Abi {
1018        match self {
1019            Ok(v) => Ok(v.into_abi()),
1020            Err(e) => {
1021                let jsval = e.into();
1022                Err(jsval.into_abi())
1023            }
1024        }
1025    }
1026}
1027
1028unsafe impl<T: ErasableGeneric, E: ErasableGeneric> ErasableGeneric for Result<T, E> {
1029    type Repr = Result<<T as ErasableGeneric>::Repr, <E as ErasableGeneric>::Repr>;
1030}
1031
1032impl<T: Promising, E> Promising for Result<T, E> {
1033    type Resolution = Result<<T as Promising>::Resolution, E>;
1034}
1035
1036impl<T, E, TargetT, TargetE> UpcastFrom<Result<T, E>> for Result<TargetT, TargetE>
1037where
1038    TargetT: UpcastFrom<T>,
1039    TargetE: UpcastFrom<E>,
1040{
1041}
1042impl<T, E, TargetT, TargetE> UpcastFrom<Result<T, E>> for JsOption<Result<TargetT, TargetE>>
1043where
1044    TargetT: UpcastFrom<T>,
1045    TargetE: UpcastFrom<E>,
1046{
1047}
1048impl<T, E, TargetT, TargetE> UpcastFrom<Result<T, E>> for JsNullable<Result<TargetT, TargetE>>
1049where
1050    TargetT: UpcastFrom<T>,
1051    TargetE: UpcastFrom<E>,
1052{
1053}
1054
1055unsafe impl ErasableGeneric for JsError {
1056    type Repr = JsValue;
1057}
1058
1059impl IntoWasmAbi for JsError {
1060    type Abi = <JsValue as IntoWasmAbi>::Abi;
1061
1062    fn into_abi(self) -> Self::Abi {
1063        self.value.into_abi()
1064    }
1065}
1066
1067// `JsError` is `#[repr(transparent)]` over `JsValue`
1068impl FromWasmAbi for JsError {
1069    type Abi = <JsValue as FromWasmAbi>::Abi;
1070
1071    #[inline]
1072    unsafe fn from_abi(js: Self::Abi) -> Self {
1073        JsError {
1074            value: JsValue::from_abi(js),
1075        }
1076    }
1077}
1078
1079impl Promising for JsError {
1080    type Resolution = JsError;
1081}
1082
1083impl UpcastFrom<JsError> for JsValue {}
1084impl UpcastFrom<JsError> for JsOption<JsValue> {}
1085impl UpcastFrom<JsError> for JsNullable<JsValue> {}
1086impl UpcastFrom<JsError> for JsError {}
1087
1088/// The compat form of an owned vector: an in-place sequence of `JsValue`
1089/// handles, converted to or from `T` in Rust. The released `Vec<String>`,
1090/// `Vec`s of exported structs and numeric enums, and third-party impls cross
1091/// this way. It has no new uses: an element whose single value crosses
1092/// without calling into wasm is declared as an encoded sequence instead.
1093///
1094/// # ⚠️ Unstable
1095///
1096/// This is part of the internal [`convert`](crate::convert) module, **no
1097/// stability guarantees** are provided. Use at your own risk. See its
1098/// documentation for more details.
1099// Note: this can't take `&[T]` because the `Into<JsValue>` impl needs
1100// ownership of `T`.
1101pub fn js_value_vector_into_abi<T: Into<JsValue>>(
1102    vector: Box<[T]>,
1103) -> <Box<[JsValue]> as IntoWasmAbi>::Abi {
1104    let js_vals: Box<[JsValue]> = vector.into_vec().into_iter().map(|x| x.into()).collect();
1105
1106    js_vals.into_abi()
1107}
1108
1109/// The mirror of [`js_value_vector_into_abi`], checking each element with
1110/// [`TryFromJsValue`].
1111///
1112/// # ⚠️ Unstable
1113///
1114/// This is part of the internal [`convert`](crate::convert) module, **no
1115/// stability guarantees** are provided. Use at your own risk. See its
1116/// documentation for more details.
1117pub unsafe fn js_value_vector_from_abi<T: TryFromJsValue>(
1118    js: <Box<[JsValue]> as FromWasmAbi>::Abi,
1119) -> Box<[T]> {
1120    // Thrown directly, rather than inside the iterator chain or a closure, to
1121    // keep the function that took the `Vec` within the debug-mode error
1122    // stack's frame limit.
1123    match try_js_value_vector_from_abi(js) {
1124        Ok(result) => result,
1125        Err(msg) => throw_str(msg),
1126    }
1127}
1128
1129/// The fallible form of [`js_value_vector_from_abi`].
1130///
1131/// Collecting stops at the first element of the wrong type and drops
1132/// everything Rust owns: the buffer, the handles not yet converted, the
1133/// rejected handle and the elements converted so far.
1134///
1135/// # ⚠️ Unstable
1136///
1137/// This is part of the internal [`convert`](crate::convert) module, **no
1138/// stability guarantees** are provided. Use at your own risk. See its
1139/// documentation for more details.
1140pub unsafe fn try_js_value_vector_from_abi<T: TryFromJsValue>(
1141    js: <Box<[JsValue]> as FromWasmAbi>::Abi,
1142) -> Result<Box<[T]>, &'static str> {
1143    <Vec<JsValue> as FromWasmAbi>::from_abi(js)
1144        .into_iter()
1145        .map(|value| T::try_from_js_value(value).map_err(|_| crate::__rt::WRONG_TYPE_ERROR))
1146        .collect()
1147}