• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "ecmascript/builtins/builtins_typedarray.h"
17 #include "ecmascript/base/typed_array_helper-inl.h"
18 #include "ecmascript/builtins/builtins_array.h"
19 #include "ecmascript/ecma_string-inl.h"
20 #include "ecmascript/interpreter/interpreter.h"
21 #include "ecmascript/js_stable_array.h"
22 #include "ecmascript/object_fast_operator-inl.h"
23 
24 namespace panda::ecmascript::builtins {
25 using TypedArrayHelper = base::TypedArrayHelper;
26 using BuiltinsArray = builtins::BuiltinsArray;
27 using BuiltinsArrayBuffer = builtins::BuiltinsArrayBuffer;
28 
29 // 22.2.1
TypedArrayBaseConstructor(EcmaRuntimeCallInfo * argv)30 JSTaggedValue BuiltinsTypedArray::TypedArrayBaseConstructor(EcmaRuntimeCallInfo *argv)
31 {
32     ASSERT(argv);
33     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, BaseConstructor);
34     THROW_TYPE_ERROR_AND_RETURN(argv->GetThread(), "TypedArray Constructor cannot be called.",
35                                 JSTaggedValue::Exception());
36 }
37 
Int8ArrayConstructor(EcmaRuntimeCallInfo * argv)38 JSTaggedValue BuiltinsTypedArray::Int8ArrayConstructor(EcmaRuntimeCallInfo *argv)
39 {
40     ASSERT(argv);
41     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, Int8ArrayConstructor);
42     JSThread *thread = argv->GetThread();
43     return TypedArrayHelper::TypedArrayConstructor(argv, thread->GlobalConstants()->GetHandledInt8ArrayString(),
44                                                    DataViewType::INT8);
45 }
46 
Uint8ArrayConstructor(EcmaRuntimeCallInfo * argv)47 JSTaggedValue BuiltinsTypedArray::Uint8ArrayConstructor(EcmaRuntimeCallInfo *argv)
48 {
49     ASSERT(argv);
50     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, Uint8ArrayConstructor);
51     JSThread *thread = argv->GetThread();
52     return TypedArrayHelper::TypedArrayConstructor(argv, thread->GlobalConstants()->GetHandledUint8ArrayString(),
53                                                    DataViewType::UINT8);
54 }
55 
Uint8ClampedArrayConstructor(EcmaRuntimeCallInfo * argv)56 JSTaggedValue BuiltinsTypedArray::Uint8ClampedArrayConstructor(EcmaRuntimeCallInfo *argv)
57 {
58     ASSERT(argv);
59     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, Uint8ClampedArrayConstructor);
60     JSThread *thread = argv->GetThread();
61     return TypedArrayHelper::TypedArrayConstructor(argv,
62                                                    thread->GlobalConstants()->GetHandledUint8ClampedArrayString(),
63                                                    DataViewType::UINT8_CLAMPED);
64 }
65 
Int16ArrayConstructor(EcmaRuntimeCallInfo * argv)66 JSTaggedValue BuiltinsTypedArray::Int16ArrayConstructor(EcmaRuntimeCallInfo *argv)
67 {
68     ASSERT(argv);
69     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, Int16ArrayConstructor);
70     JSThread *thread = argv->GetThread();
71     return TypedArrayHelper::TypedArrayConstructor(argv, thread->GlobalConstants()->GetHandledInt16ArrayString(),
72                                                    DataViewType::INT16);
73 }
74 
Uint16ArrayConstructor(EcmaRuntimeCallInfo * argv)75 JSTaggedValue BuiltinsTypedArray::Uint16ArrayConstructor(EcmaRuntimeCallInfo *argv)
76 {
77     ASSERT(argv);
78     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, Uint16ArrayConstructor);
79     JSThread *thread = argv->GetThread();
80     return TypedArrayHelper::TypedArrayConstructor(argv, thread->GlobalConstants()->GetHandledUint16ArrayString(),
81                                                    DataViewType::UINT16);
82 }
83 
Int32ArrayConstructor(EcmaRuntimeCallInfo * argv)84 JSTaggedValue BuiltinsTypedArray::Int32ArrayConstructor(EcmaRuntimeCallInfo *argv)
85 {
86     ASSERT(argv);
87     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, Int32ArrayConstructor);
88     JSThread *thread = argv->GetThread();
89     return TypedArrayHelper::TypedArrayConstructor(argv, thread->GlobalConstants()->GetHandledInt32ArrayString(),
90                                                    DataViewType::INT32);
91 }
92 
Uint32ArrayConstructor(EcmaRuntimeCallInfo * argv)93 JSTaggedValue BuiltinsTypedArray::Uint32ArrayConstructor(EcmaRuntimeCallInfo *argv)
94 {
95     ASSERT(argv);
96     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, Uint32ArrayConstructor);
97     JSThread *thread = argv->GetThread();
98     return TypedArrayHelper::TypedArrayConstructor(argv, thread->GlobalConstants()->GetHandledUint32ArrayString(),
99                                                    DataViewType::UINT32);
100 }
101 
Float32ArrayConstructor(EcmaRuntimeCallInfo * argv)102 JSTaggedValue BuiltinsTypedArray::Float32ArrayConstructor(EcmaRuntimeCallInfo *argv)
103 {
104     ASSERT(argv);
105     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, Float32ArrayConstructor);
106     JSThread *thread = argv->GetThread();
107     return TypedArrayHelper::TypedArrayConstructor(argv, thread->GlobalConstants()->GetHandledFloat32ArrayString(),
108                                                    DataViewType::FLOAT32);
109 }
110 
Float64ArrayConstructor(EcmaRuntimeCallInfo * argv)111 JSTaggedValue BuiltinsTypedArray::Float64ArrayConstructor(EcmaRuntimeCallInfo *argv)
112 {
113     ASSERT(argv);
114     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, Float64ArrayConstructor);
115     JSThread *thread = argv->GetThread();
116     return TypedArrayHelper::TypedArrayConstructor(argv, thread->GlobalConstants()->GetHandledFloat64ArrayString(),
117                                                    DataViewType::FLOAT64);
118 }
119 
BigInt64ArrayConstructor(EcmaRuntimeCallInfo * argv)120 JSTaggedValue BuiltinsTypedArray::BigInt64ArrayConstructor(EcmaRuntimeCallInfo *argv)
121 {
122     ASSERT(argv);
123     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, BigInt64ArrayConstructor);
124     JSThread *thread = argv->GetThread();
125     return TypedArrayHelper::TypedArrayConstructor(argv, thread->GlobalConstants()->GetHandledBigInt64ArrayString(),
126                                                    DataViewType::BIGINT64);
127 }
128 
BigUint64ArrayConstructor(EcmaRuntimeCallInfo * argv)129 JSTaggedValue BuiltinsTypedArray::BigUint64ArrayConstructor(EcmaRuntimeCallInfo *argv)
130 {
131     ASSERT(argv);
132     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, BigUint64ArrayConstructor);
133     JSThread *thread = argv->GetThread();
134     return TypedArrayHelper::TypedArrayConstructor(argv, thread->GlobalConstants()->GetHandledBigUint64ArrayString(),
135                                                    DataViewType::BIGUINT64);
136 }
137 
FromUsingIteratorUndefinedValues(JSThread * thread,const JSHandle<JSTaggedValue> & thisHandle,const JSHandle<JSTaggedValue> source,const JSHandle<JSTaggedValue> & thisArgHandle,const JSHandle<JSTaggedValue> & mapfn)138 JSTaggedValue FromUsingIteratorUndefinedValues(JSThread *thread, const JSHandle<JSTaggedValue> &thisHandle,
139                                                const JSHandle<JSTaggedValue> source,
140                                                const JSHandle<JSTaggedValue> &thisArgHandle,
141                                                const JSHandle<JSTaggedValue> &mapfn)
142 {
143     // 3. If mapfn is undefined, let mapping be false.
144     // 4. Else,
145     //   a. If IsCallable(mapfn) is false, throw a TypeError exception.
146     //   b. Let mapping be true.
147     bool mapping = false;
148     if (!mapfn->IsUndefined()) {
149         if (!mapfn->IsCallable()) {
150             THROW_TYPE_ERROR_AND_RETURN(thread, "the mapfn is not callable.", JSTaggedValue::Exception());
151         }
152         mapping = true;
153     }
154     // 7. NOTE: source is not an Iterable so assume it is already an array-like object.
155     // 8. Let arrayLike be ! ToObject(source).
156     JSHandle<JSObject> arrayLikeObj = JSTaggedValue::ToObject(thread, source);
157     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
158     JSHandle<JSTaggedValue> arrayLike(arrayLikeObj);
159     // 9. Let len be ? LengthOfArrayLike(arrayLike).
160     JSHandle<JSTaggedValue> lengthKey = thread->GlobalConstants()->GetHandledLengthString();
161     JSHandle<JSTaggedValue> lenResult = JSTaggedValue::GetProperty(thread, arrayLike, lengthKey).GetValue();
162     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
163     JSTaggedNumber tLen = JSTaggedValue::ToLength(thread, lenResult);
164     // 6. ReturnIfAbrupt(relativeTarget).
165     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
166     int64_t len = tLen.GetNumber();
167     // 10. Let targetObj be ? TypedArrayCreate(C, « len »).
168     JSTaggedType args[1] = {JSTaggedValue(len).GetRawData()};
169     JSHandle<JSObject> targetObj = TypedArrayHelper::TypedArrayCreate(thread, thisHandle, 1, args);
170     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
171     // 11. Let k be 0.
172     // 12. Repeat, while k < len
173     //   a. Let Pk be ! ToString(k).
174     //   b. Let kValue be ? Get(arrayLike, Pk).
175     //   c. If mapping is true, then
176     //     i. Let mappedValue be ? Call(mapfn, thisArg, « kValue, k »).
177     //   d. Else, let mappedValue be kValue.
178     //   e. Perform ? Set(targetObj, Pk, mappedValue, true).
179     //   f. Set k to k + 1.
180     JSMutableHandle<JSTaggedValue> tKey(thread, JSTaggedValue::Undefined());
181     const uint32_t argsLength = 2;
182     int64_t k = 0;
183     JSHandle<JSTaggedValue> undefined = thread->GlobalConstants()->GetHandledUndefined();
184     JSMutableHandle<JSTaggedValue> kValue(thread, JSTaggedValue::Undefined());
185     JSHandle<JSTaggedValue> mapValue;
186     while (k < len) {
187         tKey.Update(JSTaggedValue(k));
188         kValue.Update(
189             ObjectFastOperator::FastGetPropertyByValue(thread, arrayLike.GetTaggedValue(), tKey.GetTaggedValue()));
190         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
191         if (mapping) {
192             EcmaRuntimeCallInfo *info =
193                 EcmaInterpreter::NewRuntimeCallInfo(thread, mapfn, thisArgHandle, undefined, argsLength);
194             RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
195             info->SetCallArg(kValue.GetTaggedValue(), tKey.GetTaggedValue());
196             JSTaggedValue callResult = JSFunction::Call(info);
197             RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
198             mapValue = JSHandle<JSTaggedValue>(thread, callResult);
199         } else {
200             mapValue = kValue;
201         }
202         ObjectFastOperator::FastSetPropertyByIndex(thread, targetObj.GetTaggedValue(), k, mapValue.GetTaggedValue());
203         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
204         k++;
205     }
206     // 13. Return targetObj.
207     return targetObj.GetTaggedValue();
208 }
209 
ProcessFromNotUndefinedValues(JSThread * thread,const CVector<JSHandle<JSTaggedValue>> & vec,const JSHandle<JSTaggedValue> & thisHandle,JSHandle<JSTaggedValue> & thisArgHandle,JSHandle<JSTaggedValue> & mapfn)210 JSTaggedValue ProcessFromNotUndefinedValues(JSThread *thread, const CVector<JSHandle<JSTaggedValue>> &vec,
211                                             const JSHandle<JSTaggedValue> &thisHandle,
212                                             JSHandle<JSTaggedValue> &thisArgHandle, JSHandle<JSTaggedValue> &mapfn)
213 {
214     // 3. If mapfn is undefined, let mapping be false.
215     // 4. Else,
216     //   a. If IsCallable(mapfn) is false, throw a TypeError exception.
217     //   b. Let mapping be true.
218     bool mapping = false;
219     if (!mapfn->IsUndefined()) {
220         if (!mapfn->IsCallable()) {
221             THROW_TYPE_ERROR_AND_RETURN(thread, "the mapfn is not callable.", JSTaggedValue::Exception());
222         }
223         mapping = true;
224     }
225     uint32_t len = vec.size();
226     JSTaggedType args[1] = {JSTaggedValue(len).GetRawData()};
227     JSHandle<JSObject> targetObj = TypedArrayHelper::TypedArrayCreate(thread, thisHandle, 1, args);
228     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
229     //   d. Let k be 0.
230     //   e. Repeat, while k < len
231     //     i. Let Pk be ! ToString(k).
232     //     ii. Let kValue be the first element of values and remove that element from values.
233     //     iii. If mapping is true, then
234     //       1. Let mappedValue be ? Call(mapfn, thisArg, « kValue, k »).
235     //     iv. Else, let mappedValue be kValue.
236     //     v. Perform ? Set(targetObj, Pk, mappedValue, true).
237     //     vi. Set k to k + 1.
238     JSMutableHandle<JSTaggedValue> tKey(thread, JSTaggedValue::Undefined());
239     JSMutableHandle<JSTaggedValue> mapValue(thread, JSTaggedValue::Undefined());
240     const uint32_t argsLength = 2;
241     uint32_t k = 0;
242     JSHandle<JSTaggedValue> undefined = thread->GlobalConstants()->GetHandledUndefined();
243     while (k < len) {
244         tKey.Update(JSTaggedValue(k));
245         JSHandle<JSTaggedValue> kValue = vec[k];
246         if (mapping) {
247             EcmaRuntimeCallInfo *info =
248                 EcmaInterpreter::NewRuntimeCallInfo(thread, mapfn, thisArgHandle, undefined, argsLength);
249             RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
250             info->SetCallArg(kValue.GetTaggedValue(), tKey.GetTaggedValue());
251             JSTaggedValue callResult = JSFunction::Call(info);
252             RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
253             mapValue.Update(callResult);
254         } else {
255             mapValue.Update(kValue.GetTaggedValue());
256         }
257         ObjectFastOperator::FastSetPropertyByIndex(thread, targetObj.GetTaggedValue(), k, mapValue.GetTaggedValue());
258         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
259         k++;
260     }
261     //   f. Assert: values is now an empty List.
262     //   g. Return targetObj.
263     return targetObj.GetTaggedValue();
264 }
265 
266 // 22.2.2.1 %TypedArray%.from ( source [ , mapfn [ , thisArg ] ] )
From(EcmaRuntimeCallInfo * argv)267 JSTaggedValue BuiltinsTypedArray::From(EcmaRuntimeCallInfo *argv)
268 {
269     ASSERT(argv);
270     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, From);
271     JSThread *thread = argv->GetThread();
272     [[maybe_unused]] EcmaHandleScope handleScope(thread);
273     JSHandle<GlobalEnv> env = thread->GetEcmaVM()->GetGlobalEnv();
274     // 1. Let C be the this value.
275     // 2. If IsConstructor(C) is false, throw a TypeError exception.
276     JSHandle<JSTaggedValue> thisHandle = GetThis(argv);
277     if (!thisHandle->IsConstructor()) {
278         THROW_TYPE_ERROR_AND_RETURN(thread, "the this value is not a Constructor.", JSTaggedValue::Exception());
279     }
280     JSHandle<JSTaggedValue> thisArgHandle = GetCallArg(argv, BuiltinsBase::ArgsPosition::THIRD);
281     // 3. If mapfn is undefined, let mapping be false.
282     // 4. Else,
283     //   a. If IsCallable(mapfn) is false, throw a TypeError exception.
284     //   b. Let mapping be true.
285     JSHandle<JSTaggedValue> mapfn = GetCallArg(argv, 1);
286     if (!mapfn->IsUndefined()) {
287         if (!mapfn->IsCallable()) {
288             THROW_TYPE_ERROR_AND_RETURN(thread, "the mapfn is not callable.", JSTaggedValue::Exception());
289         }
290     }
291     // 5. Let usingIterator be ? GetMethod(source, @@iterator).
292     JSHandle<JSTaggedValue> source = GetCallArg(argv, 0);
293     JSHandle<JSTaggedValue> iteratorSymbol = env->GetIteratorSymbol();
294     JSHandle<JSTaggedValue> usingIterator = JSObject::GetMethod(thread, source, iteratorSymbol);
295     // 6. If usingIterator is not undefined, then
296     //   a. Let values be ? IterableToList(source, usingIterator).
297     //   b. Let len be the number of elements in values.
298     //   c. Let targetObj be ? TypedArrayCreate(C, « len »).
299     if (!usingIterator->IsUndefined() && !TypedArrayHelper::IsNativeArrayIterator(thread, source, usingIterator)) {
300         CVector<JSHandle<JSTaggedValue>> vec;
301         JSHandle<JSTaggedValue> iterator = JSIterator::GetIterator(thread, source, usingIterator);
302         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
303         JSHandle<JSTaggedValue> next(thread, JSTaggedValue::True());
304         while (!next->IsFalse()) {
305             next = JSIterator::IteratorStep(thread, iterator);
306             RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
307             if (!next->IsFalse()) {
308                 JSHandle<JSTaggedValue> nextValue = JSIterator::IteratorValue(thread, next);
309                 RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, nextValue.GetTaggedValue());
310                 vec.push_back(nextValue);
311             }
312         }
313         return ProcessFromNotUndefinedValues(thread, vec, thisHandle, thisArgHandle, mapfn);
314     }
315     return FromUsingIteratorUndefinedValues(thread, thisHandle, source, thisArgHandle, mapfn);
316 }
317 
318 // 22.2.2.2 %TypedArray%.of ( ...items )
Of(EcmaRuntimeCallInfo * argv)319 JSTaggedValue BuiltinsTypedArray::Of(EcmaRuntimeCallInfo *argv)
320 {
321     ASSERT(argv);
322     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, Of);
323     JSThread *thread = argv->GetThread();
324     [[maybe_unused]] EcmaHandleScope handleScope(thread);
325     // 1. Let len be the actual number of arguments passed to this function.
326     uint32_t len = argv->GetArgsNumber();
327     // 2. Let items be the List of arguments passed to this function.
328     // 3. Let C be the this value.
329     JSHandle<JSTaggedValue> thisHandle = GetThis(argv);
330     // 4. If IsConstructor(C) is false, throw a TypeError exception.
331     if (!thisHandle->IsConstructor()) {
332         THROW_TYPE_ERROR_AND_RETURN(thread, "the this value is not a Constructor.", JSTaggedValue::Exception());
333     }
334     // 5. Let newObj be TypedArrayCreate(C, « len »).
335     JSTaggedType args[1] = {JSTaggedValue(len).GetRawData()};
336     JSHandle<JSObject> newObj = TypedArrayHelper::TypedArrayCreate(thread, thisHandle, 1, args);
337     // 6. ReturnIfAbrupt(newObj).
338     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
339     // 7. Let k be 0.
340     // 8. Repeat, while k < len
341     //   a. Let kValue be items[k].
342     //   b. Let Pk be ! ToString(k).
343     //   c. Perform ? Set(newObj, Pk, kValue, true).
344     //   d. ReturnIfAbrupt(status).
345     //   e. Set k to k + 1.
346     JSMutableHandle<JSTaggedValue> tKey(thread, JSTaggedValue::Undefined());
347     uint32_t k = 0;
348     while (k < len) {
349         tKey.Update(JSTaggedValue(k));
350         JSHandle<JSTaggedValue> kKey(JSTaggedValue::ToString(thread, tKey));
351         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
352         JSHandle<JSTaggedValue> kValue = GetCallArg(argv, k);
353         JSTaggedValue::SetProperty(thread, JSHandle<JSTaggedValue>::Cast(newObj), kKey, kValue, true);
354         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
355         k++;
356     }
357     // 9. Return newObj.
358     return newObj.GetTaggedValue();
359 }
360 
361 // 22.2.2.4
Species(EcmaRuntimeCallInfo * argv)362 JSTaggedValue BuiltinsTypedArray::Species(EcmaRuntimeCallInfo *argv)
363 {
364     ASSERT(argv);
365     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, Species);
366     // 1. Return the this value.
367     return GetThis(argv).GetTaggedValue();
368 }
369 
370 // prototype
371 // 22.2.3.1 get %TypedArray%.prototype.buffer
GetBuffer(EcmaRuntimeCallInfo * argv)372 JSTaggedValue BuiltinsTypedArray::GetBuffer(EcmaRuntimeCallInfo *argv)
373 {
374     ASSERT(argv);
375     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, GetBuffer);
376     JSThread *thread = argv->GetThread();
377     [[maybe_unused]] EcmaHandleScope handleScope(thread);
378     // 1. Let O be the this value.
379     JSHandle<JSTaggedValue> thisHandle = GetThis(argv);
380     // 2. If Type(O) is not Object, throw a TypeError exception.
381     if (!thisHandle->IsECMAObject()) {
382         THROW_TYPE_ERROR_AND_RETURN(thread, "This value is not an object.", JSTaggedValue::Exception());
383     }
384     // 3. If O does not have a [[ViewedArrayBuffer]] internal slot, throw a TypeError exception.
385     if (!thisHandle->IsTypedArray()) {
386         THROW_TYPE_ERROR_AND_RETURN(thread, "This value does not have a [[ViewedArrayBuffer]] internal slot.",
387                                     JSTaggedValue::Exception());
388     }
389     // 4. Let buffer be the value of O’s [[ViewedArrayBuffer]] internal slot.
390     JSHandle<JSTypedArray> typedArray = JSHandle<JSTypedArray>::Cast(thisHandle);
391     JSTaggedValue buffer = JSTypedArray::GetOffHeapBuffer(thread, typedArray);
392     // 5. Return buffer.
393     return buffer;
394 }
395 
396 // 22.2.3.2
GetByteLength(EcmaRuntimeCallInfo * argv)397 JSTaggedValue BuiltinsTypedArray::GetByteLength(EcmaRuntimeCallInfo *argv)
398 {
399     ASSERT(argv);
400     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, GetByteLength);
401     JSThread *thread = argv->GetThread();
402     [[maybe_unused]] EcmaHandleScope handleScope(thread);
403     // 1. Let O be the this value.
404     JSHandle<JSTaggedValue> thisHandle = GetThis(argv);
405     // 2. If Type(O) is not Object, throw a TypeError exception.
406     if (!thisHandle->IsECMAObject()) {
407         THROW_TYPE_ERROR_AND_RETURN(thread, "This value is not an object.", JSTaggedValue::Exception());
408     }
409     // 3. If O does not have a [[ViewedArrayBuffer]] internal slot, throw a TypeError exception.
410     if (!thisHandle->IsTypedArray()) {
411         THROW_TYPE_ERROR_AND_RETURN(thread, "This value does not have a [[ViewedArrayBuffer]] internal slot.",
412                                     JSTaggedValue::Exception());
413     }
414     // 4. Let buffer be the value of O’s [[ViewedArrayBuffer]] internal slot.
415     JSHandle<JSTypedArray> typeArrayObj = JSHandle<JSTypedArray>::Cast(thisHandle);
416     JSTaggedValue buffer = typeArrayObj->GetViewedArrayBufferOrByteArray(thread);
417     // 5. If IsDetachedBuffer(buffer) is true, return 0.
418     if (BuiltinsArrayBuffer::IsDetachedBuffer(thread, buffer)) {
419         return JSTaggedValue(0);
420     }
421     // 6. Let size be the value of O’s [[ByteLength]] internal slot.
422     // 7. Return size.
423     return JSTaggedValue(typeArrayObj->GetByteLength());
424 }
425 
426 // 22.2.3.3
GetByteOffset(EcmaRuntimeCallInfo * argv)427 JSTaggedValue BuiltinsTypedArray::GetByteOffset(EcmaRuntimeCallInfo *argv)
428 {
429     ASSERT(argv);
430     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, GetByteOffset);
431     JSThread *thread = argv->GetThread();
432     [[maybe_unused]] EcmaHandleScope handleScope(thread);
433     // 1. Let O be the this value.
434     JSHandle<JSTaggedValue> thisHandle = GetThis(argv);
435     // 2. If Type(O) is not Object, throw a TypeError exception.
436     if (!thisHandle->IsECMAObject()) {
437         THROW_TYPE_ERROR_AND_RETURN(thread, "This value is not an object.", JSTaggedValue::Exception());
438     }
439     // 3. If O does not have a [[ViewedArrayBuffer]] internal slot, throw a TypeError exception.
440     if (!thisHandle->IsTypedArray()) {
441         THROW_TYPE_ERROR_AND_RETURN(thread, "This value does not have a [[ViewedArrayBuffer]] internal slot.",
442                                     JSTaggedValue::Exception());
443     }
444     // 4. Let buffer be the value of O’s [[ViewedArrayBuffer]] internal slot.
445     JSHandle<JSTypedArray> typeArrayObj = JSHandle<JSTypedArray>::Cast(thisHandle);
446     JSTaggedValue buffer = typeArrayObj->GetViewedArrayBufferOrByteArray(thread);
447     // 5. If IsDetachedBuffer(buffer) is true, return 0.
448     if (BuiltinsArrayBuffer::IsDetachedBuffer(thread, buffer)) {
449         return JSTaggedValue(0);
450     }
451     // 6. Let offset be the value of O’s [[ByteOffset]] internal slot.
452     uint32_t offset = typeArrayObj->GetByteOffset();
453     // 7. Return offset.
454     return JSTaggedValue(offset);
455 }
456 
457 // 22.2.3.5
CopyWithin(EcmaRuntimeCallInfo * argv)458 JSTaggedValue BuiltinsTypedArray::CopyWithin(EcmaRuntimeCallInfo *argv)
459 {
460     ASSERT(argv);
461     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, CopyWithin);
462     if (!GetThis(argv)->IsTypedArray()) {
463         THROW_TYPE_ERROR_AND_RETURN(argv->GetThread(), "This is not a TypedArray.", JSTaggedValue::Exception());
464     }
465     return BuiltinsArray::CopyWithin(argv);
466 }
467 
468 // 22.2.3.6
Entries(EcmaRuntimeCallInfo * argv)469 JSTaggedValue BuiltinsTypedArray::Entries(EcmaRuntimeCallInfo *argv)
470 {
471     ASSERT(argv);
472     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, Entries);
473     JSThread *thread = argv->GetThread();
474     [[maybe_unused]] EcmaHandleScope handleScope(thread);
475     // 1. Let O be the this value.
476     JSHandle<JSTaggedValue> thisHandle = GetThis(argv);
477     // 2. Let valid be ValidateTypedArray(O).
478     TypedArrayHelper::ValidateTypedArray(thread, thisHandle);
479     // 3. ReturnIfAbrupt(valid).
480     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(argv->GetThread());
481     JSHandle<JSObject> self(thisHandle);
482     ObjectFactory *factory = thread->GetEcmaVM()->GetFactory();
483     // 4. Return CreateArrayIterator(O, "key+value").
484     JSHandle<JSArrayIterator> iter(factory->NewJSArrayIterator(self, IterationKind::KEY_AND_VALUE));
485     return iter.GetTaggedValue();
486 }
487 
488 // 22.2.3.7
Every(EcmaRuntimeCallInfo * argv)489 JSTaggedValue BuiltinsTypedArray::Every(EcmaRuntimeCallInfo *argv)
490 {
491     ASSERT(argv);
492     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, Every);
493     JSThread *thread = argv->GetThread();
494     [[maybe_unused]] EcmaHandleScope handleScope(thread);
495 
496     // 1. Let valid be ValidateTypedArray(O).
497     JSHandle<JSTaggedValue> thisHandle = GetThis(argv);
498     TypedArrayHelper::ValidateTypedArray(thread, thisHandle);
499     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
500     JSHandle<JSObject> thisObjHandle = JSTaggedValue::ToObject(thread, thisHandle);
501     // 2. ReturnIfAbrupt(O).
502     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
503     JSHandle<JSTaggedValue> thisObjVal(thisObjHandle);
504 
505     // 3. Let len be ToLength(Get(O, "length")).
506     uint32_t len = JSHandle<JSTypedArray>::Cast(thisObjHandle)->GetArrayLength();
507     // 4. ReturnIfAbrupt(len).
508     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
509     // 5. If IsCallable(callbackfn) is false, throw a TypeError exception.
510     JSHandle<JSTaggedValue> callbackFnHandle = GetCallArg(argv, 0);
511     if (!callbackFnHandle->IsCallable()) {
512         THROW_TYPE_ERROR_AND_RETURN(thread, "the callbackfun is not callable.", JSTaggedValue::Exception());
513     }
514 
515     // 6. If thisArg was supplied, let T be thisArg; else let T be undefined.
516     JSHandle<JSTaggedValue> thisArgHandle = GetCallArg(argv, 1);
517 
518     // 7. Let k be 0.
519     // 8. Repeat, while k < len
520     //   a. Let Pk be ToString(k).
521     //   b. Let kPresent be HasProperty(O, Pk).
522     //   c. ReturnIfAbrupt(kPresent).
523     //   d. If kPresent is true, then
524     //     i. Let kValue be Get(O, Pk).
525     //     ii. ReturnIfAbrupt(kValue).
526     //     iii. Let testResult be ToBoolean(Call(callbackfn, T, «kValue, k, O»)).
527     //     iv. ReturnIfAbrupt(testResult).
528     //     v. If testResult is false, return false.
529     //   e. Increase k by 1.
530     JSMutableHandle<JSTaggedValue> key(thread, JSTaggedValue::Undefined());
531     const uint32_t argsLength = 3;
532     JSHandle<JSTaggedValue> undefined = thread->GlobalConstants()->GetHandledUndefined();
533     uint32_t k = 0;
534     while (k < len) {
535         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
536         JSHandle<JSTaggedValue> kValue = JSTaggedValue::GetProperty(thread, thisObjVal, k).GetValue();
537         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
538         key.Update(JSTaggedValue(k));
539         EcmaRuntimeCallInfo *info =
540             EcmaInterpreter::NewRuntimeCallInfo(thread, callbackFnHandle, thisArgHandle, undefined, argsLength);
541         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
542         info->SetCallArg(kValue.GetTaggedValue(), key.GetTaggedValue(), thisObjVal.GetTaggedValue());
543         JSTaggedValue callResult = JSFunction::Call(info);
544         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
545         bool boolResult = callResult.ToBoolean();
546         if (!boolResult) {
547             return GetTaggedBoolean(false);
548         }
549         k++;
550     }
551 
552     // 9. Return true.
553     return GetTaggedBoolean(true);
554 }
555 
556 // 22.2.3.8
Fill(EcmaRuntimeCallInfo * argv)557 JSTaggedValue BuiltinsTypedArray::Fill(EcmaRuntimeCallInfo *argv)
558 {
559     ASSERT(argv);
560     JSThread *thread = argv->GetThread();
561     BUILTINS_API_TRACE(thread, TypedArray, Fill);
562     JSHandle<JSTaggedValue> thisHandle = GetThis(argv);
563     // 1. Let O be ToObject(this value).
564     JSHandle<JSObject> thisObjHandle = JSTaggedValue::ToObject(thread, thisHandle);
565     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
566     // 2. Let taRecord be ? ValidateTypedArray(O, SEQ-CST).
567     TypedArrayHelper::ValidateTypedArray(thread, thisHandle);
568     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
569     // 3. Let len be TypedArrayLength(taRecord).
570     JSHandle<JSTaggedValue> thisObjVal(thisObjHandle);
571     int64_t len = JSHandle<JSTypedArray>::Cast(thisObjVal)->GetArrayLength();
572     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
573     // 4. If O.[[ContentType]] is BIGINT, set value to ? ToBigInt(value).
574     // 5. Otherwise, set value to ? ToNumber(value).
575     JSHandle<JSTaggedValue> value = GetCallArg(argv, 0);
576     if (thisObjVal->IsTypedArray() || thisObjVal->IsSharedTypedArray()) {
577         ContentType contentType = JSHandle<JSTypedArray>::Cast(thisObjVal)->GetContentType();
578         if (contentType == ContentType::BigInt) {
579             value = JSHandle<JSTaggedValue>(thread, JSTaggedValue::ToBigInt(thread, value));
580         } else {
581             value = JSHandle<JSTaggedValue>(thread, JSTaggedValue::ToNumber(thread, value));
582         }
583         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
584     }
585     // 6. Let relativeStart be ? ToIntegerOrInfinity(start).
586     JSHandle<JSTaggedValue> startArg = GetCallArg(argv, 1);
587     JSTaggedNumber argStartTemp = JSTaggedValue::ToInteger(thread, startArg);
588     // 7. ReturnIfAbrupt(relativeStart).
589     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
590     double argStart = argStartTemp.GetNumber();
591     // 8. Else if relativeStart < 0, let startIndex be max(len + relativeStart, 0).
592     // 9. Else, let startIndex be min(relativeStart, len).
593     int64_t start = 0;
594     if (argStart < 0) {
595         double tempStart = argStart + len;
596         start = tempStart > 0 ? tempStart : 0;
597     } else {
598         start = argStart < len ? argStart : len;
599     }
600 
601     // 10. If end is undefined, let relativeEnd be len; else let relativeEnd be ? ToIntegerOrInfinity(end).
602     double argEnd = len;
603     JSHandle<JSTaggedValue> endArg = GetCallArg(argv, INDEX_TWO);
604     if (!endArg->IsUndefined()) {
605         JSTaggedNumber argEndTemp = JSTaggedValue::ToInteger(thread, endArg);
606         // 11. ReturnIfAbrupt(relativeEnd).
607         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
608         argEnd = argEndTemp.GetNumber();
609     }
610 
611     // 12. Else if relativeEnd < 0, let endIndex be max(len + relativeEnd, 0).
612     // 13. Else, let endIndex be min(relativeEnd, len).
613     int64_t end = len;
614     if (argEnd < 0) {
615         double tempEnd = argEnd + len;
616         end = tempEnd > 0 ? tempEnd : 0;
617     } else {
618         end = argEnd < len ? argEnd : len;
619     }
620 
621     // 14. Set taRecord to MakeTypedArrayWithBufferWitnessRecord(O, SEQ-CST).
622     // 15. If IsTypedArrayOutOfBounds(taRecord) is true, throw a TypeError exception.
623     TypedArrayHelper::ValidateTypedArray(thread, thisHandle);
624     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
625 
626     // 19. Repeat, while k < final
627     //   a. Let Pk be ! ToString(��(k)).
628     //   b. Perform ! Set(O, Pk, value, true).
629     //   c. Set k to k + 1.
630 
631     if (thisObjVal->IsTypedArray() || thisObjVal->IsSharedTypedArray()) {
632         bool result = JSTypedArray::FastTypedArrayFill(thread, thisObjVal, value, start, end);
633         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
634         if (result) {
635             return thisObjHandle.GetTaggedValue();
636         }
637     }
638 
639     int64_t k = start;
640     JSMutableHandle<JSTaggedValue> key(thread, JSTaggedValue::Undefined());
641     while (k < end) {
642         key.Update(JSTaggedValue(k));
643         JSArray::FastSetPropertyByValue(thread, thisObjVal, key, value);
644         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
645         k++;
646     }
647 
648     // 20. Return O.
649     return thisObjHandle.GetTaggedValue();
650 }
651 
652 // 22.2.3.9 %TypedArray%.prototype.filter ( callbackfn [ , thisArg ] )
Filter(EcmaRuntimeCallInfo * argv)653 JSTaggedValue BuiltinsTypedArray::Filter(EcmaRuntimeCallInfo *argv)
654 {
655     ASSERT(argv);
656     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, Filter);
657     JSThread *thread = argv->GetThread();
658     [[maybe_unused]] EcmaHandleScope handleScope(thread);
659     ObjectFactory *factory = thread->GetEcmaVM()->GetFactory();
660     // 1. Let O be the this value.
661     JSHandle<JSTaggedValue> thisHandle = GetThis(argv);
662     // 2. Let valid be ValidateTypedArray(O).
663     TypedArrayHelper::ValidateTypedArray(thread, thisHandle);
664     // 3. ReturnIfAbrupt(valid).
665     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
666 
667     JSHandle<JSTypedArray> thisObj(thisHandle);
668     // 4. Let len be the value of O’s [[ArrayLength]] internal slot.
669     uint32_t len = thisObj->GetArrayLength();
670     // 5. If IsCallable(callbackfn) is false, throw a TypeError exception.
671     JSHandle<JSTaggedValue> callbackFnHandle = GetCallArg(argv, 0);
672     if (!callbackFnHandle->IsCallable()) {
673         THROW_TYPE_ERROR_AND_RETURN(thread, "the callbackfun is not callable.", JSTaggedValue::Exception());
674     }
675     // 6. If thisArg was supplied, let T be thisArg; else let T be undefined.
676     JSHandle<JSTaggedValue> thisArgHandle = GetCallArg(argv, 1);
677 
678     // 10. Let kept be a new empty List.
679     JSHandle<TaggedArray> kept(factory->NewTaggedArray(len));
680 
681     // 11. Let k be 0.
682     // 12. Let captured be 0.
683     // 13. Repeat, while k < len
684     //   a. Let Pk be ToString(k).
685     //   b. Let kValue be Get(O, Pk).
686     //   c. ReturnIfAbrupt(kValue).
687     //   d. Let selected be ToBoolean(Call(callbackfn, T, «kValue, k, O»)).
688     //   e. ReturnIfAbrupt(selected).
689     //   f. If selected is true, then
690     //     i. Append kValue to the end of kept.
691     //     ii. Increase captured by 1.
692     //   g. Increase k by 1.
693     int32_t captured = 0;
694     JSMutableHandle<JSTaggedValue> tKey(thread, JSTaggedValue::Undefined());
695     JSHandle<JSTaggedValue> undefined = thread->GlobalConstants()->GetHandledUndefined();
696     JSMutableHandle<JSTaggedValue> kValue(thread, JSTaggedValue::Undefined());
697     for (uint32_t k = 0; k < len; k++) {
698         tKey.Update(JSTaggedValue(k));
699         kValue.Update(ObjectFastOperator::FastGetPropertyByValue(thread, thisHandle.GetTaggedValue(),
700                                                                  tKey.GetTaggedValue()));
701         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
702         EcmaRuntimeCallInfo *info =
703             EcmaInterpreter::NewRuntimeCallInfo(thread, callbackFnHandle, thisArgHandle,
704             undefined, 3); // 3: «kValue, k, O»
705         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
706         info->SetCallArg(kValue.GetTaggedValue(), tKey.GetTaggedValue(), thisHandle.GetTaggedValue());
707         JSTaggedValue callResult = JSFunction::Call(info);
708         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
709         if (callResult.ToBoolean()) {
710             kept->Set(thread, captured, kValue);
711             captured++;
712         }
713     }
714     // es11 9. Let A be ? TypedArraySpeciesCreate(O, « captured »).
715     JSTaggedType args[1] = {JSTaggedValue(captured).GetRawData()};
716     JSHandle<JSObject> newArrObj = TypedArrayHelper::TypedArraySpeciesCreate(thread, thisObj, 1, args);
717     // 15. ReturnIfAbrupt(A).
718     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
719     // 16. Let n be 0.
720     // 17. For each element e of kept
721     //   a. Let status be Set(A, ToString(n), e, true ).
722     //   b. ReturnIfAbrupt(status).
723     //   c. Increase n by 1.
724     JSMutableHandle<JSTaggedValue> valueHandle(thread, JSTaggedValue::Undefined());
725     JSMutableHandle<JSTaggedValue> ntKey(thread, JSTaggedValue::Undefined());
726     for (int32_t n = 0; n < captured; n++) {
727         valueHandle.Update(kept->Get(thread, n));
728         ntKey.Update(JSTaggedValue(n));
729         ObjectFastOperator::FastSetPropertyByValue(thread, newArrObj.GetTaggedValue(),
730                                                    ntKey.GetTaggedValue(), valueHandle.GetTaggedValue());
731         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
732     }
733     // 18. Return A.
734     return newArrObj.GetTaggedValue();
735 }
736 
737 // 22.2.3.10
Find(EcmaRuntimeCallInfo * argv)738 JSTaggedValue BuiltinsTypedArray::Find(EcmaRuntimeCallInfo *argv)
739 {
740     ASSERT(argv);
741     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, Find);
742     if (!GetThis(argv)->IsTypedArray()) {
743         THROW_TYPE_ERROR_AND_RETURN(argv->GetThread(), "This is not a TypedArray.", JSTaggedValue::Exception());
744     }
745     return BuiltinsArray::Find(argv);
746 }
747 
748 // 22.2.3.11
FindIndex(EcmaRuntimeCallInfo * argv)749 JSTaggedValue BuiltinsTypedArray::FindIndex(EcmaRuntimeCallInfo *argv)
750 {
751     ASSERT(argv);
752     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, FindIndex);
753     if (!GetThis(argv)->IsTypedArray()) {
754         THROW_TYPE_ERROR_AND_RETURN(argv->GetThread(), "This is not a TypedArray.", JSTaggedValue::Exception());
755     }
756     return BuiltinsArray::FindIndex(argv);
757 }
758 
759 // 22.2.3.12
ForEach(EcmaRuntimeCallInfo * argv)760 JSTaggedValue BuiltinsTypedArray::ForEach(EcmaRuntimeCallInfo *argv)
761 {
762     ASSERT(argv);
763     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, ForEach);
764     JSThread *thread = argv->GetThread();
765     [[maybe_unused]] EcmaHandleScope handleScope(thread);
766 
767     // 1. Let valid be ValidateTypedArray(O).
768     JSHandle<JSTaggedValue> thisHandle = GetThis(argv);
769     TypedArrayHelper::ValidateTypedArray(thread, thisHandle);
770     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
771     JSHandle<JSObject> thisObjHandle = JSTaggedValue::ToObject(thread, thisHandle);
772     // 2. ReturnIfAbrupt(O).
773     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
774     JSHandle<JSTaggedValue> thisObjVal(thisObjHandle);
775 
776     // 3. Let len be ToLength(Get(O, "length")).
777     uint32_t len = JSHandle<JSTypedArray>::Cast(thisObjHandle)->GetArrayLength();
778     // 4. ReturnIfAbrupt(len).
779     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
780 
781     // 5. If IsCallable(callbackfn) is false, throw a TypeError exception.
782     JSHandle<JSTaggedValue> callbackFnHandle = GetCallArg(argv, 0);
783     if (!callbackFnHandle->IsCallable()) {
784         THROW_TYPE_ERROR_AND_RETURN(thread, "the callbackfun is not callable.", JSTaggedValue::Exception());
785     }
786 
787     // 6. If thisArg was supplied, let T be thisArg; else let T be undefined.
788     JSHandle<JSTaggedValue> thisArgHandle = GetCallArg(argv, 1);
789 
790     // 7. Let k be 0.
791     // 8. Repeat, while k < len
792     //   a. Let Pk be ToString(k).
793     //   b. Let kPresent be HasProperty(O, Pk).
794     //   c. ReturnIfAbrupt(kPresent).
795     //   d. If kPresent is true, then
796     //     i. Let kValue be Get(O, Pk).
797     //     ii. ReturnIfAbrupt(kValue).
798     //     iii. Let funcResult be Call(callbackfn, T, «kValue, k, O»).
799     //     iv. ReturnIfAbrupt(funcResult).
800     //   e. Increase k by 1.
801     JSMutableHandle<JSTaggedValue> key(thread, JSTaggedValue::Undefined());
802     const uint32_t argsLength = 3;
803     JSHandle<JSTaggedValue> undefined = thread->GlobalConstants()->GetHandledUndefined();
804     uint32_t k = 0;
805     while (k < len) {
806         JSHandle<JSTaggedValue> kValue = JSTaggedValue::GetProperty(thread, thisObjVal, k).GetValue();
807         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
808         key.Update(JSTaggedValue(k));
809         EcmaRuntimeCallInfo *info =
810             EcmaInterpreter::NewRuntimeCallInfo(thread, callbackFnHandle, thisArgHandle, undefined, argsLength);
811         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
812         info->SetCallArg(kValue.GetTaggedValue(), key.GetTaggedValue(), thisObjVal.GetTaggedValue());
813         JSTaggedValue funcResult = JSFunction::Call(info);
814         RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, funcResult);
815         k++;
816     }
817 
818     // 9. Return undefined.
819     return JSTaggedValue::Undefined();
820 }
821 
822 // 22.2.3.13
IndexOf(EcmaRuntimeCallInfo * argv)823 JSTaggedValue BuiltinsTypedArray::IndexOf(EcmaRuntimeCallInfo *argv)
824 {
825     ASSERT(argv);
826     JSThread *thread = argv->GetThread();
827     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, IndexOf);
828     TypedArrayHelper::ValidateTypedArray(thread, GetThis(argv));
829     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
830     return BuiltinsArray::IndexOf(argv);
831 }
832 
833 // 22.2.3.14
Join(EcmaRuntimeCallInfo * argv)834 JSTaggedValue BuiltinsTypedArray::Join(EcmaRuntimeCallInfo *argv)
835 {
836     ASSERT(argv);
837     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, Join);
838     JSThread *thread = argv->GetThread();
839     [[maybe_unused]] EcmaHandleScope handleScope(thread);
840 
841     JSHandle<JSTaggedValue> thisHandle = GetThis(argv);
842 
843     if (!thisHandle->IsTypedArray()) {
844         THROW_TYPE_ERROR_AND_RETURN(argv->GetThread(), "This is not a TypedArray.", JSTaggedValue::Exception());
845     }
846 
847     uint32_t length = JSHandle<JSTypedArray>::Cast(thisHandle)->GetArrayLength();
848 
849     JSHandle<JSTaggedValue> sepHandle = GetCallArg(argv, 0);
850     int sep = ',';
851     uint32_t sepLength = 1;
852     JSHandle<EcmaString> sepStringHandle;
853     if (!sepHandle->IsUndefined()) {
854         if (sepHandle->IsString()) {
855             sepStringHandle = JSHandle<EcmaString>::Cast(sepHandle);
856         } else {
857             sepStringHandle = JSTaggedValue::ToString(thread, sepHandle);
858             RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
859         }
860         if (EcmaStringAccessor(sepStringHandle).IsUtf8() && EcmaStringAccessor(sepStringHandle).GetLength() == 1) {
861             // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic)
862             sep = EcmaStringAccessor(sepStringHandle).Get(thread, 0);
863         } else if (EcmaStringAccessor(sepStringHandle).GetLength() == 0) {
864             sep = BuiltinsTypedArray::SeparatorFlag::MINUS_TWO;
865             sepLength = 0;
866         } else {
867             sep = BuiltinsTypedArray::SeparatorFlag::MINUS_ONE;
868             sepLength = EcmaStringAccessor(sepStringHandle).GetLength();
869         }
870     }
871     if (length == 0) {
872         const GlobalEnvConstants *globalConst = thread->GlobalConstants();
873         return globalConst->GetEmptyString();
874     }
875     uint64_t allocateLength = 0;
876     bool isOneByte = (sep != BuiltinsTypedArray::SeparatorFlag::MINUS_ONE) ||
877         EcmaStringAccessor(sepStringHandle).IsUtf8();
878     CVector<JSHandle<EcmaString>> vec;
879     JSMutableHandle<JSTaggedValue> elementHandle(thread, JSTaggedValue::Undefined());
880     const GlobalEnvConstants *globalConst = thread->GlobalConstants();
881     if (length <= 1) {
882         // sep unused, set isOneByte to default(true)
883         isOneByte = true;
884     }
885     for (uint32_t k = 0; k < length; k++) {
886         JSTaggedValue element = JSTypedArray::GetProperty(thread, thisHandle, k).GetValue().GetTaggedValue();
887         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
888         if (!element.IsUndefinedOrNull() && !element.IsHole()) {
889             if (!element.IsString()) {
890                 elementHandle.Update(element);
891                 JSHandle<EcmaString> strElement = JSTaggedValue::ToString(thread, elementHandle);
892                 RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
893                 element = strElement.GetTaggedValue();
894             }
895             auto nextStr = EcmaString::Cast(element.GetTaggedObject());
896             JSHandle<EcmaString> nextStrHandle(thread, nextStr);
897             vec.push_back(nextStrHandle);
898             isOneByte = EcmaStringAccessor(nextStr).IsUtf8() ? isOneByte : false;
899             allocateLength += EcmaStringAccessor(nextStr).GetLength();
900         } else {
901             vec.push_back(JSHandle<EcmaString>(globalConst->GetHandledEmptyString()));
902         }
903     }
904     allocateLength += static_cast<uint64_t>(sepLength) * (length - 1);
905     if (allocateLength > BaseString::MAX_STRING_LENGTH) {
906         THROW_RANGE_ERROR_AND_RETURN(thread, "Invalid string length", JSTaggedValue::Exception());
907     }
908     auto newString =
909     EcmaStringAccessor::CreateLineString(thread->GetEcmaVM(), static_cast<size_t>(allocateLength), isOneByte);
910     int current = 0;
911     DISALLOW_GARBAGE_COLLECTION;
912     for (uint32_t k = 0; k < length; k++) {
913         if (k > 0) {
914             if (sep >= 0) {
915                 EcmaStringAccessor(newString).Set(current, static_cast<uint16_t>(sep));
916             } else if (sep != BuiltinsTypedArray::SeparatorFlag::MINUS_TWO) {
917                 EcmaStringAccessor::ReadData(thread,
918                     newString, *sepStringHandle, current, allocateLength - static_cast<size_t>(current), sepLength);
919             }
920             current += static_cast<int>(sepLength);
921         }
922         JSHandle<EcmaString> nextStr = vec[k];
923         int nextLength = static_cast<int>(EcmaStringAccessor(nextStr).GetLength());
924         EcmaStringAccessor::ReadData(thread, newString, *nextStr, current,
925             allocateLength - static_cast<size_t>(current), nextLength);
926         current += nextLength;
927     }
928     ASSERT_PRINT(
929         isOneByte == EcmaStringAccessor::CanBeCompressed(newString), "isOneByte does not match the real value!");
930     return JSTaggedValue(newString);
931 }
932 
933 // 22.2.3.15
Keys(EcmaRuntimeCallInfo * argv)934 JSTaggedValue BuiltinsTypedArray::Keys(EcmaRuntimeCallInfo *argv)
935 {
936     ASSERT(argv);
937     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, Keys);
938     JSThread *thread = argv->GetThread();
939     [[maybe_unused]] EcmaHandleScope handleScope(thread);
940     // 1. Let O be the this value.
941     JSHandle<JSTaggedValue> thisHandle = GetThis(argv);
942     // 2. Let valid be ValidateTypedArray(O).
943     TypedArrayHelper::ValidateTypedArray(thread, thisHandle);
944     // 3. ReturnIfAbrupt(valid).
945     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(argv->GetThread());
946     JSHandle<JSObject> self(thisHandle);
947     ObjectFactory *factory = thread->GetEcmaVM()->GetFactory();
948     // 4. Return CreateArrayIterator(O, "key").
949     JSHandle<JSArrayIterator> iter(factory->NewJSArrayIterator(self, IterationKind::KEY));
950     return iter.GetTaggedValue();
951 }
952 
953 // 22.2.3.16
LastIndexOf(EcmaRuntimeCallInfo * argv)954 JSTaggedValue BuiltinsTypedArray::LastIndexOf(EcmaRuntimeCallInfo *argv)
955 {
956     ASSERT(argv);
957     JSThread *thread = argv->GetThread();
958     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, LastIndexOf);
959     TypedArrayHelper::ValidateTypedArray(thread, GetThis(argv));
960     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
961     return BuiltinsArray::LastIndexOf(argv);
962 }
963 
964 // 22.2.3.17
GetLength(EcmaRuntimeCallInfo * argv)965 JSTaggedValue BuiltinsTypedArray::GetLength(EcmaRuntimeCallInfo *argv)
966 {
967     ASSERT(argv);
968     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, GetLength);
969     JSThread *thread = argv->GetThread();
970     [[maybe_unused]] EcmaHandleScope handleScope(thread);
971     // 1. Let O be the this value.
972     JSHandle<JSTaggedValue> thisHandle = GetThis(argv);
973     // 2. If Type(O) is not Object, throw a TypeError exception.
974     if (!thisHandle->IsECMAObject()) {
975         THROW_TYPE_ERROR_AND_RETURN(thread, "This value is not an object.", JSTaggedValue::Exception());
976     }
977     // 3. If O does not have a [[TypedArrayName]] internal slot, throw a TypeError exception.
978     if (!thisHandle->IsTypedArray()) {
979         THROW_TYPE_ERROR_AND_RETURN(thread, "This value does not have a [[TypedArrayName]] internal slot.",
980                                     JSTaggedValue::Exception());
981     }
982     // 4. Assert: O has [[ViewedArrayBuffer]] and [[ArrayLength]] internal slots.
983     // 5. Let buffer be the value of O’s [[ViewedArrayBuffer]] internal slot.
984     JSTaggedValue buffer = JSHandle<JSTypedArray>::Cast(thisHandle)->GetViewedArrayBufferOrByteArray(thread);
985     // 6. If IsDetachedBuffer(buffer) is true, return 0.
986     if (BuiltinsArrayBuffer::IsDetachedBuffer(thread, buffer)) {
987         return JSTaggedValue(0);
988     }
989     // 7. Let length be the value of O’s [[ArrayLength]] internal slot.
990     uint32_t length = JSHandle<JSTypedArray>(thisHandle)->GetArrayLength();
991     // 8. Return length.
992     return JSTaggedValue(length);
993 }
994 
995 // 22.2.3.18 %TypedArray%.prototype.map ( callbackfn [ , thisArg ] )
Map(EcmaRuntimeCallInfo * argv)996 JSTaggedValue BuiltinsTypedArray::Map(EcmaRuntimeCallInfo *argv)
997 {
998     ASSERT(argv);
999     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, Map);
1000     JSThread *thread = argv->GetThread();
1001     [[maybe_unused]] EcmaHandleScope handleScope(thread);
1002     // 1. Let O be the this value.
1003     JSHandle<JSTaggedValue> thisHandle = GetThis(argv);
1004     // 2. Let valid be ValidateTypedArray(O).
1005     TypedArrayHelper::ValidateTypedArray(thread, thisHandle);
1006     // 3. ReturnIfAbrupt(valid).
1007     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1008 
1009     JSHandle<JSTypedArray> thisObj(thisHandle);
1010     // 4. Let len be the value of O’s [[ArrayLength]] internal slot.
1011     uint32_t len = thisObj->GetArrayLength();
1012     // 5. If IsCallable(callbackfn) is false, throw a TypeError exception.
1013     JSHandle<JSTaggedValue> callbackfnHandle = GetCallArg(argv, 0);
1014     if (!callbackfnHandle->IsCallable()) {
1015         THROW_TYPE_ERROR_AND_RETURN(thread, "the callbackfun is not callable.", JSTaggedValue::Exception());
1016     }
1017     // 6. If thisArg was supplied, let T be thisArg; else let T be undefined.
1018     JSHandle<JSTaggedValue> thisArgHandle = GetCallArg(argv, 1);
1019     // es11 5. Let A be ? TypedArraySpeciesCreate(O, « len »).
1020     JSTaggedType args[1] = {JSTaggedValue(len).GetRawData()};
1021     JSHandle<JSObject> newArrObj = TypedArrayHelper::TypedArraySpeciesCreate(thread, thisObj, 1, args); // 1: one arg.
1022     // 11. ReturnIfAbrupt(A).
1023     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1024 
1025     // 12. Let k be 0.
1026     // 13. Repeat, while k < len
1027     //   a. Let Pk be ToString(k).
1028     //   b. Let kValue be Get(O, Pk).
1029     //   c. ReturnIfAbrupt(kValue).
1030     //   d. Let mappedValue be Call(callbackfn, T, «kValue, k, O»).
1031     //   e. ReturnIfAbrupt(mappedValue).
1032     //   f. Let status be Set(A, Pk, mappedValue, true ).
1033     //   g. ReturnIfAbrupt(status).
1034     //   h. Increase k by 1.
1035     JSMutableHandle<JSTaggedValue> key(thread, JSTaggedValue::Undefined());
1036     JSMutableHandle<JSTaggedValue> mapValue(thread, JSTaggedValue::Undefined());
1037     JSMutableHandle<JSTaggedValue> kValue(thread, JSTaggedValue::Undefined());
1038     const uint32_t argsLength = 3;
1039     JSHandle<JSTaggedValue> undefined = thread->GlobalConstants()->GetHandledUndefined();
1040     for (uint32_t k = 0; k < len; k++) {
1041         key.Update(JSTaggedValue(k));
1042         kValue.Update(ObjectFastOperator::FastGetPropertyByValue(thread, thisHandle.GetTaggedValue(),
1043                                                                  key.GetTaggedValue()));
1044         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1045         EcmaRuntimeCallInfo *info =
1046             EcmaInterpreter::NewRuntimeCallInfo(thread, callbackfnHandle, thisArgHandle, undefined, argsLength);
1047         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1048         info->SetCallArg(kValue.GetTaggedValue(), key.GetTaggedValue(), thisHandle.GetTaggedValue());
1049         JSTaggedValue callResult = JSFunction::Call(info);
1050         mapValue.Update(callResult);
1051         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1052         ObjectFastOperator::FastSetPropertyByValue(thread, newArrObj.GetTaggedValue(),
1053                                                    key.GetTaggedValue(), mapValue.GetTaggedValue());
1054         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1055     }
1056 
1057     // 14. Return A.
1058     return newArrObj.GetTaggedValue();
1059 }
1060 
1061 // 22.2.3.19
Reduce(EcmaRuntimeCallInfo * argv)1062 JSTaggedValue BuiltinsTypedArray::Reduce(EcmaRuntimeCallInfo *argv)
1063 {
1064     ASSERT(argv);
1065     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, Reduce);
1066     if (!GetThis(argv)->IsTypedArray()) {
1067         THROW_TYPE_ERROR_AND_RETURN(argv->GetThread(), "This is not a TypedArray.", JSTaggedValue::Exception());
1068     }
1069     return BuiltinsArray::Reduce(argv);
1070 }
1071 
1072 // 22.2.3.20
ReduceRight(EcmaRuntimeCallInfo * argv)1073 JSTaggedValue BuiltinsTypedArray::ReduceRight(EcmaRuntimeCallInfo *argv)
1074 {
1075     ASSERT(argv);
1076     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, ReduceRight);
1077     if (!GetThis(argv)->IsTypedArray()) {
1078         THROW_TYPE_ERROR_AND_RETURN(argv->GetThread(), "This is not a TypedArray.", JSTaggedValue::Exception());
1079     }
1080     return BuiltinsArray::ReduceRight(argv);
1081 }
1082 
1083 // 22.2.3.21
Reverse(EcmaRuntimeCallInfo * argv)1084 JSTaggedValue BuiltinsTypedArray::Reverse(EcmaRuntimeCallInfo *argv)
1085 {
1086     ASSERT(argv);
1087     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, Reverse);
1088     JSThread *thread = argv->GetThread();
1089     [[maybe_unused]] EcmaHandleScope handleScope(thread);
1090 
1091     JSHandle<JSTaggedValue> thisHandle = GetThis(argv);
1092     TypedArrayHelper::ValidateTypedArray(thread, thisHandle);
1093     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1094 
1095     // 1. Let O be ToObject(this value).
1096     JSHandle<JSObject> thisObjHandle = JSTaggedValue::ToObject(thread, thisHandle);
1097     // 2. ReturnIfAbrupt(O).
1098     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1099     JSHandle<JSTaggedValue> thisObjVal(thisObjHandle);
1100 
1101     // 3. Let len be O.[[ArrayLength]]
1102     int64_t len = JSHandle<JSTypedArray>::Cast(thisHandle)->GetArrayLength();
1103 
1104     // 4. ReturnIfAbrupt(len).
1105     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1106 
1107     // 5. Let middle be floor(len/2).
1108     int64_t middle = std::floor(len / 2);
1109 
1110     // 6. Let lower be 0.
1111     int64_t lower = 0;
1112 
1113     // 7. Repeat, while lower ≠ middle,
1114     //     a. Let upper be len - lower - 1.
1115     //     b. Let upperP be ! ToString(��(upper)).
1116     //     c. Let lowerP be ! ToString(��(lower)).
1117     //     d. Let lowerValue be ! Get(O, lowerP).
1118     //     e. Let upperValue be ! Get(O, upperP).
1119     //     f. Perform ! Set(O, lowerP, upperValue, true).
1120     //     g. Perform ! Set(O, upperP, lowerValue, true).
1121     //     h. Set lower to lower + 1.
1122     JSMutableHandle<JSTaggedValue> lowerP(thread, JSTaggedValue::Undefined());
1123     JSMutableHandle<JSTaggedValue> upperP(thread, JSTaggedValue::Undefined());
1124     JSHandle<JSTaggedValue> lowerValueHandle(thread, JSTaggedValue::Undefined());
1125     JSHandle<JSTaggedValue> upperValueHandle(thread, JSTaggedValue::Undefined());
1126     while (lower != middle) {
1127         int64_t upper = len - lower - 1;
1128         lowerP.Update(JSTaggedValue(lower));
1129         upperP.Update(JSTaggedValue(upper));
1130         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1131         lowerValueHandle = JSArray::FastGetPropertyByValue(thread, thisObjVal, lowerP);
1132         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1133         upperValueHandle = JSArray::FastGetPropertyByValue(thread, thisObjVal, upperP);
1134         JSArray::FastSetPropertyByValue(thread, thisObjVal, lowerP, upperValueHandle);
1135         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1136         JSArray::FastSetPropertyByValue(thread, thisObjVal, upperP, lowerValueHandle);
1137         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1138         lower++;
1139     }
1140 
1141     // 8. Return O .
1142     return thisObjHandle.GetTaggedValue();
1143 }
1144 
1145 // 22.2.3.22 %TypedArray%.prototype.set ( overloaded [ , offset ])
Set(EcmaRuntimeCallInfo * argv)1146 JSTaggedValue BuiltinsTypedArray::Set(EcmaRuntimeCallInfo *argv)
1147 {
1148     ASSERT(argv);
1149     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, Set);
1150     JSThread *thread = argv->GetThread();
1151     [[maybe_unused]] EcmaHandleScope handleScope(thread);
1152     // 1. Assert: array is any ECMAScript language value other than an Object with a [[TypedArrayName]] internal slot.
1153     // If it is such an Object, the definition in 22.2.3.22.2 applies.
1154     // 2. Let target be the this value.
1155     JSHandle<JSTaggedValue> target = GetThis(argv);
1156     // 3. If Type(target) is not Object, throw a TypeError exception.
1157     if (!target->IsECMAObject()) {
1158         THROW_TYPE_ERROR_AND_RETURN(thread, "This value is not an object.", JSTaggedValue::Exception());
1159     }
1160     JSHandle<JSTypedArray> targetObj(target);
1161     // 4. If target does not have a [[TypedArrayName]] internal slot, throw a TypeError exception.
1162     if (!target->IsTypedArray()) {
1163         THROW_TYPE_ERROR_AND_RETURN(thread, "This value does not have a [[TypedArrayName]] internal slot.",
1164                                     JSTaggedValue::Exception());
1165     }
1166 
1167     // 5. Assert: target has a [[ViewedArrayBuffer]] internal slot.
1168     // 6. Let targetOffset be ToInteger (offset).
1169     const JSHandle<JSTaggedValue> srcOffset = GetCallArg(argv, 1);
1170     uint64_t targetOffset = 0;
1171     if (srcOffset->IsInt()) {
1172         if (srcOffset->GetInt() < 0) {
1173             THROW_RANGE_ERROR_AND_RETURN(thread, "The targetOffset of This value is less than 0.",
1174                                          JSTaggedValue::Exception());
1175         }
1176         targetOffset = static_cast<uint64_t>(srcOffset->GetInt());
1177     } else {
1178         JSTaggedNumber tTargetOffset = JSTaggedValue::ToInteger(thread, srcOffset);
1179         // 7. ReturnIfAbrupt(targetOffset).
1180         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1181         double rawTargetOffset = tTargetOffset.GetNumber();
1182         // 8. If targetOffset < 0, throw a RangeError exception.
1183         if (rawTargetOffset < 0) {
1184             THROW_RANGE_ERROR_AND_RETURN(thread, "The targetOffset of This value is less than 0.",
1185                                          JSTaggedValue::Exception());
1186         } else if (rawTargetOffset == base::POSITIVE_INFINITY) {
1187             THROW_RANGE_ERROR_AND_RETURN(thread, "The targetOffset is infinty, which is greater than targetLength.",
1188                                          JSTaggedValue::Exception());
1189         } else {
1190             targetOffset = static_cast<uint64_t>(rawTargetOffset);
1191         }
1192     }
1193     // 9. Let targetBuffer be the value of target’s [[ViewedArrayBuffer]] internal slot.
1194     JSHandle<JSTaggedValue> targetBuffer(thread, targetObj->GetViewedArrayBufferOrByteArray(thread));
1195     // 10. If IsDetachedBuffer(targetBuffer) is true, throw a TypeError exception.
1196     if (BuiltinsArrayBuffer::IsDetachedBuffer(thread, targetBuffer.GetTaggedValue())) {
1197         THROW_TYPE_ERROR_AND_RETURN(thread, "The targetBuffer of This value is detached buffer.",
1198                                     JSTaggedValue::Exception());
1199     }
1200     // 11. Let targetLength be the value of target’s [[ArrayLength]] internal slot.
1201     // 12. Let targetName be the String value of target’s [[TypedArrayName]] internal slot.
1202     // 13. Let targetElementSize be the Number value of the Element Size value specified in Table 49 for targetName.
1203     // 14. Let targetType be the String value of the Element Type value in Table 49 for targetName.
1204     // 15. Let targetByteOffset be the value of target’s [[ByteOffset]] internal slot.
1205     uint32_t targetLength = targetObj->GetArrayLength();
1206     DataViewType targetType = TypedArrayHelper::GetType(targetObj);
1207     uint32_t targetElementSize = TypedArrayHelper::GetSizeFromType(targetType);
1208     uint32_t targetByteOffset = targetObj->GetByteOffset();
1209 
1210     JSHandle<JSTaggedValue> argArray = GetCallArg(argv, 0);
1211 
1212     // 22.2.3.22.1 %TypedArray%.prototype.set (array [ , offset ] )
1213     if (!argArray->IsTypedArray()) {
1214         if (argArray->IsStableJSArray(thread)) {
1215             uint32_t length = JSHandle<JSArray>::Cast(argArray)->GetArrayLength();
1216             JSHandle<JSObject> argObj(argArray);
1217             uint32_t elemLength = ElementAccessor::GetElementsLength(thread, argObj);
1218             // Load On Demand check
1219             if (elemLength >= length) {
1220                 return JSStableArray::FastCopyFromArrayToTypedArray(thread, targetObj, targetType,
1221                                                                     targetOffset, length, argObj);
1222             }
1223         }
1224         // 16. Let src be ToObject(array).
1225         JSHandle<JSObject> src = JSTaggedValue::ToObject(thread, argArray);
1226         // 17. ReturnIfAbrupt(src).
1227         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1228         // 18. Let srcLength be ToLength(Get(src, "length")).
1229         JSHandle<JSTaggedValue> lengthKey = thread->GlobalConstants()->GetHandledLengthString();
1230         JSHandle<JSTaggedValue> lenResult(thread,
1231             ObjectFastOperator::FastGetPropertyByValue(thread,
1232                                                        JSHandle<JSTaggedValue>::Cast(src).GetTaggedValue(),
1233                                                        lengthKey.GetTaggedValue()));
1234         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1235         JSTaggedNumber tSrcLen = JSTaggedValue::ToLength(thread, lenResult);
1236         // 19. ReturnIfAbrupt(srcLength).
1237         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1238         uint64_t srcLen = static_cast<uint64_t>(tSrcLen.GetNumber());
1239         // 20. If srcLength + targetOffset > targetLength, throw a RangeError exception.
1240         if (srcLen + targetOffset > targetLength) {
1241             THROW_RANGE_ERROR_AND_RETURN(thread, "The sum of srcLength and targetOffset is greater than targetLength.",
1242                                          JSTaggedValue::Exception());
1243         }
1244         // 21. Let targetByteIndex be targetOffset × targetElementSize + targetByteOffset.
1245         ASSERT((targetOffset * static_cast<uint64_t>(targetElementSize) +
1246             static_cast<uint64_t>(targetByteOffset)) <= static_cast<uint64_t>(UINT32_MAX));
1247         uint32_t targetByteIndex = static_cast<uint32_t>(targetOffset * targetElementSize + targetByteOffset);
1248         // 22. Let k be 0.
1249         // 23. Let limit be targetByteIndex + targetElementSize × srcLength.
1250         uint32_t k = 0;
1251         ASSERT((static_cast<uint64_t>(targetElementSize) * srcLen +
1252             static_cast<uint64_t>(targetByteIndex)) <= static_cast<uint64_t>(UINT32_MAX));
1253         uint32_t limit = targetByteIndex + targetElementSize * srcLen;
1254         // 24. Repeat, while targetByteIndex < limit
1255         //   a. Let Pk be ToString(k).
1256         //   b. If target.[[ContentType]] is BigInt, set value to ? ToBigInt(value).
1257         //   c. Otherwise, set value to ? ToNumber(value).
1258         //   d. If IsDetachedBuffer(targetBuffer) is true, throw a TypeError exception.
1259         //   e. Perform SetValueInBuffer(targetBuffer, targetByteIndex, targetType, kNumber).
1260         //   f. Set k to k + 1.
1261         //   g. Set targetByteIndex to targetByteIndex + targetElementSize.
1262         JSMutableHandle<JSTaggedValue> tKey(thread, JSTaggedValue::Hole());
1263         JSMutableHandle<JSTaggedValue> kValue(thread, JSTaggedValue::Hole());
1264         JSMutableHandle<JSTaggedValue> kNumberHandle(thread, JSTaggedValue::Hole());
1265         ContentType contentType = JSHandle<JSTypedArray>::Cast(target)->GetContentType();
1266         while (targetByteIndex < limit) {
1267             tKey.Update(JSTaggedValue(k));
1268             JSHandle<JSTaggedValue> kKey(JSTaggedValue::ToString(thread, tKey));
1269             RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1270             kValue.Update(ObjectFastOperator::FastGetPropertyByValue(
1271                 thread, JSHandle<JSTaggedValue>::Cast(src).GetTaggedValue(), kKey.GetTaggedValue()));
1272             RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1273             if (BuiltinsArrayBuffer::IsDetachedBuffer(thread, targetBuffer.GetTaggedValue())) {
1274                 THROW_TYPE_ERROR_AND_RETURN(thread, "The targetBuffer of This value is detached buffer.",
1275                                             JSTaggedValue::Exception());
1276             }
1277             if (contentType == ContentType::BigInt) {
1278                 kNumberHandle.Update(JSTaggedValue::ToBigInt(thread, kValue));
1279             } else {
1280                 kNumberHandle.Update(JSTaggedValue::ToNumber(thread, kValue));
1281             }
1282             RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1283             BuiltinsArrayBuffer::SetValueInBuffer(thread, targetBuffer.GetTaggedValue(), targetByteIndex,
1284                                                   targetType, kNumberHandle, true);
1285             RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1286             k++;
1287             targetByteIndex = targetByteIndex + targetElementSize;
1288         }
1289         // 25. Return undefined.
1290         return JSTaggedValue::Undefined();
1291     }
1292 
1293     // 22.2.3.22.2 %TypedArray%.prototype.set(typedArray [, offset ] )
1294     JSHandle<JSTypedArray> typedArray(argArray);
1295     // 12. Let srcBuffer be the value of typedArray’s [[ViewedArrayBuffer]] internal slot.
1296     // 13. If IsDetachedBuffer(srcBuffer) is true, throw a TypeError exception.
1297     JSTaggedValue srcBuffer = typedArray->GetViewedArrayBufferOrByteArray(thread);
1298     JSHandle<JSTaggedValue> srcBufferHandle(thread, srcBuffer);
1299     if (BuiltinsArrayBuffer::IsDetachedBuffer(thread, srcBuffer)) {
1300         THROW_TYPE_ERROR_AND_RETURN(thread, "The ArrayBuffer of typedArray is detached buffer.",
1301                                     JSTaggedValue::Exception());
1302     }
1303 
1304     ContentType objContentType = JSHandle<JSTypedArray>::Cast(target)->GetContentType();
1305     ContentType argArrayContentType = JSHandle<JSTypedArray>::Cast(argArray)->GetContentType();
1306     if (argArrayContentType != objContentType) {
1307         THROW_TYPE_ERROR_AND_RETURN(thread,
1308                                     "argArrayContentType is not equal objContentType.",
1309                                     JSTaggedValue::Exception());
1310     }
1311     // 18. Let srcName be the String value of typedArray’s [[TypedArrayName]] internal slot.
1312     // 19. Let srcType be the String value of the Element Type value in Table 49 for srcName .
1313     // 20. Let srcElementSize be the Number value of the Element Size value specified in Table 49 for srcName.
1314     // 21. Let srcLength be the value of typedArray’s [[ArrayLength]] internal slot.
1315     // 22. Let srcByteOffset be the value of typedArray’s [[ByteOffset]] internal slot.
1316     JSHandle<JSTaggedValue> srcName(thread, typedArray->GetTypedArrayName(thread));
1317     DataViewType srcType = JSTypedArray::GetTypeFromName(thread, srcName);
1318     uint32_t srcElementSize = TypedArrayHelper::GetSizeFromType(srcType);
1319     uint32_t srcLength = typedArray->GetArrayLength();
1320     uint32_t srcByteOffset = typedArray->GetByteOffset();
1321     // 23. If srcLength + targetOffset > targetLength, throw a RangeError exception.
1322     if (srcLength + targetOffset > targetLength) {
1323         THROW_RANGE_ERROR_AND_RETURN(thread, "The sum of srcLength and targetOffset is greater than targetLength.",
1324                                      JSTaggedValue::Exception());
1325     }
1326     // 24. If SameValue(srcBuffer, targetBuffer) is true, then
1327     //   a. Let srcBuffer be CloneArrayBuffer(targetBuffer, srcByteOffset, %ArrayBuffer%).
1328     //   b. NOTE: %ArrayBuffer% is used to clone targetBuffer because is it known to not have any observable
1329     //      side-effects.
1330     //   c. ReturnIfAbrupt(srcBuffer).
1331     //   d. Let srcByteIndex be 0.
1332     // 25. Else, let srcByteIndex be srcByteOffset.
1333     uint32_t srcByteIndex = 0;
1334     if (JSTaggedValue::SameValue(thread, srcBufferHandle.GetTaggedValue(), targetBuffer.GetTaggedValue())) {
1335         JSHandle<GlobalEnv> env = thread->GetEcmaVM()->GetGlobalEnv();
1336         srcBuffer =
1337             BuiltinsArrayBuffer::CloneArrayBuffer(thread, targetBuffer, srcByteOffset, env->GetArrayBufferFunction());
1338         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1339         srcBufferHandle = JSHandle<JSTaggedValue>(thread, srcBuffer);
1340         srcByteIndex = 0;
1341     } else {
1342         srcByteIndex = srcByteOffset;
1343     }
1344     // 26. Let targetByteIndex be targetOffset × targetElementSize + targetByteOffset.
1345     ASSERT((targetOffset * static_cast<uint64_t>(targetElementSize) +
1346             static_cast<uint64_t>(targetByteOffset)) <= static_cast<uint64_t>(UINT32_MAX));
1347     uint32_t targetByteIndex = static_cast<uint32_t>(targetOffset) * targetElementSize + targetByteOffset;
1348     // 27. Let limit be targetByteIndex + targetElementSize × srcLength.
1349     ASSERT((static_cast<uint64_t>(targetElementSize) * static_cast<uint64_t>(srcLength) +
1350             static_cast<uint64_t>(targetByteIndex)) <= static_cast<uint64_t>(UINT32_MAX));
1351     uint32_t limit = targetByteIndex + targetElementSize * srcLength;
1352     uint32_t count = (limit - targetByteIndex) > 0 ? (limit - targetByteIndex) : 0;
1353     // 28. If SameValue(srcType, targetType) is false, then
1354     //   a. Repeat, while targetByteIndex < limit
1355     //     i. Let value be GetValueFromBuffer(srcBuffer, srcByteIndex, srcType).
1356     //     ii. Perform SetValueInBuffer (targetBuffer, targetByteIndex, targetType, value).
1357     //     iii. Set srcByteIndex to srcByteIndex + srcElementSize.
1358     //     iv. Set targetByteIndex to targetByteIndex + targetElementSize.
1359     JSMutableHandle<JSTaggedValue> value(thread, JSTaggedValue::Undefined());
1360     if (srcType != targetType) {
1361         while (targetByteIndex < limit) {
1362             JSTaggedValue taggedData =
1363                 BuiltinsArrayBuffer::GetValueFromBuffer(thread, srcBufferHandle.GetTaggedValue(),
1364                                                         srcByteIndex, srcType, true);
1365             value.Update(taggedData);
1366             BuiltinsArrayBuffer::SetValueInBuffer(thread, targetBuffer.GetTaggedValue(), targetByteIndex,
1367                                                   targetType, value, true);
1368             RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1369             srcByteIndex = srcByteIndex + srcElementSize;
1370             targetByteIndex = targetByteIndex + targetElementSize;
1371         }
1372     } else if (count > 0) {
1373         // 29. Else,
1374         //   a. NOTE: If srcType and targetType are the same the transfer must be performed in a manner that preserves
1375         //   the bit-level encoding of the source data.
1376         //   b. Repeat, while targetByteIndex < limit
1377         //     i. Let value be GetValueFromBuffer(srcBuffer, srcByteIndex, "Uint8").
1378         //     ii. Perform SetValueInBuffer (targetBuffer, targetByteIndex, "Uint8", value).
1379         //     iii. Set srcByteIndex to srcByteIndex + 1.
1380         //     iv. Set targetByteIndex to targetByteIndex + 1.
1381         void *srcBuf = BuiltinsArrayBuffer::GetDataPointFromBuffer(thread, srcBufferHandle.GetTaggedValue(),
1382             srcByteIndex);
1383         void *targetBuf = BuiltinsArrayBuffer::GetDataPointFromBuffer(thread, targetBuffer.GetTaggedValue(),
1384             targetByteIndex);
1385         if (memcpy_s(targetBuf, srcLength * srcElementSize, srcBuf, srcLength * srcElementSize) != EOK) {
1386             LOG_FULL(FATAL) << "memcpy_s failed";
1387             UNREACHABLE();
1388         }
1389     }
1390     // 30. Return undefined.
1391     return JSTaggedValue::Undefined();
1392 }  // namespace panda::ecmascript::builtins
1393 
1394 // 22.2.3.23 %TypedArray%.prototype.slice ( start, end )
Slice(EcmaRuntimeCallInfo * argv)1395 JSTaggedValue BuiltinsTypedArray::Slice(EcmaRuntimeCallInfo *argv)
1396 {
1397     ASSERT(argv);
1398     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, Slice);
1399     JSThread *thread = argv->GetThread();
1400     [[maybe_unused]] EcmaHandleScope handleScope(thread);
1401     // 1. Let O be the this value.
1402     JSHandle<JSTaggedValue> thisHandle = GetThis(argv);
1403     // 2. Let valid be ValidateTypedArray(O).
1404     TypedArrayHelper::ValidateTypedArray(thread, thisHandle);
1405     // 3. ReturnIfAbrupt(valid).
1406     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1407 
1408     JSHandle<JSTypedArray> thisObj(thisHandle);
1409     // 4. Let len be the value of O’s [[ArrayLength]] internal slot.
1410     uint32_t len = thisObj->GetArrayLength();
1411 
1412     // 5. Let relativeStart be ToInteger(start).
1413     JSTaggedNumber tRelativeStart = JSTaggedValue::ToInteger(thread, GetCallArg(argv, 0));
1414     // 6. ReturnIfAbrupt(relativeStart).
1415     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1416     double relativeStart = tRelativeStart.GetNumber();
1417     // 7. If relativeStart < 0, let k be max((len + relativeStart),0); else let k be min(relativeStart, len).
1418 
1419     uint32_t k = relativeStart < 0 ?
1420                     std::max((static_cast<double>(len) + relativeStart), 0.0) :
1421                     std::min(relativeStart, static_cast<double>(len));
1422     // 8. If end is undefined, let relativeEnd be len; else let relativeEnd be ToInteger(end).
1423     double relativeEnd = len;
1424     JSHandle<JSTaggedValue> end = GetCallArg(argv, 1);
1425     if (!end->IsUndefined()) {
1426         JSTaggedNumber tRelativeEnd = JSTaggedValue::ToInteger(thread, end);
1427         // 9. ReturnIfAbrupt(relativeEnd).
1428         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1429         relativeEnd = tRelativeEnd.GetNumber();
1430     }
1431 
1432     // 10. If relativeEnd < 0, let final be max((len + relativeEnd),0); else let final be min(relativeEnd, len).
1433 
1434     uint32_t final = relativeEnd < 0 ?
1435                         std::max((static_cast<double>(len) + relativeEnd), 0.0) :
1436                         std::min(relativeEnd, static_cast<double>(len));
1437     // 11. Let count be max(final – k, 0).
1438     uint32_t count = final > k ? (final - k) : 0;
1439     // es11 9. Let A be ? TypedArraySpeciesCreate(O, « count »).
1440     JSTaggedType args[1] = {JSTaggedValue(count).GetRawData()};
1441     JSHandle<JSObject> newArrObj = TypedArrayHelper::TypedArraySpeciesCreate(thread, thisObj, 1, args);
1442     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1443     // 17. Let srcName be the String value of O’s [[TypedArrayName]] internal slot.
1444     // 18. Let srcType be the String value of the Element Type value in Table 49 for srcName.
1445     JSHandle<JSTaggedValue> srcName(thread, thisObj->GetTypedArrayName(thread));
1446     DataViewType srcType = JSTypedArray::GetTypeFromName(thread, srcName);
1447     // 19. Let targetName be the String value of A’s [[TypedArrayName]] internal slot.
1448     // 20. Let targetType be the String value of the Element Type value in Table 49 for targetName.
1449     JSHandle<JSTaggedValue> targetName(thread, JSTypedArray::Cast(*newArrObj)->GetTypedArrayName(thread));
1450     DataViewType targetType = JSTypedArray::GetTypeFromName(thread, targetName);
1451     // 21. If SameValue(srcType, targetType) is false, then
1452     //   a. Let n be 0.
1453     //   b. Repeat, while k < final
1454     //     i. Let Pk be ToString(k).
1455     //     ii. Let kValue be Get(O, Pk).
1456     //     iii. ReturnIfAbrupt(kValue).
1457     //     iv. Let status be Set(A, ToString(n), kValue, true ).
1458     //     v. ReturnIfAbrupt(status).
1459     //     vi. Increase k by 1.
1460     //     vii. Increase n by 1.
1461     JSMutableHandle<JSTaggedValue> tKey(thread, JSTaggedValue::Undefined());
1462     JSMutableHandle<JSTaggedValue> kValue(thread, JSTaggedValue::Undefined());
1463     JSMutableHandle<JSTaggedValue> ntKey(thread, JSTaggedValue::Undefined());
1464     if (srcType != targetType) {
1465         uint32_t n = 0;
1466         while (k < final) {
1467             tKey.Update(JSTaggedValue(k));
1468             kValue.Update(ObjectFastOperator::FastGetPropertyByValue(thread, thisHandle.GetTaggedValue(),
1469                                                                      tKey.GetTaggedValue()));
1470             RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1471             ntKey.Update(JSTaggedValue(n));
1472             ObjectFastOperator::FastSetPropertyByValue(thread, newArrObj.GetTaggedValue(),
1473                                                        ntKey.GetTaggedValue(), kValue.GetTaggedValue());
1474             RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1475             n++;
1476             k++;
1477         }
1478     } else if (count > 0) {
1479         // 22. Else if count > 0,
1480         //   a. Let srcBuffer be the value of O’s [[ViewedArrayBuffer]] internal slot.
1481         //   b. If IsDetachedBuffer(srcBuffer) is true, throw a TypeError exception.
1482         JSTaggedValue srcBuffer = thisObj->GetViewedArrayBufferOrByteArray(thread);
1483         if (!srcBuffer.IsSendableArrayBuffer() && BuiltinsArrayBuffer::IsDetachedBuffer(thread, srcBuffer)) {
1484             THROW_TYPE_ERROR_AND_RETURN(thread, "The ArrayBuffer of this value is detached buffer.",
1485                                         JSTaggedValue::Exception());
1486         }
1487         if (srcBuffer.IsSendableArrayBuffer() && BuiltinsSendableArrayBuffer::IsDetachedBuffer(thread, srcBuffer)) {
1488             THROW_TYPE_ERROR_AND_RETURN(thread, "The SendableArrayBuffer of this value is detached sendable buffer.",
1489                                         JSTaggedValue::Exception());
1490         }
1491         //   c. Let targetBuffer be the value of A’s [[ViewedArrayBuffer]] internal slot.
1492         JSTaggedValue targetBuffer = JSTypedArray::Cast(*newArrObj)->GetViewedArrayBufferOrByteArray(thread);
1493         //   d. Let elementSize be the Number value of the Element Size value specified in Table 49 for srcType.
1494         uint32_t elementSize = TypedArrayHelper::GetSizeFromType(srcType);
1495         //   e. NOTE: If srcType and targetType are the same the transfer must be performed in a manner that
1496         //   preserves the bit-level encoding of the source data.
1497         //   f. Let srcByteOffset be the value of O’s[[ByteOffset]] internal slot.
1498         uint32_t srcByteOffset = thisObj->GetByteOffset();
1499         //   h. Let srcByteIndex be (k × elementSize) + srcByteOffset.
1500         uint32_t srcByteIndex = k * elementSize + srcByteOffset;
1501         //   g. Let targetByteIndex be A.[[ByteOffset]].
1502         uint32_t targetByteIndex = JSTypedArray::Cast(*newArrObj)->GetByteOffset();
1503         //   i. Repeat, while targetByteIndex < count × elementSize
1504         //     i. Let value be GetValueFromBuffer(srcBuffer, srcByteIndex, "Uint8").
1505         //     ii. Perform SetValueInBuffer (targetBuffer, targetByteIndex, "Uint8", value).
1506         //     iii. Increase srcByteIndex by 1.
1507         //     iv. Increase targetByteIndex by 1.
1508         uint8_t *srcBuf = (uint8_t *)BuiltinsArrayBuffer::GetDataPointFromBuffer(thread, srcBuffer, srcByteIndex);
1509         uint8_t *targetBuf =
1510             (uint8_t *)BuiltinsArrayBuffer::GetDataPointFromBuffer(thread, targetBuffer, targetByteIndex);
1511         if (srcBuffer != targetBuffer && memmove_s(
1512             targetBuf, elementSize * count, srcBuf, elementSize * count) != EOK) {
1513             LOG_FULL(FATAL) << "memcpy_s failed";
1514             UNREACHABLE();
1515         }
1516         while (srcBuffer == targetBuffer && count > 0) {
1517             count--;
1518             if (memcpy_s(targetBuf, elementSize, srcBuf, elementSize) != EOK) {
1519                 LOG_FULL(FATAL) << "memcpy_s failed";
1520                 UNREACHABLE();
1521             }
1522             srcBuf += elementSize;
1523             targetBuf += elementSize;
1524         }
1525     }
1526     // 23. Return A.
1527     return newArrObj.GetTaggedValue();
1528 }
1529 
1530 // 22.2.3.24
Some(EcmaRuntimeCallInfo * argv)1531 JSTaggedValue BuiltinsTypedArray::Some(EcmaRuntimeCallInfo *argv)
1532 {
1533     ASSERT(argv);
1534     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, Some);
1535     if (!GetThis(argv)->IsTypedArray()) {
1536         THROW_TYPE_ERROR_AND_RETURN(argv->GetThread(), "This is not a TypedArray.", JSTaggedValue::Exception());
1537     }
1538     JSThread *thread = argv->GetThread();
1539     [[maybe_unused]] EcmaHandleScope handleScope(thread);
1540 
1541     // 1. Let O be ToObject(this value).
1542     JSHandle<JSTaggedValue> thisHandle = GetThis(argv);
1543 
1544     // 3. Let len be ToLength(Get(O, "length")).
1545     int64_t len = JSHandle<JSTypedArray>::Cast(thisHandle)->GetArrayLength();
1546 
1547     // 4. If IsCallable(callbackfn) is false, throw a TypeError exception.
1548     JSHandle<JSTaggedValue> callbackFnHandle = GetCallArg(argv, 0);
1549     if (!callbackFnHandle->IsCallable()) {
1550         THROW_TYPE_ERROR_AND_RETURN(thread, "the callbackfun is not callable.", JSTaggedValue::Exception());
1551     }
1552 
1553     // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
1554     JSHandle<JSTaggedValue> thisArgHandle = GetCallArg(argv, 1);
1555 
1556     // 6. Repeat, while k < len,
1557     //     a. Let Pk be ! ToString(��(k)).
1558     //     b. Let kValue be ! Get(O, Pk).
1559     //     c. Let testResult be ToBoolean(? Call(callback, thisArg, « kValue, ��(k), O »)).
1560     //     d. If testResult is true, return true.
1561     //     e. Set k to k + 1.
1562     JSMutableHandle<JSTaggedValue> key(thread, JSTaggedValue::Undefined());
1563     JSMutableHandle<JSTaggedValue> kValue(thread, JSTaggedValue::Undefined());
1564     uint32_t k = 0;
1565     JSTaggedValue callResult = GetTaggedBoolean(false);
1566     while (k < len) {
1567         key.Update(JSTaggedValue(k));
1568         kValue.Update(JSArray::FastGetPropertyByValue(thread, thisHandle, key));
1569         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1570         const uint32_t argsLength = 3; // 3: «kValue, k, O»
1571         JSHandle<JSTaggedValue> undefined = thread->GlobalConstants()->GetHandledUndefined();
1572         EcmaRuntimeCallInfo *info =
1573             EcmaInterpreter::NewRuntimeCallInfo(thread, callbackFnHandle, thisArgHandle, undefined, argsLength);
1574         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1575         info->SetCallArg(kValue.GetTaggedValue(), key.GetTaggedValue(), thisHandle.GetTaggedValue());
1576         callResult = JSFunction::Call(info);
1577         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1578         if (callResult.ToBoolean()) {
1579             return GetTaggedBoolean(true);
1580         }
1581         k++;
1582     }
1583     // 8. Return false.
1584     return GetTaggedBoolean(false);
1585 }
1586 
1587 // 22.2.3.25
Sort(EcmaRuntimeCallInfo * argv)1588 JSTaggedValue BuiltinsTypedArray::Sort(EcmaRuntimeCallInfo *argv)
1589 {
1590     ASSERT(argv);
1591     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, Sort);
1592     JSThread *thread = argv->GetThread();
1593     [[maybe_unused]] EcmaHandleScope handleScope(thread);
1594 
1595     // 1. Let obj be ToObject(this value).
1596     JSHandle<JSTaggedValue> thisHandle = GetThis(argv);
1597     if (!thisHandle->IsTypedArray()) {
1598         THROW_TYPE_ERROR_AND_RETURN(argv->GetThread(), "This is not a TypedArray.", JSTaggedValue::Exception());
1599     }
1600 
1601     JSHandle<JSObject> thisObjHandle = JSTaggedValue::ToObject(thread, thisHandle);
1602     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1603     JSHandle<JSTaggedValue> thisObjVal(thisObjHandle);
1604 
1605     JSHandle<JSTaggedValue> buffer;
1606     buffer = JSHandle<JSTaggedValue>(thread, TypedArrayHelper::ValidateTypedArray(thread, thisHandle));
1607     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1608     uint32_t len = JSHandle<JSTypedArray>::Cast(thisObjHandle)->GetArrayLength();
1609 
1610     JSHandle<JSTaggedValue> callbackFnHandle = GetCallArg(argv, 0);
1611     if (!callbackFnHandle->IsUndefined() && !callbackFnHandle->IsCallable()) {
1612         THROW_TYPE_ERROR_AND_RETURN(thread, "Callable is false", JSTaggedValue::Exception());
1613     }
1614     JSMutableHandle<JSTaggedValue> presentValue(thread, JSTaggedValue::Undefined());
1615     JSMutableHandle<JSTaggedValue> middleValue(thread, JSTaggedValue::Undefined());
1616     JSMutableHandle<JSTaggedValue> previousValue(thread, JSTaggedValue::Undefined());
1617     JSMutableHandle<JSTaggedValue> key1(thread, JSTaggedValue::Undefined());
1618     JSMutableHandle<JSTaggedValue> key(thread, JSTaggedValue::Undefined());
1619     JSMutableHandle<JSTaggedValue> key2(thread, JSTaggedValue::Undefined());
1620     for (uint32_t i = 1; i < len; i++) {
1621         uint32_t beginIndex = 0;
1622         uint32_t endIndex = i;
1623         key.Update(JSTaggedValue(i));
1624         presentValue.Update(ObjectFastOperator::FastGetPropertyByValue(thread, thisObjHandle.GetTaggedValue(),
1625                                                                        key.GetTaggedValue()));
1626         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1627         while (beginIndex < endIndex) {
1628             uint32_t middleIndex = beginIndex + (endIndex - beginIndex) / 2;  // 2 : half
1629             key1.Update(JSTaggedValue(middleIndex));
1630             middleValue.Update(ObjectFastOperator::FastGetPropertyByValue(thread, thisObjHandle.GetTaggedValue(),
1631                                                                           key1.GetTaggedValue()));
1632             RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1633             int32_t compareResult = TypedArrayHelper::SortCompare(thread, callbackFnHandle, buffer,
1634                                                                   middleValue, presentValue);
1635             RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1636             compareResult > 0 ? (endIndex = middleIndex) : (beginIndex = middleIndex + 1);
1637         }
1638 
1639         if (endIndex < i) {
1640             for (uint32_t j = i; j > endIndex; j--) {
1641                 key2.Update(JSTaggedValue(j - 1));
1642                 previousValue.Update(
1643                     ObjectFastOperator::FastGetPropertyByValue(thread, thisObjHandle.GetTaggedValue(),
1644                                                                key2.GetTaggedValue()));
1645                 RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1646                 ObjectFastOperator::FastSetPropertyByIndex(thread, thisObjHandle.GetTaggedValue(), j,
1647                                                            previousValue.GetTaggedValue());
1648                 RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1649             }
1650             ObjectFastOperator::FastSetPropertyByIndex(thread, thisObjHandle.GetTaggedValue(), endIndex,
1651                                                        presentValue.GetTaggedValue());
1652             RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1653         }
1654     }
1655     return thisObjHandle.GetTaggedValue();
1656 }
1657 
1658 // 22.2.3.26 %TypedArray%.prototype.subarray( [ begin [ , end ] ] )
Subarray(EcmaRuntimeCallInfo * argv)1659 JSTaggedValue BuiltinsTypedArray::Subarray(EcmaRuntimeCallInfo *argv)
1660 {
1661     ASSERT(argv);
1662     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, Subarray);
1663     JSThread *thread = argv->GetThread();
1664     [[maybe_unused]] EcmaHandleScope handleScope(thread);
1665     // 1. Let O be the this value.
1666     JSHandle<JSTaggedValue> thisHandle = GetThis(argv);
1667     // 2. If Type(O) is not Object, throw a TypeError exception.
1668     if (!thisHandle->IsECMAObject()) {
1669         THROW_TYPE_ERROR_AND_RETURN(thread, "This value is not an object.", JSTaggedValue::Exception());
1670     }
1671     JSHandle<JSTypedArray> thisObj(thisHandle);
1672     // 3. If O does not have a [[TypedArrayName]] internal slot, throw a TypeError exception.
1673     if (!thisHandle->IsTypedArray()) {
1674         THROW_TYPE_ERROR_AND_RETURN(thread, "This value does not have a [[TypedArrayName]] internal slot.",
1675                                     JSTaggedValue::Exception());
1676     }
1677     // 4. Assert: O has a [[ViewedArrayBuffer]] internal slot.
1678     // 6. Let srcLength be the value of O’s [[ArrayLength]] internal slot.
1679     uint32_t srcLength = thisObj->GetArrayLength();
1680     // 7. Let relativeBegin be ToInteger(begin).
1681     JSTaggedNumber tRelativeBegin = JSTaggedValue::ToInteger(thread, GetCallArg(argv, 0));
1682     // 8. ReturnIfAbrupt(relativeBegin).
1683     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1684     double relativeBegin = tRelativeBegin.GetNumber();
1685 
1686     uint32_t beginIndex = 0;
1687     // 9. If relativeBegin < 0, let beginIndex be max((srcLength + relativeBegin), 0); else let beginIndex be
1688     // min(relativeBegin, srcLength).
1689     if (relativeBegin < 0) {
1690         double tempBeginIndex = relativeBegin + static_cast<double>(srcLength);
1691         beginIndex = tempBeginIndex > 0 ? static_cast<uint32_t>(tempBeginIndex) : 0;
1692     } else {
1693         beginIndex = relativeBegin < static_cast<double>(srcLength) ?
1694                         static_cast<uint32_t>(relativeBegin) : srcLength;
1695     }
1696 
1697     // 10. If end is undefined, let relativeEnd be srcLength; else, let relativeEnd be ToInteger(end).
1698     double relativeEnd = srcLength;
1699     JSHandle<JSTaggedValue> end = GetCallArg(argv, 1);
1700     if (!end->IsUndefined()) {
1701         JSTaggedNumber tRelativeEnd = JSTaggedValue::ToInteger(thread, end);
1702         // 11. ReturnIfAbrupt(relativeEnd).
1703         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1704         relativeEnd = tRelativeEnd.GetNumber();
1705     }
1706     // 12. If relativeEnd < 0, let endIndex be max((srcLength + relativeEnd), 0); else let endIndex be
1707     // min(relativeEnd, srcLength).
1708     uint32_t endIndex;
1709     if (relativeEnd < 0) {
1710         double tempEndIndex = relativeEnd + static_cast<double>(srcLength);
1711         endIndex = tempEndIndex > 0 ? static_cast<uint32_t>(tempEndIndex) : 0;
1712     } else {
1713         endIndex = relativeEnd < static_cast<double>(srcLength) ?
1714                         static_cast<uint32_t>(relativeEnd) : srcLength;
1715     }
1716     // 13. Let newLength be max(endIndex – beginIndex, 0).
1717     uint32_t newLength = endIndex > beginIndex ? (endIndex - beginIndex) : 0;
1718     // 14. Let constructorName be the String value of O’s [[TypedArrayName]] internal slot.
1719     // 15. Let elementSize be the Number value of the Element Size value specified in Table 49 for constructorName.
1720     // 16. Let srcByteOffset be the value of O’s [[ByteOffset]] internal slot.
1721     // 17. Let beginByteOffset be srcByteOffset + beginIndex × elementSize.
1722     JSHandle<JSTaggedValue> constructorName(thread, thisObj->GetTypedArrayName(thread));
1723     DataViewType elementType = JSTypedArray::GetTypeFromName(thread, constructorName);
1724     uint32_t elementSize = TypedArrayHelper::GetSizeFromType(elementType);
1725     uint32_t srcByteOffset = thisObj->GetByteOffset();
1726     ASSERT((static_cast<uint64_t>(srcByteOffset) + static_cast<uint64_t>(beginIndex) *
1727             static_cast<uint64_t>(elementSize)) <= static_cast<uint64_t>(UINT32_MAX));
1728     uint32_t beginByteOffset = srcByteOffset + beginIndex * elementSize;
1729     JSTaggedValue buffer = JSTypedArray::GetOffHeapBuffer(thread, thisObj);
1730     // 21. Let argumentsList be «buffer, beginByteOffset, newLength».
1731     // 5. Let buffer be the value of O’s [[ViewedArrayBuffer]] internal slot.
1732     // 22. Return Construct(constructor, argumentsList).
1733     const uint32_t argsLength = 3;
1734     JSTaggedType args[argsLength] = {
1735         buffer.GetRawData(),
1736         JSTaggedValue(beginByteOffset).GetRawData(),
1737         JSTaggedValue(newLength).GetRawData()
1738     };
1739     JSHandle<JSObject> newArr = TypedArrayHelper::TypedArraySpeciesCreate(thread, thisObj, argsLength, args);
1740     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1741     return newArr.GetTaggedValue();
1742 }
1743 
1744 // 22.2.3.27
ToLocaleString(EcmaRuntimeCallInfo * argv)1745 JSTaggedValue BuiltinsTypedArray::ToLocaleString(EcmaRuntimeCallInfo *argv)
1746 {
1747     ASSERT(argv);
1748     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, ToLocaleString);
1749     if (!GetThis(argv)->IsTypedArray()) {
1750         THROW_TYPE_ERROR_AND_RETURN(argv->GetThread(), "This is not a TypedArray.", JSTaggedValue::Exception());
1751     }
1752     return BuiltinsArray::ToLocaleString(argv);
1753 }
1754 
1755 // 22.2.3.28
ToString(EcmaRuntimeCallInfo * argv)1756 JSTaggedValue BuiltinsTypedArray::ToString(EcmaRuntimeCallInfo *argv)
1757 {
1758     ASSERT(argv);
1759     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, ToString);
1760     if (!GetThis(argv)->IsTypedArray()) {
1761         THROW_TYPE_ERROR_AND_RETURN(argv->GetThread(), "This is not a TypedArray.", JSTaggedValue::Exception());
1762     }
1763     return BuiltinsArray::ToString(argv);
1764 }
1765 
1766 // 22.2.3.29
Values(EcmaRuntimeCallInfo * argv)1767 JSTaggedValue BuiltinsTypedArray::Values(EcmaRuntimeCallInfo *argv)
1768 {
1769     ASSERT(argv);
1770     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, Values);
1771     JSThread *thread = argv->GetThread();
1772     [[maybe_unused]] EcmaHandleScope handleScope(thread);
1773     // 1. Let O be the this value.
1774     JSHandle<JSTaggedValue> thisHandle = GetThis(argv);
1775     // 2. Let valid be ValidateTypedArray(O).
1776     TypedArrayHelper::ValidateTypedArray(thread, thisHandle);
1777     // 3. ReturnIfAbrupt(valid).
1778     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(argv->GetThread());
1779     JSHandle<JSObject> self(thisHandle);
1780     ObjectFactory *factory = thread->GetEcmaVM()->GetFactory();
1781     // 4. Return CreateArrayIterator(O, "value").
1782     JSHandle<JSArrayIterator> iter(factory->NewJSArrayIterator(self, IterationKind::VALUE));
1783     return iter.GetTaggedValue();
1784 }
1785 
1786 // 22.2.3.31
ToStringTag(EcmaRuntimeCallInfo * argv)1787 JSTaggedValue BuiltinsTypedArray::ToStringTag(EcmaRuntimeCallInfo *argv)
1788 {
1789     ASSERT(argv);
1790     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, ToStringTag);
1791     JSThread *thread = argv->GetThread();
1792     [[maybe_unused]] EcmaHandleScope handleScope(thread);
1793     // 1. Let O be the this value.
1794     JSHandle<JSTaggedValue> thisHandle = GetThis(argv);
1795     // 2. If Type(O) is not Object, return undefined.
1796     if (!thisHandle->IsECMAObject()) {
1797         return JSTaggedValue::Undefined();
1798     }
1799     // 3. If O does not have a [[TypedArrayName]] internal slot, return undefined.
1800     if (!thisHandle->IsTypedArray()) {
1801         return JSTaggedValue::Undefined();
1802     }
1803     // 4. Let name be the value of O’s [[TypedArrayName]] internal slot.
1804     JSTaggedValue name = JSHandle<JSTypedArray>::Cast(thisHandle)->GetTypedArrayName(thread);
1805     // 5. Assert: name is a String value.
1806     ASSERT(name.IsString());
1807     // 6. Return name.
1808     return name;
1809 }
1810 
1811 // 23.2.3.1
At(EcmaRuntimeCallInfo * argv)1812 JSTaggedValue BuiltinsTypedArray::At(EcmaRuntimeCallInfo *argv)
1813 {
1814     ASSERT(argv);
1815     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, At);
1816     JSThread *thread = argv->GetThread();
1817     [[maybe_unused]] EcmaHandleScope handleScope(thread);
1818 
1819     // 1. Let O be ToObject(this value).
1820     JSHandle<JSTaggedValue> thisHandle = GetThis(argv);
1821     // 2. Let valid be ValidateTypedArray(O).
1822     TypedArrayHelper::ValidateTypedArray(thread, thisHandle);
1823     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1824     JSHandle<JSObject> thisObjHandle = JSTaggedValue::ToObject(thread, thisHandle);
1825     // ReturnIfAbrupt(O).
1826     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1827 
1828     // 3. Let len be O.[[ArrayLength]].
1829     uint32_t len = JSHandle<JSTypedArray>::Cast(thisObjHandle)->GetArrayLength();
1830     // ReturnIfAbrupt(len).
1831     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1832 
1833     // 4. Let relativeIndex be ? ToIntegerOrInfinity(index).
1834     JSTaggedNumber indexVal = JSTaggedValue::ToInteger(thread, GetCallArg(argv, 0));
1835     // ReturnIfAbrupt(indexVal).
1836     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1837     int64_t relativeIndex = indexVal.GetNumber();
1838     int64_t k = 0;
1839     // 5. If relativeIndex ≥ 0, then Let k be relativeIndex.
1840     // 6. Else, Let k be len + relativeIndex.
1841     k = relativeIndex >= 0 ? relativeIndex : static_cast<int64_t>(len) + relativeIndex;
1842     // 7. If k < 0 or k ≥ len, return undefined.
1843     if (k < 0 || k >= len) {
1844         return JSTaggedValue::Undefined();
1845     }
1846     // 8. Return ! Get(O, ! ToString(��(k))).
1847     JSHandle<JSTaggedValue> kValue = JSTypedArray::GetProperty(thread, thisHandle, k).GetValue();
1848     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1849     return kValue.GetTaggedValue();
1850 }
1851 
1852 // 23.2.3.33
ToSorted(EcmaRuntimeCallInfo * argv)1853 JSTaggedValue BuiltinsTypedArray::ToSorted(EcmaRuntimeCallInfo* argv)
1854 {
1855     ASSERT(argv);
1856     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, ToSorted);
1857     JSThread* thread = argv->GetThread();
1858     [[maybe_unused]] EcmaHandleScope handleScope(thread);
1859 
1860     // 1. If comparefn is not undefined and IsCallable(comparefn) is false, throw a TypeError exception.
1861     JSHandle<JSTaggedValue> comparefnHandle = GetCallArg(argv, 0);
1862     if (!comparefnHandle->IsUndefined() && !comparefnHandle->IsCallable()) {
1863         THROW_TYPE_ERROR_AND_RETURN(thread, "the comparefn is not callable.", JSTaggedValue::Exception());
1864     }
1865     // 2. Let O be the this value.
1866     JSHandle<JSTaggedValue> thisHandle = GetThis(argv);
1867     // 3. Perform ? ValidateTypedArray(O).
1868     TypedArrayHelper::ValidateTypedArray(thread, thisHandle);
1869     // ReturnIfAbrupt(valid).
1870     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1871 
1872     JSHandle<JSTypedArray> thisObj(thisHandle);
1873     // 4. Let len be O.[[ArrayLength]].
1874     uint32_t len = thisObj->GetArrayLength();
1875 
1876     // 5. Let A be ? TypedArrayCreateSameType(O, « ��(len) »).
1877     JSTaggedType args[1] = { JSTaggedValue(len).GetRawData() };
1878     JSHandle<JSObject> newArrObj = TypedArrayHelper::TypedArrayCreateSameType(thread, thisObj, 1, args); // 1: one arg.
1879     // ReturnIfAbrupt(A).
1880     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1881 
1882     JSHandle<JSTaggedValue> buffer =
1883         JSHandle<JSTaggedValue>(thread, TypedArrayHelper::ValidateTypedArray(thread, thisHandle));
1884     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1885 
1886     JSMutableHandle<JSTaggedValue> presentValue(thread, JSTaggedValue::Undefined());
1887     JSMutableHandle<JSTaggedValue> middleValue(thread, JSTaggedValue::Undefined());
1888     JSMutableHandle<JSTaggedValue> previousValue(thread, JSTaggedValue::Undefined());
1889     JSMutableHandle<JSTaggedValue> key(thread, JSTaggedValue::Undefined());
1890     JSMutableHandle<JSTaggedValue> key1(thread, JSTaggedValue::Undefined());
1891     JSMutableHandle<JSTaggedValue> key2(thread, JSTaggedValue::Undefined());
1892     if (len > 0) {
1893         previousValue.Update(
1894             ObjectFastOperator::FastGetPropertyByValue(thread, thisHandle.GetTaggedValue(), JSTaggedValue(0)));
1895         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1896         ObjectFastOperator::FastSetPropertyByIndex(
1897             thread, newArrObj.GetTaggedValue(), 0, previousValue.GetTaggedValue());
1898     }
1899     for (uint32_t i = 1; i < len; i++) {
1900         uint32_t beginIndex = 0;
1901         uint32_t endIndex = i;
1902         key.Update(JSTaggedValue(i));
1903         presentValue.Update(
1904             ObjectFastOperator::FastGetPropertyByValue(thread, thisHandle.GetTaggedValue(), key.GetTaggedValue()));
1905         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1906         while (beginIndex < endIndex) {
1907             uint32_t middleIndex = beginIndex + (endIndex - beginIndex) / 2; // 2 : half
1908             key1.Update(JSTaggedValue(middleIndex));
1909             middleValue.Update(
1910                 ObjectFastOperator::FastGetPropertyByValue(thread, newArrObj.GetTaggedValue(), key1.GetTaggedValue()));
1911             RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1912             int32_t compareResult =
1913                 TypedArrayHelper::SortCompare(thread, comparefnHandle, buffer, middleValue, presentValue);
1914             RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1915             compareResult > 0 ? (endIndex = middleIndex) : (beginIndex = middleIndex + 1);
1916         }
1917 
1918         if (endIndex < i) {
1919             for (uint32_t j = i; j > endIndex; j--) {
1920                 key2.Update(JSTaggedValue(j - 1));
1921                 previousValue.Update(ObjectFastOperator::FastGetPropertyByValue(
1922                     thread, newArrObj.GetTaggedValue(), key2.GetTaggedValue()));
1923                 RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1924                 ObjectFastOperator::FastSetPropertyByIndex(
1925                     thread, newArrObj.GetTaggedValue(), j, previousValue.GetTaggedValue());
1926                 RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1927             }
1928         }
1929         ObjectFastOperator::FastSetPropertyByIndex(
1930             thread, newArrObj.GetTaggedValue(), endIndex, presentValue.GetTaggedValue());
1931         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1932     }
1933     return newArrObj.GetTaggedValue();
1934 }
1935 
1936 // 23.2.3.36
With(EcmaRuntimeCallInfo * argv)1937 JSTaggedValue BuiltinsTypedArray::With(EcmaRuntimeCallInfo* argv)
1938 {
1939     ASSERT(argv);
1940     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, With);
1941     JSThread* thread = argv->GetThread();
1942     [[maybe_unused]] EcmaHandleScope handleScope(thread);
1943 
1944     // 1. Let O be the this value.
1945     JSHandle<JSTaggedValue> thisHandle = GetThis(argv);
1946     // 2. Perform ? ValidateTypedArray(O).
1947     TypedArrayHelper::ValidateTypedArray(thread, thisHandle);
1948     // ReturnIfAbrupt(valid).
1949     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1950 
1951     JSHandle<JSTypedArray> thisObj(thisHandle);
1952     // 3. Let len be O.[[ArrayLength]].
1953     uint32_t len = thisObj->GetArrayLength();
1954 
1955     // 4. Let relativeIndex be ? ToIntegerOrInfinity(index).
1956     JSTaggedNumber indexVal = JSTaggedValue::ToInteger(thread, GetCallArg(argv, 0));
1957     // ReturnIfAbrupt(indexVal).
1958     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1959     int64_t relativeIndex = indexVal.GetNumber();
1960     // 5. If relativeIndex ≥ 0, let actualIndex be relativeIndex.
1961     // 6. Else, let actualIndex be len + relativeIndex.
1962     int64_t actualIndex = relativeIndex >= 0 ? relativeIndex : static_cast<int64_t>(len) + relativeIndex;
1963 
1964     // 7. If O.[[ContentType]] is BigInt, let numericValue be ? ToBigInt(value).
1965     // 8. Else, let numericValue be ? ToNumber(value).
1966     JSHandle<JSTaggedValue> value = GetCallArg(argv, 1);
1967     ContentType contentType = thisObj->GetContentType();
1968     JSHandle<JSTaggedValue> numericValue;
1969     if (contentType == ContentType::BigInt) {
1970         numericValue = JSHandle<JSTaggedValue>(thread, JSTaggedValue::ToBigInt(thread, value));
1971     } else {
1972         numericValue = JSHandle<JSTaggedValue>(thread, JSTaggedValue::ToNumber(thread, value));
1973     }
1974     // ReturnIfAbrupt(numericValue).
1975     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1976 
1977     // 9. If IsValidIntegerIndex(O, ��(actualIndex)) is false, throw a RangeError exception.
1978     if (!JSTypedArray::IsValidIntegerIndex(thread, thisHandle, JSTaggedValue(actualIndex))) {
1979         THROW_RANGE_ERROR_AND_RETURN(thread, "Invalid typed array index", JSTaggedValue::Exception());
1980     }
1981 
1982     // 10. Let A be ? TypedArrayCreateSameType(O, « ��(len) »).
1983     JSTaggedType args[1] = { JSTaggedValue(len).GetRawData() };
1984     JSHandle<JSObject> newArrObj = TypedArrayHelper::TypedArrayCreateSameType(thread, thisObj, 1, args); // 1: one arg.
1985     // ReturnIfAbrupt(A).
1986     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
1987 
1988     // 11. Let k be 0.
1989     // 12. Repeat, while k < len,
1990     //     a. Let Pk be ! ToString(��(k)).
1991     //     b. If k is actualIndex, let fromValue be numericValue.
1992     //     c. Else, let fromValue be ! Get(O, Pk).
1993     //     d. Perform ! Set(A, Pk, fromValue, true).
1994     //     e. Set k to k + 1.
1995     JSMutableHandle<JSTaggedValue> tKey(thread, JSTaggedValue::Undefined());
1996     JSMutableHandle<JSTaggedValue> fromValue(thread, JSTaggedValue::Undefined());
1997     uint32_t k = 0;
1998     while (k < len) {
1999         tKey.Update(JSTaggedValue(k));
2000         if (k == actualIndex) {
2001             fromValue.Update(numericValue);
2002         } else {
2003             fromValue.Update(
2004                 ObjectFastOperator::FastGetPropertyByValue(thread, thisHandle.GetTaggedValue(), tKey.GetTaggedValue()));
2005             RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
2006         }
2007         ObjectFastOperator::FastSetPropertyByValue(thread, newArrObj.GetTaggedValue(),
2008             tKey.GetTaggedValue(), fromValue.GetTaggedValue());
2009         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
2010         k++;
2011     }
2012     return newArrObj.GetTaggedValue();
2013 }
2014 
2015 // es12 23.2.3.13
Includes(EcmaRuntimeCallInfo * argv)2016 JSTaggedValue BuiltinsTypedArray::Includes(EcmaRuntimeCallInfo *argv)
2017 {
2018     ASSERT(argv);
2019     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, Includes);
2020     if (!GetThis(argv)->IsTypedArray()) {
2021         THROW_TYPE_ERROR_AND_RETURN(argv->GetThread(), "This is not a TypedArray.", JSTaggedValue::Exception());
2022     }
2023     return BuiltinsArray::Includes(argv);
2024 }
2025 
2026 // 23.2.3.32
ToReversed(EcmaRuntimeCallInfo * argv)2027 JSTaggedValue BuiltinsTypedArray::ToReversed(EcmaRuntimeCallInfo *argv)
2028 {
2029     ASSERT(argv);
2030     JSThread *thread = argv->GetThread();
2031     BUILTINS_API_TRACE(thread, TypedArray, ToReversed);
2032     [[maybe_unused]] EcmaHandleScope handleScope(thread);
2033 
2034     // 1. Let O be ToObject(this value).
2035     JSHandle<JSTaggedValue> thisHandle = GetThis(argv);
2036     JSHandle<JSTypedArray> thisObj(thisHandle);
2037     // 2. Perform ? ValidateTypedArray(O).
2038     TypedArrayHelper::ValidateTypedArray(thread, thisHandle);
2039     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
2040     JSHandle<JSObject> thisObjHandle = JSTaggedValue::ToObject(thread, thisHandle);
2041     // ReturnIfAbrupt(O).
2042     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
2043     // 3. Let len be O.[[ArrayLength]].
2044     uint32_t len = JSHandle<JSTypedArray>::Cast(thisObjHandle)->GetArrayLength();
2045     // ReturnIfAbrupt(len).
2046     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
2047     // 4. Let A be ? TypedArrayCreateSameType(O, « ��(length) »).
2048     JSTaggedType args[1] = {JSTaggedValue(len).GetRawData()};
2049     JSHandle<JSObject> newArrayHandle = TypedArrayHelper::TypedArrayCreateSameType(thread, thisObj, 1, args);
2050     // ReturnIfAbrupt(newObj).
2051     RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
2052     // 5. Let k be 0.
2053     uint32_t k = 0;
2054 
2055     // 6. Repeat, while k < length,
2056     //     a. Let from be ! ToString(��(length - k - 1)).
2057     //     b. Let Pk be ! ToString(��(k)).
2058     //     c. Let fromValue be ! Get(O, from).
2059     //     d. Perform ! Set(A, Pk, fromValue, true).
2060     //     e. Set k to k + 1.
2061     while (k < len) {
2062         uint32_t from = len - k - 1;
2063         JSHandle<JSTaggedValue> fromValue = JSTypedArray::GetProperty(thread, thisHandle, from).GetValue();
2064         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
2065         ObjectFastOperator::FastSetPropertyByIndex(thread, newArrayHandle.GetTaggedValue(), k,
2066                                                    fromValue.GetTaggedValue());
2067         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
2068         ++k;
2069     }
2070     // 7. Return A.
2071     return newArrayHandle.GetTaggedValue();
2072 }
2073 
2074 // 23.2.3.13
FindLast(EcmaRuntimeCallInfo * argv)2075 JSTaggedValue BuiltinsTypedArray::FindLast(EcmaRuntimeCallInfo *argv)
2076 {
2077     ASSERT(argv);
2078     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, FindLast);
2079     if (!GetThis(argv)->IsTypedArray()) {
2080         THROW_TYPE_ERROR_AND_RETURN(argv->GetThread(), "This is not a TypedArray.", JSTaggedValue::Exception());
2081     }
2082     return BuiltinsArray::FindLast(argv);
2083 }
2084 
2085 // 23.2.3.14
FindLastIndex(EcmaRuntimeCallInfo * argv)2086 JSTaggedValue BuiltinsTypedArray::FindLastIndex(EcmaRuntimeCallInfo *argv)
2087 {
2088     ASSERT(argv);
2089     BUILTINS_API_TRACE(argv->GetThread(), TypedArray, FindLastIndex);
2090     if (!GetThis(argv)->IsTypedArray()) {
2091         THROW_TYPE_ERROR_AND_RETURN(argv->GetThread(), "This is not a TypedArray.", JSTaggedValue::Exception());
2092     }
2093     return BuiltinsArray::FindLastIndex(argv);
2094 }
2095 }  // namespace panda::ecmascript::builtins
2096