1/*
2 * Copyright (c) 2024 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#ifndef ECMASCRIPT_SUSTAINING_JS_HANDLE_H
17#define ECMASCRIPT_SUSTAINING_JS_HANDLE_H
18
19#include "ecmascript/common.h"
20#include "ecmascript/platform/mutex.h"
21#include "ecmascript/ecma_vm.h"
22
23namespace panda::ecmascript {
24
25class SustainingJSHandle {
26public:
27    SustainingJSHandle(EcmaVM *vm);
28    ~SustainingJSHandle();
29    template <typename T>
30    JSHandle<T> NewHandle(JSHandle<T> value)
31    {
32        return JSHandle<T>(GetJsHandleSlot(value.GetTaggedType()));
33    }
34
35    template <typename T>
36    JSHandle<T> NewHandle(JSTaggedType value)
37    {
38        return JSHandle<T>(GetJsHandleSlot(value));
39    }
40
41    void Iterate(const RootRangeVisitor &rv);
42
43private:
44    uintptr_t GetJsHandleSlot(JSTaggedType value);
45    uintptr_t Expand();
46
47    EcmaVM *vm_ { nullptr };
48
49    JSTaggedType *blockNext_ { nullptr };
50    JSTaggedType *blockLimit_ { nullptr };
51    SustainingJSHandle *pre_ { nullptr };
52    SustainingJSHandle *next_ { nullptr };
53    EcmaContext *context_ { nullptr };
54
55    static constexpr uint32_t BLOCK_SIZE = 256L;
56    std::vector<std::array<JSTaggedType, BLOCK_SIZE>*> handleBlocks_;
57    friend class SustainingJSHandleList;
58};
59
60class SustainingJSHandleList {
61public:
62    void AddSustainingJSHandle(SustainingJSHandle *sustainingJSHandle);
63    void RemoveSustainingJSHandle(SustainingJSHandle *sustainingJSHandle);
64    void Iterate(const RootRangeVisitor &rv);
65
66private:
67    SustainingJSHandle *listHead_ { nullptr };
68    Mutex mutex_;
69};
70}  // namespace panda::ecmascript
71#endif  // ECMASCRIPT_SUSTAINING_JS_HANDLE_H
72