• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2025 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 AUTO_NAPI_REF_H
17 #define AUTO_NAPI_REF_H
18 
19 #include "napi/native_api.h"
20 #include "napi/native_common.h"
21 #include "napi/native_node_api.h"
22 
23 struct AutoNapiRef {
AutoNapiRefAutoNapiRef24     AutoNapiRef() {}
AutoNapiRefAutoNapiRef25     AutoNapiRef(napi_env env, napi_value value)
26     {
27         CreateReference(env, value);
28     }
29     AutoNapiRef(const AutoNapiRef&) = delete;
30     AutoNapiRef& operator=(const AutoNapiRef&) = delete;
31 
CreateReferenceAutoNapiRef32     void CreateReference(napi_env env, napi_value value) {
33         Reset();
34         env_ = env;
35         if (env) {
36             napi_create_reference(env, value, 1, &ref_);
37         }
38     }
39 
~AutoNapiRefAutoNapiRef40     ~AutoNapiRef()
41     {
42         if (env_ && ref_) {
43             napi_delete_reference(env_, ref_);
44         }
45     }
46 
GetRefValueAutoNapiRef47     napi_value GetRefValue()
48     {
49         napi_value value = nullptr;
50         if (env_ && ref_) {
51             napi_get_reference_value(env_, ref_, &value);
52         }
53         return value;
54     }
55 
ResetAutoNapiRef56     void Reset()
57     {
58         if (env_ && ref_) {
59             napi_delete_reference(env_, ref_);
60         }
61         ref_ = nullptr;
62         env_ = nullptr;
63     }
64 
65     napi_ref ref_ = nullptr;
66     napi_env env_ = nullptr;
67 };
68 
69 #endif // AUTO_NAPI_REF_H
70