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
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
//! Rust API wrappers for the `TypedArray` Builtin ECMAScript Objects
use crate::{
    builtins::typed_array::BuiltinTypedArray,
    builtins::{typed_array::TypedArray, BuiltInConstructor},
    error::JsNativeError,
    object::{JsArrayBuffer, JsFunction, JsObject, JsObjectType},
    value::{IntoOrUndefined, TryFromJs},
    Context, JsResult, JsString, JsValue,
};
use boa_gc::{Finalize, Trace};
use std::ops::Deref;

/// `JsTypedArray` provides a wrapper for Boa's implementation of the ECMAScript `TypedArray`
/// builtin object.
#[derive(Debug, Clone, Trace, Finalize)]
pub struct JsTypedArray {
    inner: JsObject,
}

impl JsTypedArray {
    /// Create a [`JsTypedArray`] from a [`JsObject`], if the object is not a typed array throw a
    /// `TypeError`.
    ///
    /// This does not clone the fields of the typed array, it only does a shallow clone of the
    /// object.
    #[inline]
    pub fn from_object(object: JsObject) -> JsResult<Self> {
        if object.is::<TypedArray>() {
            Ok(Self { inner: object })
        } else {
            Err(JsNativeError::typ()
                .with_message("object is not a TypedArray")
                .into())
        }
    }

    /// Get the length of the array.
    ///
    /// Same as `array.length` in JavaScript.
    #[inline]
    pub fn length(&self, context: &mut Context) -> JsResult<usize> {
        Ok(
            BuiltinTypedArray::length(&self.inner.clone().into(), &[], context)?
                .as_number()
                .map(|x| x as usize)
                .expect("length should return a number"),
        )
    }

    /// Check if the array is empty, i.e. the `length` is zero.
    #[inline]
    pub fn is_empty(&self, context: &mut Context) -> JsResult<bool> {
        Ok(self.length(context)? == 0)
    }

    /// Calls `TypedArray.prototype.at()`.
    pub fn at<T>(&self, index: T, context: &mut Context) -> JsResult<JsValue>
    where
        T: Into<i64>,
    {
        BuiltinTypedArray::at(&self.inner.clone().into(), &[index.into().into()], context)
    }

    /// Returns the `ArrayBuffer` referenced by this typed array at construction time.
    ///
    /// Calls `TypedArray.prototype.buffer()`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use boa_engine::{js_string, JsResult, object::{builtins::{JsUint8Array, JsArrayBuffer}}, property::{PropertyKey}, JsValue, Context};
    /// # fn main() -> JsResult<()> {
    ///
    /// let context = &mut Context::default();
    /// let array_buffer8 = JsArrayBuffer::new(8, context)?;
    /// let array = JsUint8Array::from_array_buffer(array_buffer8, context)?;
    /// assert_eq!(
    ///     array.buffer(context)?.as_object().unwrap().get(PropertyKey::String(js_string!("byteLength")), context).unwrap(),
    ///     JsValue::new(8)
    /// );
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn buffer(&self, context: &mut Context) -> JsResult<JsValue> {
        BuiltinTypedArray::buffer(&self.inner.clone().into(), &[], context)
    }

    /// Returns `TypedArray.prototype.byteLength`.
    #[inline]
    pub fn byte_length(&self, context: &mut Context) -> JsResult<usize> {
        Ok(
            BuiltinTypedArray::byte_length(&self.inner.clone().into(), &[], context)?
                .as_number()
                .map(|x| x as usize)
                .expect("byteLength should return a number"),
        )
    }

    /// Returns `TypedArray.prototype.byteOffset`.
    #[inline]
    pub fn byte_offset(&self, context: &mut Context) -> JsResult<usize> {
        Ok(
            BuiltinTypedArray::byte_offset(&self.inner.clone().into(), &[], context)?
                .as_number()
                .map(|x| x as usize)
                .expect("byteLength should return a number"),
        )
    }

    /// Function that created the instance object. It is the hidden `TypedArray` constructor function,
    /// but each typed array subclass also defines its own constructor property.
    ///
    /// Returns `TypedArray.prototype.constructor`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use boa_engine::{JsResult, object::{builtins::JsUint8Array}, JsNativeError, Context};
    /// # fn main() -> JsResult<()> {
    ///
    /// let context = &mut Context::default();
    /// let array = JsUint8Array::from_iter(vec![1, 2, 3, 4, 5], context)?;
    /// assert_eq!(
    ///     Err(JsNativeError::typ()
    ///         .with_message("the TypedArray constructor should never be called directly")
    ///         .into()),
    ///     array.constructor(context)
    /// );
    ///
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn constructor(&self, context: &mut Context) -> JsResult<JsValue> {
        BuiltinTypedArray::constructor(&self.inner.clone().into(), &[], context)
    }

    /// Shallow copies part of this typed array to another location in the same typed
    /// array and returns this typed array without modifying its length.
    ///
    /// Returns `TypedArray.prototype.copyWithin()`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use boa_engine::{JsResult, JsValue, object::{builtins::{JsUint8Array}}, Context};
    /// # fn main() -> JsResult<()> {
    ///
    /// let context = &mut Context::default();
    /// let array = JsUint8Array::from_iter(vec![1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8, 8u8], context)?;
    /// array.copy_within(3, 1, Some(3), context)?;
    /// assert_eq!(array.get(0, context)?, JsValue::new(1.0));
    /// assert_eq!(array.get(1, context)?, JsValue::new(2.0));
    /// assert_eq!(array.get(2, context)?, JsValue::new(3.0));
    /// assert_eq!(array.get(3, context)?, JsValue::new(2.0));
    /// assert_eq!(array.get(4, context)?, JsValue::new(3.0));
    /// assert_eq!(array.get(5, context)?, JsValue::new(6.0));
    /// assert_eq!(array.get(6, context)?, JsValue::new(7.0));
    /// assert_eq!(array.get(7, context)?, JsValue::new(8.0));
    ///
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn copy_within<T>(
        &self,
        target: T,
        start: u64,
        end: Option<u64>,
        context: &mut Context,
    ) -> JsResult<Self>
    where
        T: Into<JsValue>,
    {
        let object = BuiltinTypedArray::copy_within(
            &self.inner.clone().into(),
            &[target.into(), start.into(), end.into_or_undefined()],
            context,
        )?;

        Ok(Self {
            inner: object
                .as_object()
                .cloned()
                .expect("`copyWithin` must always return a `TypedArray` on success"),
        })
    }

    /// Calls `TypedArray.prototype.fill()`.
    pub fn fill<T>(
        &self,
        value: T,
        start: Option<usize>,
        end: Option<usize>,
        context: &mut Context,
    ) -> JsResult<Self>
    where
        T: Into<JsValue>,
    {
        BuiltinTypedArray::fill(
            &self.inner.clone().into(),
            &[
                value.into(),
                start.into_or_undefined(),
                end.into_or_undefined(),
            ],
            context,
        )?;
        Ok(self.clone())
    }

    /// Calls `TypedArray.prototype.every()`.
    pub fn every(
        &self,
        predicate: JsFunction,
        this_arg: Option<JsValue>,
        context: &mut Context,
    ) -> JsResult<bool> {
        let result = BuiltinTypedArray::every(
            &self.inner.clone().into(),
            &[predicate.into(), this_arg.into_or_undefined()],
            context,
        )?
        .as_boolean()
        .expect("TypedArray.prototype.every should always return boolean");

        Ok(result)
    }

    /// Calls `TypedArray.prototype.some()`.
    #[inline]
    pub fn some(
        &self,
        callback: JsFunction,
        this_arg: Option<JsValue>,
        context: &mut Context,
    ) -> JsResult<bool> {
        let result = BuiltinTypedArray::some(
            &self.inner.clone().into(),
            &[callback.into(), this_arg.into_or_undefined()],
            context,
        )?
        .as_boolean()
        .expect("TypedArray.prototype.some should always return boolean");

        Ok(result)
    }

    /// Calls `TypedArray.prototype.sort()`.
    #[inline]
    pub fn sort(&self, compare_fn: Option<JsFunction>, context: &mut Context) -> JsResult<Self> {
        BuiltinTypedArray::sort(
            &self.inner.clone().into(),
            &[compare_fn.into_or_undefined()],
            context,
        )?;

        Ok(self.clone())
    }

    /// Returns a new typed array on the same `ArrayBuffer` store and with the same element
    /// types as for this typed array.
    /// The begin offset is inclusive and the end offset is exclusive.
    ///
    /// Calls `TypedArray.prototype.subarray()`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use boa_engine::{JsResult, object::{builtins::JsUint8Array}, JsValue, Context};
    /// # fn main() -> JsResult<()> {
    ///
    /// let context = &mut Context::default();
    /// let array = JsUint8Array::from_iter(vec![1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8, 8u8], context)?;
    /// let subarray2_6 = array.subarray(2, 6, context)?;
    /// assert_eq!(subarray2_6.length(context)?, 4);
    /// assert_eq!(subarray2_6.get(0, context)?, JsValue::new(3.0));
    /// assert_eq!(subarray2_6.get(1, context)?, JsValue::new(4.0));
    /// assert_eq!(subarray2_6.get(2, context)?, JsValue::new(5.0));
    /// assert_eq!(subarray2_6.get(3, context)?, JsValue::new(6.0));
    /// let subarray4_6 = array.subarray(-4, 6, context)?;
    /// assert_eq!(subarray4_6.length(context)?, 2);
    /// assert_eq!(subarray4_6.get(0, context)?, JsValue::new(5.0));
    /// assert_eq!(subarray4_6.get(1, context)?, JsValue::new(6.0));
    ///
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn subarray(&self, begin: i64, end: i64, context: &mut Context) -> JsResult<Self> {
        let subarray = BuiltinTypedArray::subarray(
            &self.inner.clone().into(),
            &[begin.into(), end.into()],
            context,
        )?;

        Ok(Self {
            inner: subarray
                .as_object()
                .cloned()
                .expect("`subarray` must always return a `TypedArray` on success"),
        })
    }

    /// Calls `TypedArray.prototype.toLocaleString()`
    #[inline]
    pub fn to_locale_string(
        &self,
        reserved1: Option<JsValue>,
        reserved2: Option<JsValue>,
        context: &mut Context,
    ) -> JsResult<JsValue> {
        BuiltinTypedArray::to_locale_string(
            &self.inner.clone().into(),
            &[reserved1.into_or_undefined(), reserved2.into_or_undefined()],
            context,
        )
    }

    /// Calls `TypedArray.prototype.filter()`.
    #[inline]
    pub fn filter(
        &self,
        callback: JsFunction,
        this_arg: Option<JsValue>,
        context: &mut Context,
    ) -> JsResult<Self> {
        let object = BuiltinTypedArray::filter(
            &self.inner.clone().into(),
            &[callback.into(), this_arg.into_or_undefined()],
            context,
        )?;

        Ok(Self {
            inner: object
                .as_object()
                .cloned()
                .expect("`filter` must always return a `TypedArray` on success"),
        })
    }

    /// Calls `TypedArray.prototype.map()`.
    #[inline]
    pub fn map(
        &self,
        callback: JsFunction,
        this_arg: Option<JsValue>,
        context: &mut Context,
    ) -> JsResult<Self> {
        let object = BuiltinTypedArray::map(
            &self.inner.clone().into(),
            &[callback.into(), this_arg.into_or_undefined()],
            context,
        )?;

        Ok(Self {
            inner: object
                .as_object()
                .cloned()
                .expect("`map` must always return a `TypedArray` on success"),
        })
    }

    /// Calls `TypedArray.prototype.reduce()`.
    #[inline]
    pub fn reduce(
        &self,
        callback: JsFunction,
        initial_value: Option<JsValue>,
        context: &mut Context,
    ) -> JsResult<JsValue> {
        BuiltinTypedArray::reduce(
            &self.inner.clone().into(),
            &[callback.into(), initial_value.into_or_undefined()],
            context,
        )
    }

    /// Calls `TypedArray.prototype.reduceRight()`.
    #[inline]
    pub fn reduce_right(
        &self,
        callback: JsFunction,
        initial_value: Option<JsValue>,
        context: &mut Context,
    ) -> JsResult<JsValue> {
        BuiltinTypedArray::reduceright(
            &self.inner.clone().into(),
            &[callback.into(), initial_value.into_or_undefined()],
            context,
        )
    }

    /// Calls `TypedArray.prototype.reverse()`.
    #[inline]
    pub fn reverse(&self, context: &mut Context) -> JsResult<Self> {
        BuiltinTypedArray::reverse(&self.inner.clone().into(), &[], context)?;
        Ok(self.clone())
    }

    /// Stores multiple values in the typed array, reading input values from a specified array.
    ///
    /// Returns `TypedArray.prototype.set()`.
    ///
    ///
    /// # Examples
    ///
    /// ```
    /// # use boa_engine::{JsResult, object::{builtins::{JsUint8Array, JsArray, JsArrayBuffer}}, JsValue, Context};
    /// # fn main() -> JsResult<()> {
    ///
    /// let context = &mut Context::default();
    /// let array_buffer8 = JsArrayBuffer::new(8, context)?;
    /// let initialized8_array = JsUint8Array::from_array_buffer(array_buffer8, context)?;
    /// initialized8_array.set_values(
    ///   JsArray::from_iter(vec![JsValue::new(1), JsValue::new(2)], context).into(),
    ///   Some(3),
    ///   context,
    /// )?;
    /// assert_eq!(initialized8_array.get(0, context)?, JsValue::new(0));
    /// assert_eq!(initialized8_array.get(1, context)?, JsValue::new(0));
    /// assert_eq!(initialized8_array.get(2, context)?, JsValue::new(0));
    /// assert_eq!(initialized8_array.get(3, context)?, JsValue::new(1.0));
    /// assert_eq!(initialized8_array.get(4, context)?, JsValue::new(2.0));
    /// assert_eq!(initialized8_array.get(5, context)?, JsValue::new(0));
    /// assert_eq!(initialized8_array.get(6, context)?, JsValue::new(0));
    /// assert_eq!(initialized8_array.get(7, context)?, JsValue::new(0));
    /// assert_eq!(initialized8_array.get(8, context)?, JsValue::Undefined);
    ///
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn set_values(
        &self,
        source: JsValue,
        offset: Option<u64>,
        context: &mut Context,
    ) -> JsResult<JsValue> {
        BuiltinTypedArray::set(
            &self.inner.clone().into(),
            &[source, offset.into_or_undefined()],
            context,
        )
    }

    /// Calls `TypedArray.prototype.slice()`.
    #[inline]
    pub fn slice(
        &self,
        start: Option<usize>,
        end: Option<usize>,
        context: &mut Context,
    ) -> JsResult<Self> {
        let object = BuiltinTypedArray::slice(
            &self.inner.clone().into(),
            &[start.into_or_undefined(), end.into_or_undefined()],
            context,
        )?;

        Ok(Self {
            inner: object
                .as_object()
                .cloned()
                .expect("`slice` must always return a `TypedArray` on success"),
        })
    }

    /// Calls `TypedArray.prototype.find()`.
    #[inline]
    pub fn find(
        &self,
        predicate: JsFunction,
        this_arg: Option<JsValue>,
        context: &mut Context,
    ) -> JsResult<JsValue> {
        BuiltinTypedArray::find(
            &self.inner.clone().into(),
            &[predicate.into(), this_arg.into_or_undefined()],
            context,
        )
    }

    /// Returns the index of the first element in an array that satisfies the
    /// provided testing function.
    /// If no elements satisfy the testing function, `JsResult::Ok(None)` is returned.
    ///
    /// Calls `TypedArray.prototype.findIndex()`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use boa_engine::{JsResult, object::{builtins::JsUint8Array, FunctionObjectBuilder}, NativeFunction, JsValue, Context};
    /// # fn main() -> JsResult<()> {
    /// let context = &mut Context::default();
    /// let data: Vec<u8> = (0..=255).collect();
    /// let array = JsUint8Array::from_iter(data, context)?;
    ///
    /// let greter_than_10_predicate = FunctionObjectBuilder::new(
    ///     context.realm(),
    ///     NativeFunction::from_fn_ptr(|_this, args, _context| {
    ///         let element = args
    ///             .first()
    ///             .cloned()
    ///             .unwrap_or_default()
    ///             .as_number()
    ///             .expect("error at number conversion");
    ///         Ok(JsValue::Boolean(element > 10.0))
    ///     }),
    /// )
    /// .build();
    /// assert_eq!(
    ///     array.find_index(greter_than_10_predicate, None, context),
    ///     Ok(Some(11))
    /// );
    ///
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn find_index(
        &self,
        predicate: JsFunction,
        this_arg: Option<JsValue>,
        context: &mut Context,
    ) -> JsResult<Option<u64>> {
        let index = BuiltinTypedArray::find_index(
            &self.inner.clone().into(),
            &[predicate.into(), this_arg.into_or_undefined()],
            context,
        )?
        .as_number()
        .expect("TypedArray.prototype.findIndex() should always return number");

        if index >= 0.0 {
            Ok(Some(index as u64))
        } else {
            Ok(None)
        }
    }

    /// Iterates the typed array in reverse order and returns the value of
    /// the first element that satisfies the provided testing function.
    /// If no elements satisfy the testing function, `JsResult::Ok(None)` is returned.  
    ///
    /// Calls `TypedArray.prototype.findLast()`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use boa_engine::{JsResult, object::{builtins::JsUint8Array, FunctionObjectBuilder}, NativeFunction, JsValue, Context};
    /// # fn main() -> JsResult<()> {
    /// let context = &mut Context::default();
    /// let data: Vec<u8> = (0..=255).collect();
    /// let array = JsUint8Array::from_iter(data, context)?;
    ///
    /// let lower_than_200_predicate = FunctionObjectBuilder::new(
    ///     context.realm(),
    ///     NativeFunction::from_fn_ptr(|_this, args, _context| {
    ///         let element = args
    ///             .first()
    ///             .cloned()
    ///             .unwrap_or_default()
    ///             .as_number()
    ///             .expect("error at number conversion");
    ///         Ok(JsValue::Boolean(element < 200.0))
    ///     }),
    /// )
    /// .build();
    /// assert_eq!(
    ///     array.find_last(lower_than_200_predicate.clone(), None, context),
    ///     Ok(JsValue::Integer(199))
    /// );
    ///
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn find_last(
        &self,
        predicate: JsFunction,
        this_arg: Option<JsValue>,
        context: &mut Context,
    ) -> JsResult<JsValue> {
        BuiltinTypedArray::find_last(
            &self.inner.clone().into(),
            &[predicate.into(), this_arg.into_or_undefined()],
            context,
        )
    }

    /// Iterates the typed array in reverse order and returns the index of
    /// the first element that satisfies the provided testing function.
    /// If no elements satisfy the testing function, `JsResult::OK(None)` is returned.
    ///
    /// Calls `TypedArray.prototype.findLastIndex()`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use boa_engine::{JsResult, object::{builtins::JsUint8Array, FunctionObjectBuilder}, NativeFunction, JsValue, Context};
    /// # fn main() -> JsResult<()> {
    /// let context = &mut Context::default();
    /// let data: Vec<u8> = (0..=255).collect();
    /// let array = JsUint8Array::from_iter(data, context)?;
    ///
    /// let lower_than_200_predicate = FunctionObjectBuilder::new(
    ///     context.realm(),
    ///     NativeFunction::from_fn_ptr(|_this, args, _context| {
    ///         let element = args
    ///             .first()
    ///             .cloned()
    ///             .unwrap_or_default()
    ///             .as_number()
    ///             .expect("error at number conversion");
    ///         Ok(JsValue::Boolean(element < 200.0))
    ///     }),
    /// )
    /// .build();
    /// assert_eq!(
    ///     array.find_last(lower_than_200_predicate.clone(), None, context),
    ///     Ok(JsValue::Integer(199))
    /// );
    ///
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn find_last_index(
        &self,
        predicate: JsFunction,
        this_arg: Option<JsValue>,
        context: &mut Context,
    ) -> JsResult<Option<u64>> {
        let index = BuiltinTypedArray::find_last_index(
            &self.inner.clone().into(),
            &[predicate.into(), this_arg.into_or_undefined()],
            context,
        )?
        .as_number()
        .expect("TypedArray.prototype.findLastIndex() should always return number");

        if index >= 0.0 {
            Ok(Some(index as u64))
        } else {
            Ok(None)
        }
    }

    /// Executes a provided function once for each typed array element.
    ///
    /// Calls `TypedArray.prototype.forEach()`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use boa_gc::{Gc, GcRefCell};
    /// # use boa_engine::{JsResult, object::{builtins::JsUint8Array, FunctionObjectBuilder}, NativeFunction, JsValue, Context};
    /// # fn main() -> JsResult<()> {
    /// let context = &mut Context::default();
    /// let array = JsUint8Array::from_iter(vec![1, 2, 3, 4, 5], context)?;
    /// let num_to_modify = Gc::new(GcRefCell::new(0u8));
    ///
    /// let js_function = FunctionObjectBuilder::new(
    ///     context.realm(),
    ///     NativeFunction::from_copy_closure_with_captures(
    ///         |_, args, captures, inner_context| {
    ///             let element = args
    ///                 .first()
    ///                 .cloned()
    ///                 .unwrap_or_default()
    ///                 .to_uint8(inner_context)
    ///                 .expect("error at number conversion");
    ///             *captures.borrow_mut() += element;
    ///             Ok(JsValue::Undefined)
    ///         },
    ///         Gc::clone(&num_to_modify),
    ///     ),
    /// )
    /// .build();
    ///
    /// array.for_each(js_function, None, context);
    /// let borrow = *num_to_modify.borrow();
    /// assert_eq!(borrow, 15u8);
    ///
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn for_each(
        &self,
        callback: JsFunction,
        this_arg: Option<JsValue>,
        context: &mut Context,
    ) -> JsResult<JsValue> {
        BuiltinTypedArray::for_each(
            &self.inner.clone().into(),
            &[callback.into(), this_arg.into_or_undefined()],
            context,
        )
    }

    /// Determines whether a typed array includes a certain value among its entries,
    /// returning true or false as appropriate.
    ///
    /// Calls `TypedArray.prototype.includes()`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use boa_engine::{JsResult, object::{builtins::JsUint8Array}, JsValue, Context};
    /// # fn main() -> JsResult<()> {
    ///
    /// let context = &mut Context::default();
    /// let data: Vec<u8> = (0..=255).collect();
    /// let array = JsUint8Array::from_iter(data, context)?;
    ///
    /// assert_eq!(array.includes(JsValue::new(2), None, context), Ok(true));
    /// let empty_array = JsUint8Array::from_iter(vec![], context)?;
    /// assert_eq!(
    ///     empty_array.includes(JsValue::new(2), None, context),
    ///     Ok(false)
    /// );
    ///
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn includes<T>(
        &self,
        search_element: T,
        from_index: Option<u64>,
        context: &mut Context,
    ) -> JsResult<bool>
    where
        T: Into<JsValue>,
    {
        let result = BuiltinTypedArray::includes(
            &self.inner.clone().into(),
            &[search_element.into(), from_index.into_or_undefined()],
            context,
        )?
        .as_boolean()
        .expect("TypedArray.prototype.includes should always return boolean");

        Ok(result)
    }

    /// Calls `TypedArray.prototype.indexOf()`.
    pub fn index_of<T>(
        &self,
        search_element: T,
        from_index: Option<usize>,
        context: &mut Context,
    ) -> JsResult<Option<usize>>
    where
        T: Into<JsValue>,
    {
        let index = BuiltinTypedArray::index_of(
            &self.inner.clone().into(),
            &[search_element.into(), from_index.into_or_undefined()],
            context,
        )?
        .as_number()
        .expect("TypedArray.prototype.indexOf should always return number");

        #[allow(clippy::float_cmp)]
        if index == -1.0 {
            Ok(None)
        } else {
            Ok(Some(index as usize))
        }
    }

    /// Calls `TypedArray.prototype.lastIndexOf()`.
    pub fn last_index_of<T>(
        &self,
        search_element: T,
        from_index: Option<usize>,
        context: &mut Context,
    ) -> JsResult<Option<usize>>
    where
        T: Into<JsValue>,
    {
        let index = BuiltinTypedArray::last_index_of(
            &self.inner.clone().into(),
            &[search_element.into(), from_index.into_or_undefined()],
            context,
        )?
        .as_number()
        .expect("TypedArray.prototype.lastIndexOf should always return number");

        #[allow(clippy::float_cmp)]
        if index == -1.0 {
            Ok(None)
        } else {
            Ok(Some(index as usize))
        }
    }

    /// Calls `TypedArray.prototype.join()`.
    #[inline]
    pub fn join(&self, separator: Option<JsString>, context: &mut Context) -> JsResult<JsString> {
        BuiltinTypedArray::join(
            &self.inner.clone().into(),
            &[separator.into_or_undefined()],
            context,
        )
        .map(|x| {
            x.as_string()
                .cloned()
                .expect("TypedArray.prototype.join always returns string")
        })
    }

    /// Calls `TypedArray.prototype.toReversed ( )`.
    #[inline]
    pub fn to_reversed(&self, context: &mut Context) -> JsResult<Self> {
        let array = BuiltinTypedArray::to_reversed(&self.inner.clone().into(), &[], context)?;

        Ok(Self {
            inner: array
                .as_object()
                .cloned()
                .expect("`to_reversed` must always return a `TypedArray` on success"),
        })
    }

    /// Calls `TypedArray.prototype.toSorted ( comparefn )`.
    #[inline]
    pub fn to_sorted(
        &self,
        compare_fn: Option<JsFunction>,
        context: &mut Context,
    ) -> JsResult<Self> {
        let array = BuiltinTypedArray::to_sorted(
            &self.inner.clone().into(),
            &[compare_fn.into_or_undefined()],
            context,
        )?;

        Ok(Self {
            inner: array
                .as_object()
                .cloned()
                .expect("`to_sorted` must always return a `TypedArray` on success"),
        })
    }

    /// Calls `TypedArray.prototype.with ( index, value )`.
    #[inline]
    pub fn with(&self, index: u64, value: JsValue, context: &mut Context) -> JsResult<Self> {
        let array =
            BuiltinTypedArray::with(&self.inner.clone().into(), &[index.into(), value], context)?;

        Ok(Self {
            inner: array
                .as_object()
                .cloned()
                .expect("`with` must always return a `TypedArray` on success"),
        })
    }

    /// It is a getter that returns the same string as the typed array constructor's name.
    /// It returns `Ok(JsValue::Undefined)` if the this value is not one of the typed array subclasses.
    ///
    /// Returns `TypedArray.prototype.toStringTag()`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use boa_engine::{JsResult, js_string, object::{builtins::{JsUint8Array}}, Context};
    /// # fn main() -> JsResult<()> {
    ///
    /// let context = &mut Context::default();
    /// let array = JsUint8Array::from_iter(vec![1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8, 8u8], context)?;
    /// let tag = array.to_string_tag(context)?.to_string(context)?;
    /// assert_eq!(tag, js_string!("Uint8Array"));
    ///
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn to_string_tag(&self, context: &mut Context) -> JsResult<JsValue> {
        BuiltinTypedArray::to_string_tag(&self.inner.clone().into(), &[], context)
    }
}

impl From<JsTypedArray> for JsObject {
    #[inline]
    fn from(o: JsTypedArray) -> Self {
        o.inner.clone()
    }
}

impl From<JsTypedArray> for JsValue {
    #[inline]
    fn from(o: JsTypedArray) -> Self {
        o.inner.clone().into()
    }
}

impl Deref for JsTypedArray {
    type Target = JsObject;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl JsObjectType for JsTypedArray {}

impl TryFromJs for JsTypedArray {
    fn try_from_js(value: &JsValue, _context: &mut Context) -> JsResult<Self> {
        match value {
            JsValue::Object(o) => Self::from_object(o.clone()),
            _ => Err(JsNativeError::typ()
                .with_message("value is not a TypedArray object")
                .into()),
        }
    }
}

macro_rules! JsTypedArrayType {
    (
        $name:ident,
        $constructor_function:ident,
        $checker_function:ident,
        $constructor_object:ident,
        $element:ty
    ) => {

        #[doc = concat!(
            "`", stringify!($name),
            "` provides a wrapper for Boa's implementation of the ECMAScript `",
            stringify!($constructor_function) ,"` builtin object."
        )]
        #[derive(Debug, Clone, Trace, Finalize)]
        pub struct $name {
            inner: JsTypedArray,
        }

        impl $name {
            #[doc = concat!("Creates a `", stringify!($name),
                "` using a [`JsObject`]. It will make sure that the object is of the correct kind."
            )]
            #[inline]
            pub fn from_object(object: JsObject) -> JsResult<Self> {
                if object.borrow().$checker_function() {
                    Ok(Self {
                        inner: JsTypedArray {
                            inner: object.into(),
                        },
                    })
                } else {
                    Err(JsNativeError::typ()
                        .with_message("object is not a TypedArray")
                        .into())
                }
            }

            /// Create the typed array from a [`JsArrayBuffer`].
            pub fn from_array_buffer(
                array_buffer: JsArrayBuffer,
                context: &mut Context,
            ) -> JsResult<Self> {
                let new_target = context
                    .intrinsics()
                    .constructors()
                    .$constructor_object()
                    .constructor()
                    .into();
                let object = crate::builtins::typed_array::$constructor_function::constructor(
                    &new_target,
                    &[array_buffer.into()],
                    context,
                )?
                .as_object()
                .expect("object")
                .clone();

                Ok(Self {
                    inner: JsTypedArray {
                        inner: object.into(),
                    },
                })
            }

            /// Create the typed array from an iterator.
            pub fn from_iter<I>(elements: I, context: &mut Context) -> JsResult<Self>
            where
                I: IntoIterator<Item = $element>,
            {
                let bytes: Vec<_> = elements
                    .into_iter()
                    .flat_map(<$element>::to_ne_bytes)
                    .collect();
                let array_buffer = JsArrayBuffer::from_byte_block(bytes, context)?;
                let new_target = context
                    .intrinsics()
                    .constructors()
                    .$constructor_object()
                    .constructor()
                    .into();
                let object = crate::builtins::typed_array::$constructor_function::constructor(
                    &new_target,
                    &[array_buffer.into()],
                    context,
                )?
                .as_object()
                .expect("object")
                .clone();

                Ok(Self {
                    inner: JsTypedArray {
                        inner: object.into(),
                    },
                })
            }
        }

        impl From<$name> for JsObject {
            #[inline]
            fn from(o: $name) -> Self {
                o.inner
                    .inner
                    .clone()
            }
        }

        impl From<$name> for JsValue {
            #[inline]
            fn from(o: $name) -> Self {
                o.inner.inner.clone().into()
            }
        }

        impl Deref for $name {
            type Target = JsTypedArray;

            #[inline]
            fn deref(&self) -> &Self::Target {
                &self.inner
            }
        }

        impl TryFromJs for $name {
            fn try_from_js(value: &JsValue, _context: &mut Context) -> JsResult<Self> {
                match value {
                    JsValue::Object(o) => Self::from_object(o.clone()),
                    _ => Err(JsNativeError::typ()
                        .with_message(concat!(
                            "value is not a ",
                            stringify!($constructor_function),
                            " object"
                        ))
                        .into()),
                }
            }
        }
    };
}

JsTypedArrayType!(
    JsUint8Array,
    Uint8Array,
    is_typed_uint8_array,
    typed_uint8_array,
    u8
);
JsTypedArrayType!(
    JsInt8Array,
    Int8Array,
    is_typed_int8_array,
    typed_int8_array,
    i8
);
JsTypedArrayType!(
    JsUint16Array,
    Uint16Array,
    is_typed_uint16_array,
    typed_uint16_array,
    u16
);
JsTypedArrayType!(
    JsInt16Array,
    Int16Array,
    is_typed_int16_array,
    typed_int16_array,
    i16
);
JsTypedArrayType!(
    JsUint32Array,
    Uint32Array,
    is_typed_uint32_array,
    typed_uint32_array,
    u32
);
JsTypedArrayType!(
    JsInt32Array,
    Int32Array,
    is_typed_int32_array,
    typed_int32_array,
    i32
);
JsTypedArrayType!(
    JsFloat32Array,
    Float32Array,
    is_typed_float32_array,
    typed_float32_array,
    f32
);
JsTypedArrayType!(
    JsFloat64Array,
    Float64Array,
    is_typed_float64_array,
    typed_float64_array,
    f64
);