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