• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #ifndef HIVIEWDFX_NAPI_NCALSS
17 #define HIVIEWDFX_NAPI_NCALSS
18 
19 #pragma once
20 
21 #include "uni_header.h"
22 
23 #include <map>
24 #include <memory>
25 #include <mutex>
26 #include <string>
27 #include <tuple>
28 #include <vector>
29 
30 namespace OHOS {
31 namespace HiviewDFX {
32 class NClass {
33 public:
34     NClass(const NClass &) = delete;
35     NClass &operator = (const NClass &) = delete;
~NClass()36     ~NClass() {};
37     static NClass &GetInstance();
38 
39     static std::tuple<bool, napi_value> DefineClass(napi_env env,
40                                                     std::string className,
41                                                     napi_callback constructor,
42                                                     std::vector<napi_property_descriptor> &&properties);
43     static bool SaveClass(napi_env env, std::string className, napi_value exClass);
44     static napi_value InstantiateClass(napi_env env, std::string className, std::vector<napi_value> args);
45 
GetEntityOf(napi_env env,napi_value objStat)46     template<class T> static T *GetEntityOf(napi_env env, napi_value objStat)
47     {
48         if (!env || !objStat) {
49             return nullptr;
50         }
51         T *t = nullptr;
52         napi_status status = napi_unwrap(env, objStat, (void **)&t);
53         if (status != napi_ok) {
54             return nullptr;
55         }
56         return t;
57     }
58 
SetEntityFor(napi_env env,napi_value obj,std::unique_ptr<T> entity)59     template<class T> static bool SetEntityFor(napi_env env, napi_value obj, std::unique_ptr<T> entity)
60     {
61         napi_status status = napi_wrap(
62             env,
63             obj,
64             entity.get(),
65             [](napi_env env, void *data, void *hint) {
66                 auto entity = static_cast<T *>(data);
67                 delete entity;
68             },
69             nullptr,
70             nullptr);
71         entity.release();
72         return status == napi_ok;
73     }
74 
75 private:
76     NClass() = default;
77     std::map<std::string, napi_ref> exClassMap;
78     std::mutex exClassMapLock;
79 };
80 } // namespace HiviewDFX
81 } // namespace OHOS
82 
83 #endif // HIVIEWDFX_NAPI_NCALSS