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 FOUNDATION_ACE_NAPI_NATIVE_ENGINE_ARK_FINALIZERS_PACK_H
17#define FOUNDATION_ACE_NAPI_NATIVE_ENGINE_ARK_FINALIZERS_PACK_H
18
19#include "interfaces/inner_api/napi/native_node_api.h"
20
21class NativeEngine;
22
23using RefFinalizer = std::pair<NapiNativeFinalize, std::tuple<NativeEngine*, void*, void*>>;
24using ArkFinalizersPackFinishNotify = std::function<void(size_t totalNativeBindingSize)>;
25
26class ArkFinalizersPack {
27public:
28    ArkFinalizersPack() = default;
29    ~ArkFinalizersPack() = default;
30    DEFAULT_MOVE_SEMANTIC(ArkFinalizersPack);
31    DEFAULT_COPY_SEMANTIC(ArkFinalizersPack);
32
33    void Clear()
34    {
35        finalizers_.clear();
36        totalNativeBindingSize_ = 0;
37        notify_ = nullptr;
38    }
39    bool Empty() const
40    {
41        return finalizers_.empty();
42    }
43    void RegisterFinishNotify(ArkFinalizersPackFinishNotify notify)
44    {
45        notify_ = notify;
46    }
47    size_t GetNumFinalizers() const
48    {
49        return finalizers_.size();
50    }
51    void ProcessAll() const
52    {
53        for (auto &iter : finalizers_) {
54            NapiNativeFinalize callback = iter.first;
55            auto &[p0, p1, p2] = iter.second;
56            callback(reinterpret_cast<napi_env>(p0), p1, p2);
57        }
58        NotifyFinish();
59    }
60    size_t GetTotalNativeBindingSize() const
61    {
62        return totalNativeBindingSize_;
63    }
64    void AddFinalizer(RefFinalizer &finalizer, size_t nativeBindingSize)
65    {
66        finalizers_.emplace_back(finalizer);
67        totalNativeBindingSize_ += nativeBindingSize;
68    }
69private:
70    void NotifyFinish() const
71    {
72        if (notify_ != nullptr) {
73            notify_(totalNativeBindingSize_);
74        }
75    }
76    std::vector<RefFinalizer> finalizers_ {};
77    size_t totalNativeBindingSize_ {0};
78    ArkFinalizersPackFinishNotify notify_ {nullptr};
79};
80
81#endif /* FOUNDATION_ACE_NAPI_NATIVE_ENGINE_ARK_FINALIZERS_PACK_H */
82