wry-bindgen-runtime 0.1.0-alpha.7

Wry runtime transport for wry-bindgen semantic bindings
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
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
use alloc::boxed::Box;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::future::Future;
use core::ops::AsyncFnOnce;

use super::{DecodeError, DecodedData, EncodedData, JsRef};

pub trait BinaryEncode {
    fn encode(self, encoder: &mut EncodedData);
}

pub trait BinaryDecode: Sized {
    fn decode(decoder: &mut DecodedData) -> Result<Self, DecodeError>;
}

pub trait JsRefEncode {
    fn js_ref(&self) -> JsRef;
}

mod sealed {
    pub trait Sealed {}
}

/// How long a decoded borrow must remain valid.
#[doc(hidden)]
pub trait BorrowScope: sealed::Sealed {}

/// The borrow only needs to outlive the synchronous call, so a JS handle may
/// ride JS's borrow stack.
#[doc(hidden)]
pub struct CallScoped;

/// The borrow must outlive the `Promise` an `async` export returns, so a JS
/// handle anchors an owned copy instead of riding the borrow stack.
#[doc(hidden)]
pub struct Anchored;

impl sealed::Sealed for CallScoped {}
impl sealed::Sealed for Anchored {}
impl BorrowScope for CallScoped {}
impl BorrowScope for Anchored {}

/// Decode one exported-function or callback argument from the wire, for borrow
/// scope `S`.
///
/// [`decode`](ArgAbi::decode) produces a [`Guard`](ArgAbi::Guard) that owns
/// whatever backs the argument for the duration of the call. [`project`] invokes
/// a continuation with the [`Projected`](ArgAbi::Projected) value the Rust
/// function actually receives (`&T`, `&mut T`, or an owned `T`) while the guard
/// is still alive.
#[doc(hidden)]
pub trait ArgAbi<S: BorrowScope> {
    /// The type whose `TypeDef` is advertised to JS for this argument.
    type Wire: EncodeTypeDef;

    /// Owns whatever keeps the projected argument valid across the call.
    type Guard;

    /// The guard type after projection, retained for any later write-back.
    type ProjectedGuard;

    /// What the Rust function receives, borrowed from the guard for `'a`.
    type Projected<'a>;

    /// Decode the guard from the incoming wire bytes.
    fn decode(decoder: &mut DecodedData) -> Result<Self::Guard, DecodeError>;

    /// Project the call argument for the duration of `with`, then return the
    /// continuation result and guard for any later write-back.
    fn project<R, F>(guard: Self::Guard, with: F) -> (R, Self::ProjectedGuard)
    where
        F: for<'a> FnOnce(Self::Projected<'a>) -> R;

    /// Append any post-call write-back data to the export response.
    fn write_back(_guard: Self::ProjectedGuard, _encoder: &mut EncodedData) {}

    /// The `async` counterpart of [`project`](ArgAbi::project): drive the async
    /// continuation `with` with the projected argument while owning the guard for
    /// the returned future's lifetime.
    fn project_async<R, F>(guard: Self::Guard, with: F) -> impl Future<Output = R>
    where
        F: for<'a> AsyncFnOnce(Self::Projected<'a>) -> R;
}

impl<S, T> ArgAbi<S> for T
where
    S: BorrowScope,
    T: BinaryDecode + EncodeTypeDef,
{
    type Wire = T;
    type Guard = T;
    type ProjectedGuard = ();
    type Projected<'a> = T;

    fn decode(decoder: &mut DecodedData) -> Result<Self::Guard, DecodeError> {
        <T as BinaryDecode>::decode(decoder)
    }

    fn project<R, F>(guard: Self::Guard, with: F) -> (R, Self::ProjectedGuard)
    where
        F: for<'a> FnOnce(Self::Projected<'a>) -> R,
    {
        let result = with(guard);
        (result, ())
    }

    async fn project_async<R, F>(guard: Self::Guard, with: F) -> R
    where
        F: for<'a> AsyncFnOnce(Self::Projected<'a>) -> R,
    {
        with(guard).await
    }
}

impl<S: BorrowScope> ArgAbi<S> for &str {
    type Wire = String;
    type Guard = String;
    type ProjectedGuard = ();
    type Projected<'a> = &'a str;

    fn decode(decoder: &mut DecodedData) -> Result<Self::Guard, DecodeError> {
        <String as BinaryDecode>::decode(decoder)
    }

    fn project<R, F>(guard: Self::Guard, with: F) -> (R, Self::ProjectedGuard)
    where
        F: for<'a> FnOnce(Self::Projected<'a>) -> R,
    {
        let result = with(&guard);
        (result, ())
    }

    async fn project_async<R, F>(guard: Self::Guard, with: F) -> R
    where
        F: for<'a> AsyncFnOnce(Self::Projected<'a>) -> R,
    {
        with(&guard).await
    }
}

impl<S, T> ArgAbi<S> for &[T]
where
    S: BorrowScope,
    T: BinaryDecode + EncodeTypeDef + 'static,
{
    type Wire = Vec<T>;
    type Guard = Vec<T>;
    type ProjectedGuard = ();
    type Projected<'a> = &'a [T];

    fn decode(decoder: &mut DecodedData) -> Result<Self::Guard, DecodeError> {
        <Vec<T> as BinaryDecode>::decode(decoder)
    }

    fn project<R, F>(guard: Self::Guard, with: F) -> (R, Self::ProjectedGuard)
    where
        F: for<'a> FnOnce(Self::Projected<'a>) -> R,
    {
        let result = with(&guard);
        (result, ())
    }

    async fn project_async<R, F>(guard: Self::Guard, with: F) -> R
    where
        F: for<'a> AsyncFnOnce(Self::Projected<'a>) -> R,
    {
        with(&guard).await
    }
}

impl<S, T> ArgAbi<S> for &mut [T]
where
    S: BorrowScope,
    T: BinaryDecode + BinaryEncode + EncodeTypeDef + 'static,
{
    type Wire = MutSliceArg<T>;
    type Guard = MutSliceArg<T>;
    type ProjectedGuard = Self::Guard;
    type Projected<'a> = &'a mut [T];

    fn decode(decoder: &mut DecodedData) -> Result<Self::Guard, DecodeError> {
        <MutSliceArg<T> as BinaryDecode>::decode(decoder)
    }

    fn project<R, F>(mut guard: Self::Guard, with: F) -> (R, Self::ProjectedGuard)
    where
        F: for<'a> FnOnce(Self::Projected<'a>) -> R,
    {
        let result = with(guard.as_mut_slice());
        (result, guard)
    }

    fn write_back(guard: Self::ProjectedGuard, encoder: &mut EncodedData) {
        MutSliceArg::write_back(guard, encoder);
    }

    async fn project_async<R, F>(mut guard: Self::Guard, with: F) -> R
    where
        F: for<'a> AsyncFnOnce(Self::Projected<'a>) -> R,
    {
        with(guard.as_mut_slice()).await
    }
}

pub(crate) const TYPE_CACHED: u8 = 0xFF;
pub(crate) const TYPE_FULL: u8 = 0xFE;

#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TypeTag {
    // The Rust unit type `()`. It carries no bytes; JS decodes it to `undefined`,
    // so an export returning `()` resolves to `undefined`, matching wasm-bindgen.
    Undefined = 0,
    Bool = 1,
    U8 = 2,
    U16 = 3,
    U32 = 4,
    U64 = 5,
    U128 = 6,
    I8 = 7,
    I16 = 8,
    I32 = 9,
    I64 = 10,
    I128 = 11,
    F32 = 12,
    F64 = 13,
    Usize = 14,
    Isize = 15,
    String = 16,
    HeapRef = 17,
    Callback = 18,
    Option = 19,
    Result = 20,
    Array = 21,
    BorrowedRef = 22,
    U8Clamped = 23,
    StringEnum = 24,
    DynamicUnion = 25,
    Char = 26,
    ThrowingResult = 27,
    NumericEnum = 28,
    RustValue = 29,
    RustBorrow = 30,
    // A `&mut [T]` argument. It rides the wire exactly like `Array` (a
    // length-prefixed element list), but the distinct tag tells the receiving
    // side to copy the (possibly mutated) elements back to the caller after the
    // call returns — wry has no shared linear memory, so the write-back travels
    // as data appended to the response. The element type def follows the tag.
    MutArray = 31,
}

#[derive(Clone, Default, PartialEq, Eq, PartialOrd, Ord)]
pub struct TypeDef {
    bytes: Vec<u8>,
}

#[derive(Clone, Copy)]
pub struct FunctionTypeInfo<'a> {
    type_id: u32,
    can_use_cached: bool,
    type_def: &'a TypeDef,
}

impl<'a> FunctionTypeInfo<'a> {
    pub const fn new(type_id: u32, can_use_cached: bool, type_def: &'a TypeDef) -> Self {
        Self {
            type_id,
            can_use_cached,
            type_def,
        }
    }
}

impl BinaryEncode for FunctionTypeInfo<'_> {
    fn encode(self, encoder: &mut EncodedData) {
        if self.can_use_cached {
            encoder.push_u8(TYPE_CACHED);
            encoder.push_u32(self.type_id);
        } else {
            encoder.push_u8(TYPE_FULL);
            encoder.push_u32(self.type_id);
            for &byte in self.type_def.bytes() {
                encoder.push_u8(byte);
            }
        }
    }
}

impl TypeDef {
    pub fn of<T: EncodeTypeDef + ?Sized>() -> Self {
        let mut type_def = TypeDef::default();
        T::encode_type_def(&mut type_def);
        type_def
    }

    pub(crate) fn bytes(&self) -> &[u8] {
        &self.bytes
    }

    pub(crate) fn heap_ref(&mut self) {
        self.push_tag(TypeTag::HeapRef);
    }

    /// The wire type for an exported Rust struct passed or returned by value.
    /// On the wire it behaves exactly like a [`heap_ref`](Self::heap_ref) (the
    /// object wrapper rides the JS heap), but the distinct tag lets JS apply
    /// wasm-bindgen's moved-value semantics: passing the wrapper by value
    /// transfers ownership to Rust, so JS zeroes the wrapper's handle and a later
    /// use throws "Attempt to use a moved value".
    #[doc(hidden)]
    pub fn rust_value(&mut self, class_name: &str) {
        self.push_tag(TypeTag::RustValue);
        // The class name lets JS find an inheritance descendant's per-class
        // ancestor slot, so a by-value pass of a descendant as its ancestor can
        // be rejected (the descendant's own handle differs from the ancestor
        // view's). A non-participating struct has no such slot, so the check is a
        // no-op for it.
        self.push_str(class_name);
    }

    #[doc(hidden)]
    pub fn borrowed_ref(&mut self) {
        self.push_tag(TypeTag::BorrowedRef);
    }

    /// A borrowed `&T` to an exported struct: the routed object handle rides the
    /// wire as a plain `u32` (like a method receiver), so no borrow-stack
    /// round-trip is needed to read it. `class_name` lets JS route an inheritance
    /// descendant passed as `&Ancestor` to its shared ancestor-view handle.
    #[doc(hidden)]
    pub fn rust_borrow(&mut self, class_name: &str) {
        self.push_tag(TypeTag::RustBorrow);
        self.push_str(class_name);
    }

    /// Build the type def of `T` and, if it is an exported struct (`RustValue`
    /// tag), return its class name. Used to forward an exported struct's class
    /// name onto a borrowed `&T` argument so JS can route inheritance descendants
    /// to their ancestor view.
    #[doc(hidden)]
    pub fn rust_value_class_name<T: EncodeTypeDef + ?Sized>() -> Option<alloc::string::String> {
        let def = TypeDef::of::<T>();
        let bytes = def.bytes();
        if bytes.first().copied() != Some(TypeTag::RustValue as u8) {
            return None;
        }
        let len_bytes = bytes.get(1..5)?;
        let len = u32::from_le_bytes(len_bytes.try_into().ok()?) as usize;
        let name_bytes = bytes.get(5..5 + len)?;
        core::str::from_utf8(name_bytes).ok().map(Into::into)
    }

    #[doc(hidden)]
    pub fn u8_clamped(&mut self) {
        self.push_tag(TypeTag::U8Clamped);
    }

    /// A mutable array (`&mut [T]`): the inner array type def follows (an
    /// `Array` of `T`). JS copies the mutated elements back to the caller's
    /// array after the call.
    pub fn mut_array<T: EncodeTypeDef + ?Sized>(&mut self) {
        self.push_tag(TypeTag::MutArray);
        self.push_tag(TypeTag::Array);
        T::encode_type_def(self);
    }

    /// A mutable clamped array (`Clamped<&mut [u8]>`). The inner array type is a
    /// `U8Clamped` (the element is always `u8`); JS copies the mutated bytes back.
    pub fn mut_u8_clamped(&mut self) {
        self.push_tag(TypeTag::MutArray);
        self.push_tag(TypeTag::U8Clamped);
    }

    pub fn string_enum(&mut self, variants: &[&str]) {
        self.push_tag(TypeTag::StringEnum);
        self.push_u8(u8::try_from(variants.len()).expect("too many string enum variants"));
        for variant in variants {
            self.push_str(variant);
        }
    }

    /// A C-style enum: JS validates that a value is one of `values` (decoded as
    /// `i32` when `signed`, else `u32`) so a non-enum value is rejected rather
    /// than silently coerced.
    pub fn numeric_enum(&mut self, signed: bool, values: &[u32]) {
        self.push_tag(TypeTag::NumericEnum);
        self.push_u8(signed as u8);
        self.push_u8(u8::try_from(values.len()).expect("too many numeric enum variants"));
        for value in values {
            self.bytes.extend_from_slice(&value.to_le_bytes());
        }
    }

    #[doc(hidden)]
    pub fn dynamic_union(
        &mut self,
        variant_count: usize,
        encode_variants: impl FnOnce(&mut TypeDef),
    ) {
        self.push_tag(TypeTag::DynamicUnion);
        self.push_u8(u8::try_from(variant_count).expect("too many dynamic union variants"));
        encode_variants(self);
    }

    #[doc(hidden)]
    pub fn dynamic_union_string_variant(&mut self, value: &str) {
        self.push_u8(0);
        self.push_str(value);
    }

    #[doc(hidden)]
    pub fn dynamic_union_type_variant<T: EncodeTypeDef>(&mut self) {
        self.push_u8(1);
        T::encode_type_def(self);
    }

    #[doc(hidden)]
    pub fn callback<Signature: EncodeTypeDef + ?Sized>(&mut self) {
        self.push_tag(TypeTag::Callback);
        Signature::encode_type_def(self);
    }

    #[doc(hidden)]
    pub fn callback_with_signature(
        &mut self,
        arg_count: u8,
        encode_args_and_return: impl FnOnce(&mut TypeDef),
    ) {
        self.push_tag(TypeTag::Callback);
        self.push_u8(arg_count);
        encode_args_and_return(self);
    }

    fn push_tag(&mut self, tag: TypeTag) {
        self.push_u8(tag as u8);
    }

    fn push_u8(&mut self, value: u8) {
        self.bytes.push(value);
    }

    fn push_str(&mut self, value: &str) {
        self.bytes
            .extend_from_slice(&(value.len() as u32).to_le_bytes());
        self.bytes.extend_from_slice(value.as_bytes());
    }
}

pub trait EncodeTypeDef {
    fn encode_type_def(type_def: &mut TypeDef);
}

impl EncodeTypeDef for () {
    fn encode_type_def(type_def: &mut TypeDef) {
        type_def.push_tag(TypeTag::Undefined);
    }
}

impl BinaryEncode for () {
    fn encode(self, _encoder: &mut EncodedData) {}
}

impl BinaryDecode for () {
    fn decode(_decoder: &mut DecodedData) -> Result<Self, DecodeError> {
        Ok(())
    }
}

macro_rules! impl_num {
    ($ty:ty, $tag:ident, $push:ident, $take:ident) => {
        impl EncodeTypeDef for $ty {
            fn encode_type_def(type_def: &mut TypeDef) {
                type_def.push_tag(TypeTag::$tag);
            }
        }

        impl BinaryEncode for $ty {
            fn encode(self, encoder: &mut EncodedData) {
                encoder.$push(self as _);
            }
        }

        impl BinaryDecode for $ty {
            fn decode(decoder: &mut DecodedData) -> Result<Self, DecodeError> {
                Ok(decoder.$take()? as $ty)
            }
        }
    };
}

impl EncodeTypeDef for bool {
    fn encode_type_def(type_def: &mut TypeDef) {
        type_def.push_tag(TypeTag::Bool);
    }
}

impl BinaryEncode for bool {
    fn encode(self, encoder: &mut EncodedData) {
        encoder.push_u8(if self { 1 } else { 0 });
    }
}

impl BinaryDecode for bool {
    fn decode(decoder: &mut DecodedData) -> Result<Self, DecodeError> {
        Ok(decoder.take_u8()? != 0)
    }
}

impl EncodeTypeDef for char {
    fn encode_type_def(type_def: &mut TypeDef) {
        // The wire payload is the u32 code point, but JS converts to/from a 1-char
        // string (matching wasm-bindgen) via the `Char` type tag.
        type_def.push_tag(TypeTag::Char);
    }
}

impl BinaryEncode for char {
    fn encode(self, encoder: &mut EncodedData) {
        encoder.push_u32(self as u32);
    }
}

impl BinaryDecode for char {
    fn decode(decoder: &mut DecodedData) -> Result<Self, DecodeError> {
        let cp = decoder.take_u32()?;
        char::from_u32(cp).ok_or_else(|| {
            DecodeError::custom(alloc::format!(
                "expected a valid Unicode scalar value, found {cp}"
            ))
        })
    }
}

impl_num!(u8, U8, push_u8, take_u8);
impl_num!(u16, U16, push_u16, take_u16);
impl_num!(u32, U32, push_u32, take_u32);
impl_num!(u64, U64, push_u64, take_u64);
impl_num!(u128, U128, push_u128, take_u128);
impl_num!(i8, I8, push_u8, take_u8);
impl_num!(i16, I16, push_u16, take_u16);
impl_num!(i32, I32, push_u32, take_u32);
impl_num!(i64, I64, push_u64, take_u64);
impl_num!(i128, I128, push_u128, take_u128);

impl EncodeTypeDef for f32 {
    fn encode_type_def(type_def: &mut TypeDef) {
        type_def.push_tag(TypeTag::F32);
    }
}

impl BinaryEncode for f32 {
    fn encode(self, encoder: &mut EncodedData) {
        encoder.push_u32(self.to_bits());
    }
}

impl BinaryDecode for f32 {
    fn decode(decoder: &mut DecodedData) -> Result<Self, DecodeError> {
        Ok(f32::from_bits(decoder.take_u32()?))
    }
}

impl EncodeTypeDef for f64 {
    fn encode_type_def(type_def: &mut TypeDef) {
        type_def.push_tag(TypeTag::F64);
    }
}

impl BinaryEncode for f64 {
    fn encode(self, encoder: &mut EncodedData) {
        encoder.push_u64(self.to_bits());
    }
}

impl BinaryDecode for f64 {
    fn decode(decoder: &mut DecodedData) -> Result<Self, DecodeError> {
        Ok(f64::from_bits(decoder.take_u64()?))
    }
}

impl EncodeTypeDef for usize {
    fn encode_type_def(type_def: &mut TypeDef) {
        type_def.push_tag(TypeTag::Usize);
    }
}

impl BinaryEncode for usize {
    fn encode(self, encoder: &mut EncodedData) {
        encoder.push_u64(self as u64);
    }
}

impl BinaryDecode for usize {
    fn decode(decoder: &mut DecodedData) -> Result<Self, DecodeError> {
        Ok(decoder.take_u64()? as usize)
    }
}

impl EncodeTypeDef for isize {
    fn encode_type_def(type_def: &mut TypeDef) {
        type_def.push_tag(TypeTag::Isize);
    }
}

impl BinaryEncode for isize {
    fn encode(self, encoder: &mut EncodedData) {
        encoder.push_u64(self as u64);
    }
}

impl BinaryDecode for isize {
    fn decode(decoder: &mut DecodedData) -> Result<Self, DecodeError> {
        Ok(decoder.take_u64()? as isize)
    }
}

impl EncodeTypeDef for str {
    fn encode_type_def(type_def: &mut TypeDef) {
        type_def.push_tag(TypeTag::String);
    }
}

impl EncodeTypeDef for &str {
    fn encode_type_def(type_def: &mut TypeDef) {
        str::encode_type_def(type_def);
    }
}

impl<T: JsRefEncode + ?Sized> EncodeTypeDef for &T {
    fn encode_type_def(type_def: &mut TypeDef) {
        type_def.borrowed_ref();
    }
}

impl BinaryEncode for &str {
    fn encode(self, encoder: &mut EncodedData) {
        encoder.push_str(self);
    }
}

impl<T: JsRefEncode + ?Sized> BinaryEncode for &T {
    fn encode(self, encoder: &mut EncodedData) {
        self.js_ref().raw().encode(encoder);
    }
}

impl EncodeTypeDef for String {
    fn encode_type_def(type_def: &mut TypeDef) {
        str::encode_type_def(type_def);
    }
}

impl BinaryEncode for String {
    fn encode(self, encoder: &mut EncodedData) {
        encoder.push_str(&self);
    }
}

impl BinaryDecode for String {
    fn decode(decoder: &mut DecodedData) -> Result<Self, DecodeError> {
        Ok(decoder.take_str()?.to_string())
    }
}

impl<T: EncodeTypeDef> EncodeTypeDef for Option<T> {
    fn encode_type_def(type_def: &mut TypeDef) {
        type_def.push_tag(TypeTag::Option);
        T::encode_type_def(type_def);
    }
}

impl<T: BinaryDecode> BinaryDecode for Option<T> {
    fn decode(decoder: &mut DecodedData) -> Result<Self, DecodeError> {
        if decoder.take_u8()? != 0 {
            Ok(Some(T::decode(decoder)?))
        } else {
            Ok(None)
        }
    }
}

impl<T: BinaryEncode> BinaryEncode for Option<T> {
    fn encode(self, encoder: &mut EncodedData) {
        match self {
            Some(value) => {
                encoder.push_u8(1);
                value.encode(encoder);
            }
            None => encoder.push_u8(0),
        }
    }
}

impl<T: EncodeTypeDef, E: EncodeTypeDef> EncodeTypeDef for Result<T, E> {
    fn encode_type_def(type_def: &mut TypeDef) {
        type_def.push_tag(TypeTag::Result);
        T::encode_type_def(type_def);
        E::encode_type_def(type_def);
    }
}

impl<T: BinaryEncode, E: BinaryEncode> BinaryEncode for Result<T, E> {
    fn encode(self, encoder: &mut EncodedData) {
        match self {
            Ok(value) => {
                encoder.push_u8(1);
                value.encode(encoder);
            }
            Err(error) => {
                encoder.push_u8(0);
                error.encode(encoder);
            }
        }
    }
}

impl<T: BinaryDecode, E: BinaryDecode> BinaryDecode for Result<T, E> {
    fn decode(decoder: &mut DecodedData) -> Result<Self, DecodeError> {
        if decoder.take_u8()? != 0 {
            Ok(Ok(T::decode(decoder)?))
        } else {
            Ok(Err(E::decode(decoder)?))
        }
    }
}

/// A `Result` returned from an exported Rust function. The wire payload is
/// identical to `Result`, but the distinct type tag tells JS to throw the `Err`
/// value as an exception instead of returning a `{err}` object, matching
/// wasm-bindgen's behavior for fallible exports.
pub struct ThrowingResult<T, E>(pub Result<T, E>);

impl<T: EncodeTypeDef, E: EncodeTypeDef> EncodeTypeDef for ThrowingResult<T, E> {
    fn encode_type_def(type_def: &mut TypeDef) {
        type_def.push_tag(TypeTag::ThrowingResult);
        T::encode_type_def(type_def);
        E::encode_type_def(type_def);
    }
}

impl<T: BinaryEncode, E: BinaryEncode> BinaryEncode for ThrowingResult<T, E> {
    fn encode(self, encoder: &mut EncodedData) {
        self.0.encode(encoder);
    }
}

impl<T: EncodeTypeDef> EncodeTypeDef for Vec<T> {
    fn encode_type_def(type_def: &mut TypeDef) {
        type_def.push_tag(TypeTag::Array);
        T::encode_type_def(type_def);
    }
}

impl<T: EncodeTypeDef> EncodeTypeDef for &[T] {
    fn encode_type_def(type_def: &mut TypeDef) {
        type_def.push_tag(TypeTag::Array);
        T::encode_type_def(type_def);
    }
}

impl<T: EncodeTypeDef> EncodeTypeDef for &mut [T] {
    fn encode_type_def(type_def: &mut TypeDef) {
        type_def.mut_array::<T>();
    }
}

impl<T: EncodeTypeDef> EncodeTypeDef for Box<[T]> {
    fn encode_type_def(type_def: &mut TypeDef) {
        type_def.push_tag(TypeTag::Array);
        T::encode_type_def(type_def);
    }
}

/// The wire form of a `&mut [T]` export argument. JS sends the array (under the
/// `MutArray` tag), Rust decodes it into an owned buffer the export mutates, and
/// the mutated buffer is copied back to JS in the response (`write_back`). The
/// export codegen advertises this type, decodes it, mutably borrows `buffer`,
/// then re-encodes it after the return value.
pub struct MutSliceArg<T> {
    buffer: Vec<T>,
}

impl<T: EncodeTypeDef> EncodeTypeDef for MutSliceArg<T> {
    fn encode_type_def(type_def: &mut TypeDef) {
        type_def.mut_array::<T>();
    }
}

impl<T: BinaryDecode> BinaryDecode for MutSliceArg<T> {
    fn decode(decoder: &mut DecodedData) -> Result<Self, DecodeError> {
        Ok(MutSliceArg {
            buffer: Vec::<T>::decode(decoder)?,
        })
    }
}

impl<T> MutSliceArg<T> {
    pub(crate) fn as_mut_slice(&mut self) -> &mut [T] {
        self.buffer.as_mut_slice()
    }

    /// Append the (possibly mutated) elements to the export response so JS can
    /// copy them back into the caller's array.
    pub(crate) fn write_back(self, encoder: &mut EncodedData)
    where
        T: BinaryEncode,
    {
        encoder.push_u32(self.buffer.len() as u32);
        for val in self.buffer {
            val.encode(encoder);
        }
    }
}

impl<T> core::ops::Deref for MutSliceArg<T> {
    type Target = [T];

    fn deref(&self) -> &[T] {
        self.buffer.as_slice()
    }
}

impl<T> core::ops::DerefMut for MutSliceArg<T> {
    fn deref_mut(&mut self) -> &mut [T] {
        self.buffer.as_mut_slice()
    }
}

impl<T: BinaryEncode> BinaryEncode for Box<[T]> {
    fn encode(self, encoder: &mut EncodedData) {
        encoder.push_u32(self.len() as u32);
        for val in self.into_vec() {
            val.encode(encoder);
        }
    }
}

impl<T: BinaryEncode> BinaryEncode for Vec<T> {
    fn encode(self, encoder: &mut EncodedData) {
        encoder.push_u32(self.len() as u32);
        for val in self {
            val.encode(encoder);
        }
    }
}

impl<T: BinaryDecode> BinaryDecode for Vec<T> {
    fn decode(decoder: &mut DecodedData) -> Result<Self, DecodeError> {
        let len = decoder.take_u32()? as usize;
        let mut vec = Vec::with_capacity(len);
        for _ in 0..len {
            // A failed element decode means JS supplied an array element of the
            // wrong type; report it with wasm-bindgen's message.
            let item = T::decode(decoder)
                .map_err(|_| DecodeError::custom("array contains a value of the wrong type"))?;
            vec.push(item);
        }
        Ok(vec)
    }
}

impl<T: BinaryDecode> BinaryDecode for Box<[T]> {
    fn decode(decoder: &mut DecodedData) -> Result<Self, DecodeError> {
        Ok(Vec::<T>::decode(decoder)?.into_boxed_slice())
    }
}

macro_rules! ref_encode_via_clone {
    ($($ty:ty),* $(,)?) => {
        $(
            impl EncodeTypeDef for &$ty {
                fn encode_type_def(type_def: &mut TypeDef) {
                    <$ty as EncodeTypeDef>::encode_type_def(type_def);
                }
            }

            impl BinaryEncode for &$ty {
                fn encode(self, encoder: &mut EncodedData) {
                    self.clone().encode(encoder);
                }
            }
        )*
    };
}

ref_encode_via_clone!(
    bool, char, u8, u16, u32, u64, u128, i8, i16, i32, i64, i128, f32, f64, usize, isize, String,
);

/// Register the write-back for a `&mut [T]` argument passed to a JS import.
///
/// wry has no shared linear memory, so a JS function that mutates a `&mut [T]`
/// argument cannot write into the Rust slice directly. Instead the receiver (JS)
/// appends the mutated array after the call's return value, and this queues a
/// closure that — once the return value is decoded — reads the array back and
/// copies it into the original slice. The whole encode -> call -> decode ->
/// write-back runs synchronously inside `run_js_sync`, so the raw slice pointer
/// captured here stays valid until the write-back runs.
fn register_slice_write_back<T: BinaryDecode + 'static>(slice: &mut [T]) {
    let raw = slice as *mut [T];
    crate::batch::push_write_back(Box::new(move |decoder: &mut DecodedData| {
        let updated = Vec::<T>::decode(decoder).expect("failed to decode &mut [T] write-back");
        // SAFETY: The raw pointer was captured from the original slice, and the write-back runs synchronously inside `run_js_sync` after the return value is decoded, so the original slice is still valid and uniquely borrowed when we write back into it.
        let target = unsafe { &mut *raw };
        for (dst, src) in target.iter_mut().zip(updated) {
            *dst = src;
        }
    }));
}

macro_rules! slice_encode_via_copy {
    ($($ty:ty),* $(,)?) => {
        $(
            impl BinaryEncode for &[$ty] {
                fn encode(self, encoder: &mut EncodedData) {
                    encoder.push_u32(self.len() as u32);
                    for val in self {
                        (*val).encode(encoder);
                    }
                }
            }

            impl BinaryEncode for &mut [$ty] {
                fn encode(self, encoder: &mut EncodedData) {
                    encoder.push_u32(self.len() as u32);
                    for val in self.iter() {
                        (*val).encode(encoder);
                    }
                    register_slice_write_back(self);
                }
            }
        )*
    };
}

slice_encode_via_copy!(
    bool, char, u8, u16, u32, u64, u128, i8, i16, i32, i64, i128, f32, f64, usize, isize
);

// A `&[String]` argument (e.g. a `slice_to_array` import taking `&[String]`).
// `String` is neither a copy-primitive nor a handle type, so it falls outside
// both the primitive and `JsRefEncode` slice impls; each element is cloned and
// encoded as a length-prefixed UTF-8 string, matching `Vec<String>`.
impl BinaryEncode for &[String] {
    fn encode(self, encoder: &mut EncodedData) {
        encoder.push_u32(self.len() as u32);
        for val in self {
            val.clone().encode(encoder);
        }
    }
}

impl BinaryEncode for &mut [String] {
    fn encode(self, encoder: &mut EncodedData) {
        encoder.push_u32(self.len() as u32);
        for val in self.iter() {
            val.clone().encode(encoder);
        }
        register_slice_write_back(self);
    }
}

impl<T: JsRefEncode> BinaryEncode for &[T] {
    fn encode(self, encoder: &mut EncodedData) {
        encoder.push_u32(self.len() as u32);
        for val in self {
            val.js_ref().raw().encode(encoder);
        }
    }
}

impl<T: JsRefEncode + BinaryDecode + 'static> BinaryEncode for &mut [T] {
    fn encode(self, encoder: &mut EncodedData) {
        encoder.push_u32(self.len() as u32);
        for val in self.iter() {
            val.js_ref().raw().encode(encoder);
        }
        register_slice_write_back(self);
    }
}

macro_rules! impl_fn_type_def {
    (0,) => {
        impl<R: EncodeTypeDef> EncodeTypeDef for fn() -> R {
            fn encode_type_def(type_def: &mut TypeDef) {
                type_def.push_u8(0);
                R::encode_type_def(type_def);
            }
        }
    };
    ($n:expr, $($T:ident),+) => {
        impl<$($T: EncodeTypeDef,)+ R: EncodeTypeDef> EncodeTypeDef for fn($($T),+) -> R {
            fn encode_type_def(type_def: &mut TypeDef) {
                type_def.push_u8($n);
                $($T::encode_type_def(type_def);)+
                R::encode_type_def(type_def);
            }
        }
    };
}

impl_fn_type_def!(0,);
impl_fn_type_def!(1, T1);
impl_fn_type_def!(2, T1, T2);
impl_fn_type_def!(3, T1, T2, T3);
impl_fn_type_def!(4, T1, T2, T3, T4);
impl_fn_type_def!(5, T1, T2, T3, T4, T5);
impl_fn_type_def!(6, T1, T2, T3, T4, T5, T6);
impl_fn_type_def!(7, T1, T2, T3, T4, T5, T6, T7);
impl_fn_type_def!(8, T1, T2, T3, T4, T5, T6, T7, T8);
impl_fn_type_def!(9, T1, T2, T3, T4, T5, T6, T7, T8, T9);
impl_fn_type_def!(10, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10);
impl_fn_type_def!(11, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11);
impl_fn_type_def!(12, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12);
impl_fn_type_def!(13, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13);
impl_fn_type_def!(
    14, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14
);
impl_fn_type_def!(
    15, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15
);
impl_fn_type_def!(
    16, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16
);
impl_fn_type_def!(
    17, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17
);
impl_fn_type_def!(
    18, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18
);
impl_fn_type_def!(
    19, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19
);
impl_fn_type_def!(
    20, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20
);
impl_fn_type_def!(
    21, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20,
    T21
);
impl_fn_type_def!(
    22, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20,
    T21, T22
);
impl_fn_type_def!(
    23, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20,
    T21, T22, T23
);
impl_fn_type_def!(
    24, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20,
    T21, T22, T23, T24
);
impl_fn_type_def!(
    25, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20,
    T21, T22, T23, T24, T25
);
impl_fn_type_def!(
    26, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20,
    T21, T22, T23, T24, T25, T26
);
impl_fn_type_def!(
    27, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20,
    T21, T22, T23, T24, T25, T26, T27
);
impl_fn_type_def!(
    28, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20,
    T21, T22, T23, T24, T25, T26, T27, T28
);
impl_fn_type_def!(
    29, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20,
    T21, T22, T23, T24, T25, T26, T27, T28, T29
);
impl_fn_type_def!(
    30, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20,
    T21, T22, T23, T24, T25, T26, T27, T28, T29, T30
);
impl_fn_type_def!(
    31, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20,
    T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31
);
impl_fn_type_def!(
    32, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20,
    T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32
);