forked from SerenityOS/serenity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TypedArrayPrototype.cpp
1801 lines (1436 loc) Β· 69.6 KB
/
TypedArrayPrototype.cpp
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
/*
* Copyright (c) 2020-2022, Linus Groh <linusg@serenityos.org>
* Copyright (c) 2021, Luke Wilde <lukew@serenityos.org>
* Copyright (c) 2021-2022, Idan Horowitz <idan.horowitz@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibJS/Runtime/AbstractOperations.h>
#include <LibJS/Runtime/Array.h>
#include <LibJS/Runtime/ArrayIterator.h>
#include <LibJS/Runtime/GlobalObject.h>
#include <LibJS/Runtime/TypedArray.h>
#include <LibJS/Runtime/TypedArrayPrototype.h>
namespace JS {
TypedArrayPrototype::TypedArrayPrototype(GlobalObject& global_object)
: Object(*global_object.object_prototype())
{
}
void TypedArrayPrototype::initialize(GlobalObject& object)
{
auto& vm = this->vm();
Object::initialize(object);
u8 attr = Attribute::Writable | Attribute::Configurable;
define_native_accessor(vm.names.buffer, buffer_getter, nullptr, Attribute::Configurable);
define_native_accessor(vm.names.byteLength, byte_length_getter, nullptr, Attribute::Configurable);
define_native_accessor(vm.names.byteOffset, byte_offset_getter, nullptr, Attribute::Configurable);
define_native_accessor(vm.names.length, length_getter, nullptr, Attribute::Configurable);
define_native_function(vm.names.at, at, 1, attr);
define_native_function(vm.names.copyWithin, copy_within, 2, attr);
define_native_function(vm.names.entries, entries, 0, attr);
define_native_function(vm.names.every, every, 1, attr);
define_native_function(vm.names.fill, fill, 1, attr);
define_native_function(vm.names.filter, filter, 1, attr);
define_native_function(vm.names.find, find, 1, attr);
define_native_function(vm.names.findIndex, find_index, 1, attr);
define_native_function(vm.names.findLast, find_last, 1, attr);
define_native_function(vm.names.findLastIndex, find_last_index, 1, attr);
define_native_function(vm.names.forEach, for_each, 1, attr);
define_native_function(vm.names.includes, includes, 1, attr);
define_native_function(vm.names.indexOf, index_of, 1, attr);
define_native_function(vm.names.join, join, 1, attr);
define_native_function(vm.names.keys, keys, 0, attr);
define_native_function(vm.names.lastIndexOf, last_index_of, 1, attr);
define_native_function(vm.names.map, map, 1, attr);
define_native_function(vm.names.reduce, reduce, 1, attr);
define_native_function(vm.names.reduceRight, reduce_right, 1, attr);
define_native_function(vm.names.reverse, reverse, 0, attr);
define_native_function(vm.names.set, set, 1, attr);
define_native_function(vm.names.slice, slice, 2, attr);
define_native_function(vm.names.some, some, 1, attr);
define_native_function(vm.names.sort, sort, 1, attr);
define_native_function(vm.names.subarray, subarray, 2, attr);
define_native_function(vm.names.toLocaleString, to_locale_string, 0, attr);
define_native_function(vm.names.toReversed, to_reversed, 0, attr);
define_native_function(vm.names.toSorted, to_sorted, 1, attr);
define_native_function(vm.names.toSpliced, to_spliced, 2, attr);
define_native_function(vm.names.with, with, 2, attr);
define_native_function(vm.names.values, values, 0, attr);
define_native_accessor(*vm.well_known_symbol_to_string_tag(), to_string_tag_getter, nullptr, Attribute::Configurable);
// 23.2.3.32 %TypedArray%.prototype.toString ( ), https://tc39.es/ecma262/#sec-%typedarray%.prototype.tostring
define_direct_property(vm.names.toString, global_object().array_prototype()->get_without_side_effects(vm.names.toString), attr);
// 23.2.3.34 %TypedArray%.prototype [ @@iterator ] ( ), https://tc39.es/ecma262/#sec-%typedarray%.prototype-@@iterator
define_direct_property(*vm.well_known_symbol_iterator(), get_without_side_effects(vm.names.values), attr);
}
static ThrowCompletionOr<TypedArrayBase*> typed_array_from_this(GlobalObject& global_object)
{
auto this_value = global_object.vm().this_value(global_object);
return typed_array_from(global_object, this_value);
}
static ThrowCompletionOr<TypedArrayBase*> validate_typed_array_from_this(GlobalObject& global_object)
{
auto* typed_array = TRY(typed_array_from_this(global_object));
TRY(validate_typed_array(global_object, *typed_array));
return typed_array;
}
static ThrowCompletionOr<FunctionObject*> callback_from_args(GlobalObject& global_object, String const& name)
{
auto& vm = global_object.vm();
if (vm.argument_count() < 1)
return vm.throw_completion<TypeError>(global_object, ErrorType::TypedArrayPrototypeOneArg, name);
auto callback = vm.argument(0);
if (!callback.is_function())
return vm.throw_completion<TypeError>(global_object, ErrorType::NotAFunction, callback.to_string_without_side_effects());
return &callback.as_function();
}
static ThrowCompletionOr<void> for_each_item(VM& vm, GlobalObject& global_object, String const& name, Function<IterationDecision(size_t index, Value value, Value callback_result)> callback)
{
auto* typed_array = TRY(validate_typed_array_from_this(global_object));
auto initial_length = typed_array->array_length();
auto* callback_function = TRY(callback_from_args(global_object, name));
auto this_value = vm.argument(1);
for (size_t i = 0; i < initial_length; ++i) {
auto value = TRY(typed_array->get(i));
auto callback_result = TRY(call(global_object, *callback_function, this_value, value, Value((i32)i), typed_array));
if (callback(i, value, callback_result) == IterationDecision::Break)
break;
}
return {};
}
static ThrowCompletionOr<void> for_each_item_from_last(VM& vm, GlobalObject& global_object, String const& name, Function<IterationDecision(size_t index, Value value, Value callback_result)> callback)
{
auto* typed_array = TRY(validate_typed_array_from_this(global_object));
auto initial_length = typed_array->array_length();
auto* callback_function = TRY(callback_from_args(global_object, name));
auto this_value = vm.argument(1);
for (ssize_t i = (ssize_t)initial_length - 1; i >= 0; --i) {
auto value = TRY(typed_array->get(i));
auto callback_result = TRY(call(global_object, *callback_function, this_value, value, Value((i32)i), typed_array));
if (callback(i, value, callback_result) == IterationDecision::Break)
break;
}
return {};
}
// 23.2.4.1 TypedArraySpeciesCreate ( exemplar, argumentList ), https://tc39.es/ecma262/#typedarray-species-create
static ThrowCompletionOr<TypedArrayBase*> typed_array_species_create(GlobalObject& global_object, TypedArrayBase const& exemplar, MarkedVector<Value> arguments)
{
auto& vm = global_object.vm();
// 1. Let defaultConstructor be the intrinsic object listed in column one of Table 72 for exemplar.[[TypedArrayName]].
auto* default_constructor = (global_object.*exemplar.intrinsic_constructor())();
// 2. Let constructor be ? SpeciesConstructor(exemplar, defaultConstructor).
auto* constructor = TRY(species_constructor(global_object, exemplar, *default_constructor));
// 3. Let result be ? TypedArrayCreate(constructor, argumentList).
auto* result = TRY(typed_array_create(global_object, *constructor, move(arguments)));
// 4. Assert: result has [[TypedArrayName]] and [[ContentType]] internal slots.
// 5. If result.[[ContentType]] β exemplar.[[ContentType]], throw a TypeError exception.
if (result->content_type() != exemplar.content_type())
return vm.throw_completion<TypeError>(global_object, ErrorType::TypedArrayContentTypeMismatch, result->class_name(), exemplar.class_name());
// 6. Return result.
return result;
}
// 23.2.3.1 %TypedArray%.prototype.at ( index ), https://tc39.es/ecma262/#sec-%typedarray%.prototype.at
JS_DEFINE_NATIVE_FUNCTION(TypedArrayPrototype::at)
{
auto* typed_array = TRY(validate_typed_array_from_this(global_object));
auto length = typed_array->array_length();
auto relative_index = TRY(vm.argument(0).to_integer_or_infinity(global_object));
if (Value(relative_index).is_infinity())
return js_undefined();
Checked<size_t> index { 0 };
if (relative_index >= 0) {
index += relative_index;
} else {
index += length;
index -= -relative_index;
}
if (index.has_overflow() || index.value() >= length)
return js_undefined();
return TRY(typed_array->get(index.value()));
}
// 23.2.3.2 get %TypedArray%.prototype.buffer, https://tc39.es/ecma262/#sec-get-%typedarray%.prototype.buffer
JS_DEFINE_NATIVE_FUNCTION(TypedArrayPrototype::buffer_getter)
{
auto* typed_array = TRY(typed_array_from_this(global_object));
auto* array_buffer = typed_array->viewed_array_buffer();
VERIFY(array_buffer);
return Value(array_buffer);
}
// 23.2.3.3 get %TypedArray%.prototype.byteLength, https://tc39.es/ecma262/#sec-get-%typedarray%.prototype.bytelength
JS_DEFINE_NATIVE_FUNCTION(TypedArrayPrototype::byte_length_getter)
{
auto* typed_array = TRY(typed_array_from_this(global_object));
auto* array_buffer = typed_array->viewed_array_buffer();
VERIFY(array_buffer);
if (array_buffer->is_detached())
return Value(0);
return Value(typed_array->byte_length());
}
// 23.2.3.4 get %TypedArray%.prototype.byteOffset, https://tc39.es/ecma262/#sec-get-%typedarray%.prototype.byteoffset
JS_DEFINE_NATIVE_FUNCTION(TypedArrayPrototype::byte_offset_getter)
{
auto* typed_array = TRY(typed_array_from_this(global_object));
auto* array_buffer = typed_array->viewed_array_buffer();
VERIFY(array_buffer);
if (array_buffer->is_detached())
return Value(0);
return Value(typed_array->byte_offset());
}
// 23.2.3.6 %TypedArray%.prototype.copyWithin ( target, start [ , end ] ), https://tc39.es/ecma262/#sec-%typedarray%.prototype.copywithin
JS_DEFINE_NATIVE_FUNCTION(TypedArrayPrototype::copy_within)
{
// 1. Let O be the this value.
// 2. Perform ? ValidateTypedArray(O).
auto* typed_array = TRY(validate_typed_array_from_this(global_object));
// 3. Let len be O.[[ArrayLength]].
auto length = typed_array->array_length();
// 4. Let relativeTarget be ? ToIntegerOrInfinity(target).
auto relative_target = TRY(vm.argument(0).to_integer_or_infinity(global_object));
double to;
if (Value(relative_target).is_negative_infinity()) {
// 5. If relativeTarget is -β, let to be 0.
to = 0.0;
} else if (relative_target < 0) {
// 6. Else if relativeTarget < 0, let to be max(len + relativeTarget, 0)
to = max(length + relative_target, 0.0);
} else {
// 7. Else, let to be min(relativeTarget, len).
to = min(relative_target, (double)length);
}
// 8. Let relativeStart be ? ToIntegerOrInfinity(start).
auto relative_start = TRY(vm.argument(1).to_integer_or_infinity(global_object));
double from;
if (Value(relative_start).is_negative_infinity()) {
// 9. If relativeStart is -β, let from be 0.
from = 0.0;
} else if (relative_start < 0) {
// 10. Else if relativeStart < 0, let from be max(len + relativeStart, 0).
from = max(length + relative_start, 0.0);
} else {
// 11. Else, let from be min(relativeStart, len).
from = min(relative_start, (double)length);
}
double relative_end;
// 12. If end is undefined, let relativeEnd be len; else let relativeEnd be ? ToIntegerOrInfinity(end).
if (vm.argument(2).is_undefined())
relative_end = length;
else
relative_end = TRY(vm.argument(2).to_integer_or_infinity(global_object));
double final;
if (Value(relative_end).is_negative_infinity()) {
// 13. If relativeEnd is -β, let final be 0.
final = 0.0;
} else if (relative_end < 0) {
// 14. Else if relativeEnd < 0, let final be max(len + relativeEnd, 0).
final = max(length + relative_end, 0.0);
} else {
// 15. Else, let final be min(relativeEnd, len).
final = min(relative_end, (double)length);
}
// 16. Let count be min(final - from, len - to).
double count = min(final - from, length - to);
// 17. If count > 0, then
if (count > 0.0) {
// a. NOTE: The copying must be performed in a manner that preserves the bit-level encoding of the source data.
// b. Let buffer be O.[[ViewedArrayBuffer]].
auto buffer = typed_array->viewed_array_buffer();
// c. If IsDetachedBuffer(buffer) is true, throw a TypeError exception.
if (buffer->is_detached())
return vm.throw_completion<TypeError>(global_object, ErrorType::DetachedArrayBuffer);
// d. Let elementSize be TypedArrayElementSize(O).
auto element_size = typed_array->element_size();
// e. Let byteOffset be O.[[ByteOffset]].
auto byte_offset = typed_array->byte_offset();
// FIXME: Not exactly sure what we should do when overflow occurs.
// Just return as if succeeded for now. (This goes for steps g to j)
// f. Let toByteIndex be to Γ elementSize + byteOffset.
Checked<size_t> to_byte_index_checked = static_cast<size_t>(to);
to_byte_index_checked *= element_size;
to_byte_index_checked += byte_offset;
if (to_byte_index_checked.has_overflow()) {
dbgln("TypedArrayPrototype::copy_within: to_byte_index overflowed, returning as if succeeded.");
return typed_array;
}
// g. Let fromByteIndex be from Γ elementSize + byteOffset.
Checked<size_t> from_byte_index_checked = static_cast<size_t>(from);
from_byte_index_checked *= element_size;
from_byte_index_checked += byte_offset;
if (from_byte_index_checked.has_overflow()) {
dbgln("TypedArrayPrototype::copy_within: from_byte_index_checked overflowed, returning as if succeeded.");
return typed_array;
}
// h. Let countBytes be count Γ elementSize.
Checked<size_t> count_bytes_checked = static_cast<size_t>(count);
count_bytes_checked *= element_size;
if (count_bytes_checked.has_overflow()) {
dbgln("TypedArrayPrototype::copy_within: count_bytes_checked overflowed, returning as if succeeded.");
return typed_array;
}
auto to_byte_index = to_byte_index_checked.value();
auto from_byte_index = from_byte_index_checked.value();
auto count_bytes = count_bytes_checked.value();
Checked<size_t> from_plus_count = from_byte_index;
from_plus_count += count_bytes;
if (from_plus_count.has_overflow()) {
dbgln("TypedArrayPrototype::copy_within: from_plus_count overflowed, returning as if succeeded.");
return typed_array;
}
i8 direction;
// i. If fromByteIndex < toByteIndex and toByteIndex < fromByteIndex + countBytes, then
if (from_byte_index < to_byte_index && to_byte_index < from_plus_count.value()) {
// i. Let direction be -1.
direction = -1;
// ii. Set fromByteIndex to fromByteIndex + countBytes - 1.
from_byte_index = from_plus_count.value() - 1;
Checked<size_t> to_plus_count = to_byte_index;
to_plus_count += count_bytes;
if (to_plus_count.has_overflow()) {
dbgln("TypedArrayPrototype::copy_within: to_plus_count overflowed, returning as if succeeded.");
return typed_array;
}
// iii. Set toByteIndex to toByteIndex + countBytes - 1.
to_byte_index = to_plus_count.value() - 1;
}
// j. Else,
else {
// i. Let direction be 1.
direction = 1;
}
// k. Repeat, while countBytes > 0,
for (; count_bytes > 0; --count_bytes) {
// i. Let value be GetValueFromBuffer(buffer, fromByteIndex, Uint8, true, Unordered).
auto value = buffer->get_value<u8>(from_byte_index, true, ArrayBuffer::Order::Unordered);
// ii. Perform SetValueInBuffer(buffer, toByteIndex, Uint8, value, true, Unordered).
buffer->set_value<u8>(to_byte_index, value, true, ArrayBuffer::Order::Unordered);
// iii. Set fromByteIndex to fromByteIndex + direction.
from_byte_index += direction;
// iv. Set toByteIndex to toByteIndex + direction.
to_byte_index += direction;
// v. Set countBytes to countBytes - 1.
}
}
// 18. Return O.
return typed_array;
}
// 23.2.3.7 %TypedArray%.prototype.entries ( ), https://tc39.es/ecma262/#sec-%typedarray%.prototype.entries
JS_DEFINE_NATIVE_FUNCTION(TypedArrayPrototype::entries)
{
auto* typed_array = TRY(validate_typed_array_from_this(global_object));
return ArrayIterator::create(global_object, typed_array, Object::PropertyKind::KeyAndValue);
}
// 23.2.3.8 %TypedArray%.prototype.every ( callbackfn [ , thisArg ] ), https://tc39.es/ecma262/#sec-%typedarray%.prototype.every
JS_DEFINE_NATIVE_FUNCTION(TypedArrayPrototype::every)
{
auto result = true;
TRY(for_each_item(vm, global_object, "every", [&](auto, auto, auto callback_result) {
if (!callback_result.to_boolean()) {
result = false;
return IterationDecision::Break;
}
return IterationDecision::Continue;
}));
return Value(result);
}
// 23.2.3.9 %TypedArray%.prototype.fill ( value [ , start [ , end ] ] ), https://tc39.es/ecma262/#sec-%typedarray%.prototype.fill
JS_DEFINE_NATIVE_FUNCTION(TypedArrayPrototype::fill)
{
auto typed_array = TRY(validate_typed_array_from_this(global_object));
auto length = typed_array->array_length();
Value value;
if (typed_array->content_type() == TypedArrayBase::ContentType::BigInt)
value = TRY(vm.argument(0).to_bigint(global_object));
else
value = TRY(vm.argument(0).to_number(global_object));
auto relative_start = TRY(vm.argument(1).to_integer_or_infinity(global_object));
u32 k;
if (Value(relative_start).is_negative_infinity())
k = 0;
else if (relative_start < 0)
k = max(length + relative_start, 0);
else
k = min(relative_start, length);
double relative_end;
if (vm.argument(2).is_undefined())
relative_end = length;
else
relative_end = TRY(vm.argument(2).to_integer_or_infinity(global_object));
u32 final;
if (Value(relative_end).is_negative_infinity())
final = 0;
else if (relative_end < 0)
final = max(length + relative_end, 0);
else
final = min(relative_end, length);
if (typed_array->viewed_array_buffer()->is_detached())
return vm.throw_completion<TypeError>(global_object, ErrorType::DetachedArrayBuffer);
for (; k < final; ++k)
TRY(typed_array->set(k, value, Object::ShouldThrowExceptions::Yes));
return typed_array;
}
// 23.2.3.10 %TypedArray%.prototype.filter ( callbackfn [ , thisArg ] ), https://tc39.es/ecma262/#sec-%typedarray%.prototype.filter
JS_DEFINE_NATIVE_FUNCTION(TypedArrayPrototype::filter)
{
// 1. Let O be the this value.
// 2. Perform ? ValidateTypedArray(O).
auto* typed_array = TRY(validate_typed_array_from_this(global_object));
// 3. Let len be O.[[ArrayLength]].
auto initial_length = typed_array->array_length();
// 4. If IsCallable(callbackfn) is false, throw a TypeError exception.
auto* callback_function = TRY(callback_from_args(global_object, "filter"));
// 5. Let kept be a new empty List.
MarkedVector<Value> kept(vm.heap());
// 7. Let captured be 0.
size_t captured = 0;
auto this_value = vm.argument(1);
// 5. Let k be 0.
// 8. Repeat, while k < len,
for (size_t i = 0; i < initial_length; ++i) {
// a. Let Pk be ! ToString(π½(k)).
// b. Let kValue be ! Get(O, Pk).
auto value = MUST(typed_array->get(i));
// c. Let selected be ToBoolean(? Call(callbackfn, thisArg, Β« kValue, π½(k), O Β»)).
auto callback_result = TRY(call(global_object, *callback_function, this_value, value, Value((i32)i), typed_array)).to_boolean();
// d. If selected is true, then
if (callback_result) {
// i. Append kValue to the end of kept.
kept.append(value);
// ii. Set captured to captured + 1.
++captured;
}
// e. Set k to k + 1.
}
// 9. Let A be ? TypedArraySpeciesCreate(O, Β« π½(captured) Β»).
MarkedVector<Value> arguments(vm.heap());
arguments.empend(captured);
auto* filter_array = TRY(typed_array_species_create(global_object, *typed_array, move(arguments)));
// 10. Let n be 0.
size_t index = 0;
// 11. For each element e of kept, do
for (auto& value : kept) {
// a. Perform ! Set(A, ! ToString(π½(n)), e, true).
MUST(filter_array->set(index, value, Object::ShouldThrowExceptions::Yes));
// b. Set n to n + 1.
++index;
}
// 12. Return A.
return filter_array;
}
// 23.2.3.11 %TypedArray%.prototype.find ( predicate [ , thisArg ] ), https://tc39.es/ecma262/#sec-%typedarray%.prototype.find
JS_DEFINE_NATIVE_FUNCTION(TypedArrayPrototype::find)
{
auto result = js_undefined();
TRY(for_each_item(vm, global_object, "find", [&](auto, auto value, auto callback_result) {
if (callback_result.to_boolean()) {
result = value;
return IterationDecision::Break;
}
return IterationDecision::Continue;
}));
return result;
}
// 23.2.3.12 %TypedArray%.prototype.findIndex ( predicate [ , thisArg ] ), https://tc39.es/ecma262/#sec-%typedarray%.prototype.findindex
JS_DEFINE_NATIVE_FUNCTION(TypedArrayPrototype::find_index)
{
auto result_index = -1;
TRY(for_each_item(vm, global_object, "findIndex", [&](auto index, auto, auto callback_result) {
if (callback_result.to_boolean()) {
result_index = index;
return IterationDecision::Break;
}
return IterationDecision::Continue;
}));
return Value(result_index);
}
// 23.2.3.13 %TypedArray%.prototype.findLast ( predicate [ , thisArg ] ), https://tc39.es/ecma262/#sec-%typedarray%.prototype.findlast
JS_DEFINE_NATIVE_FUNCTION(TypedArrayPrototype::find_last)
{
auto result = js_undefined();
TRY(for_each_item_from_last(vm, global_object, "findLast", [&](auto, auto value, auto callback_result) {
if (callback_result.to_boolean()) {
result = value;
return IterationDecision::Break;
}
return IterationDecision::Continue;
}));
return result;
}
// 23.2.3.14 %TypedArray%.prototype.findLastIndex ( predicate [ , thisArg ] ), https://tc39.es/ecma262/#sec-%typedarray%.prototype.findlastindex
JS_DEFINE_NATIVE_FUNCTION(TypedArrayPrototype::find_last_index)
{
auto result_index = -1;
TRY(for_each_item_from_last(vm, global_object, "findLastIndex", [&](auto index, auto, auto callback_result) {
if (callback_result.to_boolean()) {
result_index = index;
return IterationDecision::Break;
}
return IterationDecision::Continue;
}));
return Value(result_index);
}
// 23.2.3.15 %TypedArray%.prototype.forEach ( callbackfn [ , thisArg ] ), https://tc39.es/ecma262/#sec-%typedarray%.prototype.foreach
JS_DEFINE_NATIVE_FUNCTION(TypedArrayPrototype::for_each)
{
TRY(for_each_item(vm, global_object, "forEach", [](auto, auto, auto) {
return IterationDecision::Continue;
}));
return js_undefined();
}
// 23.2.3.16 %TypedArray%.prototype.includes ( searchElement [ , fromIndex ] ), https://tc39.es/ecma262/#sec-%typedarray%.prototype.includes
JS_DEFINE_NATIVE_FUNCTION(TypedArrayPrototype::includes)
{
auto typed_array = TRY(validate_typed_array_from_this(global_object));
auto length = typed_array->array_length();
if (length == 0)
return Value(false);
auto n = TRY(vm.argument(1).to_integer_or_infinity(global_object));
auto value_n = Value(n);
if (value_n.is_positive_infinity())
return Value(false);
else if (value_n.is_negative_infinity())
n = 0;
u32 k;
if (n >= 0) {
k = n;
} else {
auto relative_k = length + n;
if (relative_k < 0)
relative_k = 0;
k = relative_k;
}
auto search_element = vm.argument(0);
for (; k < length; ++k) {
auto element_k = MUST(typed_array->get(k));
if (same_value_zero(search_element, element_k))
return Value(true);
}
return Value(false);
}
// 23.2.3.17 %TypedArray%.prototype.indexOf ( searchElement [ , fromIndex ] ), https://tc39.es/ecma262/#sec-%typedarray%.prototype.indexof
JS_DEFINE_NATIVE_FUNCTION(TypedArrayPrototype::index_of)
{
auto typed_array = TRY(validate_typed_array_from_this(global_object));
auto length = typed_array->array_length();
if (length == 0)
return Value(-1);
auto n = TRY(vm.argument(1).to_integer_or_infinity(global_object));
auto value_n = Value(n);
if (value_n.is_positive_infinity())
return Value(-1);
else if (value_n.is_negative_infinity())
n = 0;
u32 k;
if (n >= 0) {
k = n;
} else {
auto relative_k = length + n;
if (relative_k < 0)
relative_k = 0;
k = relative_k;
}
auto search_element = vm.argument(0);
for (; k < length; ++k) {
auto k_present = MUST(typed_array->has_property(k));
if (k_present) {
auto element_k = MUST(typed_array->get(k));
if (is_strictly_equal(search_element, element_k))
return Value(k);
}
}
return Value(-1);
}
// 23.2.3.18 %TypedArray%.prototype.join ( separator ), https://tc39.es/ecma262/#sec-%typedarray%.prototype.join
JS_DEFINE_NATIVE_FUNCTION(TypedArrayPrototype::join)
{
auto* typed_array = TRY(validate_typed_array_from_this(global_object));
auto length = typed_array->array_length();
String separator = ",";
if (!vm.argument(0).is_undefined())
separator = TRY(vm.argument(0).to_string(global_object));
StringBuilder builder;
for (size_t i = 0; i < length; ++i) {
if (i > 0)
builder.append(separator);
auto value = TRY(typed_array->get(i));
if (value.is_nullish())
continue;
auto string = TRY(value.to_string(global_object));
builder.append(string);
}
return js_string(vm, builder.to_string());
}
// 23.2.3.19 %TypedArray%.prototype.keys ( ), https://tc39.es/ecma262/#sec-%typedarray%.prototype.keys
JS_DEFINE_NATIVE_FUNCTION(TypedArrayPrototype::keys)
{
auto* typed_array = TRY(validate_typed_array_from_this(global_object));
return ArrayIterator::create(global_object, typed_array, Object::PropertyKind::Key);
}
// 23.2.3.20 %TypedArray%.prototype.lastIndexOf ( searchElement [ , fromIndex ] ), https://tc39.es/ecma262/#sec-%typedarray%.prototype.lastindexof
JS_DEFINE_NATIVE_FUNCTION(TypedArrayPrototype::last_index_of)
{
auto typed_array = TRY(validate_typed_array_from_this(global_object));
auto length = typed_array->array_length();
if (length == 0)
return Value(-1);
double n;
if (vm.argument_count() > 1)
n = TRY(vm.argument(1).to_integer_or_infinity(global_object));
else
n = length - 1;
if (Value(n).is_negative_infinity())
return Value(-1);
i32 k;
if (n >= 0) {
k = min(n, (i32)length - 1);
} else {
auto relative_k = length + n;
if (relative_k < 0) // ensures we dont underflow `k`
relative_k = -1;
k = relative_k;
}
auto search_element = vm.argument(0);
for (; k >= 0; --k) {
auto k_present = MUST(typed_array->has_property(k));
if (k_present) {
auto element_k = MUST(typed_array->get(k));
if (is_strictly_equal(search_element, element_k))
return Value(k);
}
}
return Value(-1);
}
// 23.2.3.21 get %TypedArray%.prototype.length, https://tc39.es/ecma262/#sec-get-%typedarray%.prototype.length
JS_DEFINE_NATIVE_FUNCTION(TypedArrayPrototype::length_getter)
{
auto* typed_array = TRY(typed_array_from_this(global_object));
auto* array_buffer = typed_array->viewed_array_buffer();
VERIFY(array_buffer);
if (array_buffer->is_detached())
return Value(0);
return Value(typed_array->array_length());
}
// 23.2.3.22 %TypedArray%.prototype.map ( callbackfn [ , thisArg ] ), https://tc39.es/ecma262/#sec-%typedarray%.prototype.map
JS_DEFINE_NATIVE_FUNCTION(TypedArrayPrototype::map)
{
// 1. Let O be the this value.
// 2. Perform ? ValidateTypedArray(O).
auto* typed_array = TRY(validate_typed_array_from_this(global_object));
// 3. Let len be O.[[ArrayLength]].
auto initial_length = typed_array->array_length();
// 4. If IsCallable(callbackfn) is false, throw a TypeError exception.
auto* callback_function = TRY(callback_from_args(global_object, "map"));
// 5. Let A be ? TypedArraySpeciesCreate(O, Β« π½(len) Β»).
MarkedVector<Value> arguments(vm.heap());
arguments.empend(initial_length);
auto* return_array = TRY(typed_array_species_create(global_object, *typed_array, move(arguments)));
auto this_value = vm.argument(1);
// 6. Let k be 0.
// 7. Repeat, while k < len,
for (size_t i = 0; i < initial_length; ++i) {
// a. Let Pk be ! ToString(π½(k)).
// b. Let kValue be ! Get(O, Pk).
auto value = MUST(typed_array->get(i));
// c. Let mappedValue be ? Call(callbackfn, thisArg, Β« kValue, π½(k), O Β»).
auto mapped_value = TRY(call(global_object, *callback_function, this_value, value, Value((i32)i), typed_array));
// d. Perform ? Set(A, Pk, mappedValue, true).
TRY(return_array->set(i, mapped_value, Object::ShouldThrowExceptions::Yes));
// e. Set k to k + 1.
}
// 8. Return A.
return return_array;
}
// 23.2.3.23 %TypedArray%.prototype.reduce ( callbackfn [ , initialValue ] ), https://tc39.es/ecma262/#sec-%typedarray%.prototype.reduce
JS_DEFINE_NATIVE_FUNCTION(TypedArrayPrototype::reduce)
{
auto* typed_array = TRY(validate_typed_array_from_this(global_object));
auto length = typed_array->array_length();
auto* callback_function = TRY(callback_from_args(global_object, vm.names.reduce.as_string()));
if (length == 0 && vm.argument_count() <= 1)
return vm.throw_completion<TypeError>(global_object, ErrorType::ReduceNoInitial);
u32 k = 0;
Value accumulator;
if (vm.argument_count() > 1) {
accumulator = vm.argument(1);
} else {
accumulator = MUST(typed_array->get(k));
++k;
}
for (; k < length; ++k) {
auto k_value = MUST(typed_array->get(k));
accumulator = TRY(call(global_object, *callback_function, js_undefined(), accumulator, k_value, Value(k), typed_array));
}
return accumulator;
}
// 23.2.3.24 %TypedArray%.prototype.reduceRight ( callbackfn [ , initialValue ] ), https://tc39.es/ecma262/#sec-%typedarray%.prototype.reduce
JS_DEFINE_NATIVE_FUNCTION(TypedArrayPrototype::reduce_right)
{
auto* typed_array = TRY(validate_typed_array_from_this(global_object));
auto length = typed_array->array_length();
auto* callback_function = TRY(callback_from_args(global_object, vm.names.reduce.as_string()));
if (length == 0 && vm.argument_count() <= 1)
return vm.throw_completion<TypeError>(global_object, ErrorType::ReduceNoInitial);
i32 k = (i32)length - 1;
Value accumulator;
if (vm.argument_count() > 1) {
accumulator = vm.argument(1);
} else {
accumulator = MUST(typed_array->get(k));
--k;
}
for (; k >= 0; --k) {
auto k_value = MUST(typed_array->get(k));
accumulator = TRY(call(global_object, *callback_function, js_undefined(), accumulator, k_value, Value(k), typed_array));
}
return accumulator;
}
// 23.2.3.25 %TypedArray%.prototype.reverse ( ), https://tc39.es/ecma262/#sec-%typedarray%.prototype.reverse
JS_DEFINE_NATIVE_FUNCTION(TypedArrayPrototype::reverse)
{
// 1. Let O be the this value.
// 2. Perform ? ValidateTypedArray(O).
auto* typed_array = TRY(validate_typed_array_from_this(global_object));
// 3. Let len be O.[[ArrayLength]].
auto length = typed_array->array_length();
// 4. Let middle be floor(len / 2).
auto middle = length / 2;
// 5. Let lower be 0.
// 6. Repeat, while lower β middle,
for (size_t lower = 0; lower != middle; ++lower) {
// a. Let upper be len - lower - 1.
auto upper = length - lower - 1;
// b. Let upperP be ! ToString(π½(upper)).
// d. Let lowerValue be ! Get(O, lowerP).
auto lower_value = MUST(typed_array->get(lower));
// c. Let lowerP be ! ToString(π½(lower)).
// e. Let upperValue be ! Get(O, upperP).
auto upper_value = MUST(typed_array->get(upper));
// f. Perform ! Set(O, lowerP, upperValue, true).
MUST(typed_array->set(lower, upper_value, Object::ShouldThrowExceptions::Yes));
// g. Perform ! Set(O, upperP, lowerValue, true).
MUST(typed_array->set(upper, lower_value, Object::ShouldThrowExceptions::Yes));
// h. Set lower to lower + 1.
}
// 7. Return O.
return typed_array;
}
// 23.2.3.26.1 SetTypedArrayFromTypedArray ( target, targetOffset, source ), https://tc39.es/ecma262/#sec-settypedarrayfromtypedarray
static ThrowCompletionOr<void> set_typed_array_from_typed_array(GlobalObject& global_object, TypedArrayBase& target, double target_offset, TypedArrayBase& source)
{
auto& vm = global_object.vm();
// 1. Let targetBuffer be target.[[ViewedArrayBuffer]].
auto* target_buffer = target.viewed_array_buffer();
// 2. If IsDetachedBuffer(targetBuffer) is true, throw a TypeError exception.
if (target_buffer->is_detached())
return vm.throw_completion<TypeError>(global_object, ErrorType::DetachedArrayBuffer);
// 3. Let targetLength be target.[[ArrayLength]].
auto target_length = target.array_length();
// 4. Let srcBuffer be source.[[ViewedArrayBuffer]].
auto* source_buffer = source.viewed_array_buffer();
// 5. If IsDetachedBuffer(srcBuffer) is true, throw a TypeError exception.
if (source_buffer->is_detached())
return vm.throw_completion<TypeError>(global_object, ErrorType::DetachedArrayBuffer);
// 6. Let targetType be TypedArrayElementType(target).
// 7. Let targetElementSize be TypedArrayElementSize(target).
auto target_element_size = target.element_size();
// 8. Let targetByteOffset be target.[[ByteOffset]].
auto target_byte_offset = target.byte_offset();
// 9. Let srcType be TypedArrayElementType(source).
// 10. Let srcElementSize be TypedArrayElementSize(source).
auto source_element_size = source.element_size();
// 11. Let srcLength be source.[[ArrayLength]].
auto source_length = source.array_length();
// 12. Let srcByteOffset be source.[[ByteOffset]].
auto source_byte_offset = source.byte_offset();
// 13. If targetOffset is +β, throw a RangeError exception.
if (isinf(target_offset))
return vm.throw_completion<RangeError>(global_object, ErrorType::TypedArrayInvalidTargetOffset, "finite");
// 14. If srcLength + targetOffset > targetLength, throw a RangeError exception.
Checked<size_t> checked = source_length;
checked += static_cast<u32>(target_offset);
if (checked.has_overflow() || checked.value() > target_length)
return vm.throw_completion<RangeError>(global_object, ErrorType::TypedArrayOverflowOrOutOfBounds, "target length");
// 15. If target.[[ContentType]] β source.[[ContentType]], throw a TypeError exception.
if (target.content_type() != source.content_type())
return vm.throw_completion<TypeError>(global_object, ErrorType::TypedArrayInvalidCopy, target.class_name(), source.class_name());
// FIXME: 16. If both IsSharedArrayBuffer(srcBuffer) and IsSharedArrayBuffer(targetBuffer) are true, then
// FIXME: a. If srcBuffer.[[ArrayBufferData]] and targetBuffer.[[ArrayBufferData]] are the same Shared Data Block values, let same be true; else let same be false.
// 17. Else, let same be SameValue(srcBuffer, targetBuffer).
auto same = same_value(source_buffer, target_buffer);
size_t source_byte_index = 0;
// 18. If same is true, then
if (same) {
// a. Let srcByteLength be source.[[ByteLength]].
auto source_byte_length = source.byte_length();
// b. Set srcBuffer to ? CloneArrayBuffer(srcBuffer, srcByteOffset, srcByteLength).
source_buffer = TRY(clone_array_buffer(global_object, *source_buffer, source_byte_offset, source_byte_length));
// c. Let srcByteIndex be 0.
source_byte_index = 0;
}
// 19. Else, let srcByteIndex be srcByteOffset.
else {
source_byte_index = source_byte_offset;
}
// 20. Let targetByteIndex be targetOffset Γ targetElementSize + targetByteOffset.
Checked<size_t> checked_target_byte_index(static_cast<size_t>(target_offset));
checked_target_byte_index *= target_element_size;
checked_target_byte_index += target_byte_offset;
if (checked_target_byte_index.has_overflow())
return vm.throw_completion<RangeError>(global_object, ErrorType::TypedArrayOverflow, "target byte index");
auto target_byte_index = checked_target_byte_index.value();
// 21. Let limit be targetByteIndex + targetElementSize Γ srcLength.
Checked<size_t> checked_limit(source_length);
checked_limit *= target_element_size;
checked_limit += target_byte_index;
if (checked_limit.has_overflow())
return vm.throw_completion<RangeError>(global_object, ErrorType::TypedArrayOverflow, "target limit");
auto limit = checked_limit.value();
// 22. If srcType is the same as targetType, then
if (source.element_name() == target.element_name()) {
// a. NOTE: If srcType and targetType are the same, the transfer must be performed in a manner that preserves the bit-level encoding of the source data.
// b. Repeat, while targetByteIndex < limit,
// i. Let value be GetValueFromBuffer(srcBuffer, srcByteIndex, Uint8, true, Unordered).
// ii. Perform SetValueInBuffer(targetBuffer, targetByteIndex, Uint8, value, true, Unordered).
// iii. Set srcByteIndex to srcByteIndex + 1.
// iv. Set targetByteIndex to targetByteIndex + 1.
target_buffer->buffer().overwrite(target_byte_index, source_buffer->buffer().data() + source_byte_index, limit - target_byte_index);
}
// 23. Else,
else {
// a. Repeat, while targetByteIndex < limit,
while (target_byte_index < limit) {
// i. Let value be GetValueFromBuffer(srcBuffer, srcByteIndex, srcType, true, Unordered).
auto value = source.get_value_from_buffer(source_byte_index, ArrayBuffer::Unordered);
// ii. Perform SetValueInBuffer(targetBuffer, targetByteIndex, targetType, value, true, Unordered).
target.set_value_in_buffer(target_byte_index, value, ArrayBuffer::Unordered);
// iii. Set srcByteIndex to srcByteIndex + srcElementSize.
source_byte_index += source_element_size;