1 /*
2 * Copyright (c) 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/js_api/js_api_vector_iterator.h"
17
18 #include "ecmascript/base/typed_array_helper.h"
19 #include "ecmascript/global_env.h"
20 #include "ecmascript/js_api/js_api_vector.h"
21
22 namespace panda::ecmascript {
23 using BuiltinsBase = base::BuiltinsBase;
24 // VectorIteratorPrototype%.next ( )
Next(EcmaRuntimeCallInfo * argv)25 JSTaggedValue JSAPIVectorIterator::Next(EcmaRuntimeCallInfo *argv)
26 {
27 ASSERT(argv);
28 JSThread *thread = argv->GetThread();
29 [[maybe_unused]] EcmaHandleScope handleScope(thread);
30 JSHandle<JSTaggedValue> input(BuiltinsBase::GetThis(argv));
31
32 if (!input->IsJSAPIVectorIterator()) {
33 THROW_TYPE_ERROR_AND_RETURN(thread, "this value is not an vector iterator", JSTaggedValue::Exception());
34 }
35 JSHandle<JSAPIVectorIterator> iter(input);
36 // Let a be O.[[IteratedVectorLike]].
37 JSHandle<JSTaggedValue> vector(thread, iter->GetIteratedVector(thread));
38 // If a is undefined, return an undefinedIteratorResult.
39 if (vector->IsUndefined()) {
40 JSHandle<GlobalEnv> env = thread->GetEcmaVM()->GetGlobalEnv();
41 return env->GetUndefinedIteratorResult().GetTaggedValue();
42 }
43 // Let index be O.[[VectorLikeNextIndex]].
44 uint32_t index = iter->GetNextIndex();
45 // If a has a [[TypedVectorName]] internal slot, then
46 // Let len be the value of O’s [[VectorLength]] internal slot.
47 ASSERT(vector->IsJSAPIVector());
48 const uint32_t length = static_cast<uint32_t>(JSHandle<JSAPIVector>::Cast(vector)->GetSize());
49 // If index >= len, then
50 if (index >= length) {
51 // Set O.[[IteratedVectorLike]] to undefined.
52 // Return undefinedIteratorResult.
53 JSHandle<JSTaggedValue> undefinedHandle = thread->GlobalConstants()->GetHandledUndefined();
54 iter->SetIteratedVector(thread, undefinedHandle);
55 JSHandle<GlobalEnv> env = thread->GetEcmaVM()->GetGlobalEnv();
56 return env->GetUndefinedIteratorResult().GetTaggedValue();
57 }
58 // Set O.[[VectorLikeNextIndex]] to index + 1.
59 iter->SetNextIndex(index + 1);
60 JSHandle<JSTaggedValue> value(thread, JSAPIVector::Get(thread, JSHandle<JSAPIVector>::Cast(vector),
61 static_cast<int32_t>(index)));
62 return JSIterator::CreateIterResultObject(thread, value, false).GetTaggedValue();
63 }
64 } // namespace panda::ecmascript
65