1 /*
2 * Copyright (c) 2021 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/ic/proto_change_details.h"
17 #include "ecmascript/weak_vector-inl.h"
18
19 namespace panda::ecmascript {
Add(const JSThread * thread,const JSHandle<ChangeListener> & array,const JSHandle<JSHClass> & value,uint32_t * index)20 JSHandle<ChangeListener> ChangeListener::Add(const JSThread *thread, const JSHandle<ChangeListener> &array,
21 const JSHandle<JSHClass> &value, uint32_t *index)
22 {
23 JSTaggedValue weakValue;
24 if (!array->Full()) {
25 weakValue = JSTaggedValue(value.GetTaggedValue().CreateAndGetWeakRef());
26 uint32_t arrayIndex = array->PushBack(thread, weakValue);
27 if (arrayIndex != TaggedArray::MAX_ARRAY_INDEX) {
28 if (index != nullptr) {
29 *index = arrayIndex;
30 }
31 return array;
32 }
33 UNREACHABLE();
34 }
35 // if exist hole, use it.
36 uint32_t holeIndex = CheckHole(array);
37 if (holeIndex != TaggedArray::MAX_ARRAY_INDEX) {
38 weakValue = JSTaggedValue(value.GetTaggedValue().CreateAndGetWeakRef());
39 array->Set(thread, holeIndex, weakValue);
40 if (index != nullptr) {
41 *index = holeIndex;
42 }
43 return array;
44 }
45 // the vector is full and no hole exists.
46 JSHandle<WeakVector> newArray = WeakVector::Grow(thread, JSHandle<WeakVector>(array), array->GetCapacity() + 1);
47 weakValue = JSTaggedValue(value.GetTaggedValue().CreateAndGetWeakRef());
48 uint32_t arrayIndex = newArray->PushBack(thread, weakValue);
49 ASSERT(arrayIndex != TaggedArray::MAX_ARRAY_INDEX);
50 if (index != nullptr) {
51 *index = arrayIndex;
52 }
53 return JSHandle<ChangeListener>(newArray);
54 }
55
CheckHole(const JSHandle<ChangeListener> & array)56 uint32_t ChangeListener::CheckHole(const JSHandle<ChangeListener> &array)
57 {
58 for (uint32_t i = 0; i < array->GetEnd(); i++) {
59 JSTaggedValue value = array->Get(i);
60 if (value == JSTaggedValue::Hole() || value == JSTaggedValue::Undefined()) {
61 return i;
62 }
63 }
64 return TaggedArray::MAX_ARRAY_INDEX;
65 }
66
Get(uint32_t index)67 JSTaggedValue ChangeListener::Get(uint32_t index)
68 {
69 JSTaggedValue value = WeakVector::Get(index);
70 if (!value.IsHeapObject()) {
71 return value;
72 }
73 return JSTaggedValue(value.GetTaggedWeakRef());
74 }
75 } // namespace panda::ecmascript