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#ifndef JS_CONCURRENT_MODULE_COMMON_HELPER_OBJECT_HELPER_H
17#define JS_CONCURRENT_MODULE_COMMON_HELPER_OBJECT_HELPER_H
18
19namespace Commonlibrary::Concurrent::Common::Helper {
20class DereferenceHelp {
21public:
22    template<typename Inner, typename Outer>
23    static Outer* DereferenceOf(const Inner Outer::*field, const Inner* pointer)
24    {
25        if (field != nullptr && pointer != nullptr) {
26            auto fieldOffset = reinterpret_cast<uintptr_t>(&(static_cast<Outer*>(0)->*field));
27            auto outPointer = reinterpret_cast<Outer*>(reinterpret_cast<uintptr_t>(pointer) - fieldOffset);
28            return outPointer;
29        }
30        return nullptr;
31    }
32};
33
34class CloseHelp {
35public:
36    template<typename T>
37    static void DeletePointer(const T* value, bool isArray)
38    {
39        if (value == nullptr) {
40            return;
41        }
42        if (isArray) {
43            delete[] value;
44        } else {
45            delete value;
46            value = nullptr;
47        }
48    }
49};
50
51template<typename T>
52class ObjectScope {
53public:
54    ObjectScope(const T* data, bool isArray) : data_(data), isArray_(isArray) {}
55    ~ObjectScope()
56    {
57        if (data_ == nullptr) {
58            return;
59        }
60        if (isArray_) {
61            delete[] data_;
62        } else {
63            delete data_;
64            data_ = nullptr;
65        }
66    }
67
68private:
69    const T* data_;
70    bool isArray_;
71};
72
73class HandleScope {
74public:
75    HandleScope(napi_env env, napi_status& status) : env_(env)
76    {
77        status = napi_open_handle_scope(env, &scope_);
78    }
79    ~HandleScope()
80    {
81        if (env_ != nullptr && scope_ != nullptr) {
82            napi_close_handle_scope(env_, scope_);
83        }
84    }
85
86private:
87    napi_handle_scope scope_ = nullptr;
88    napi_env env_ = nullptr;
89};
90} // namespace Commonlibrary::Concurrent::Common::Helper
91#endif // JS_CONCURRENT_MODULE_COMMON_HELPER_OBJECT_HELPER_H
92