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 #include "n_ref.h"
17 
18 namespace OHOS {
19 namespace FileManagement {
20 namespace LibN {
NRef()21 NRef::NRef() {}
22 
NRef(NVal val)23 NRef::NRef(NVal val)
24 {
25     if (val) {
26         env_ = val.env_;
27         napi_create_reference(val.env_, val.val_, 1, &ref_);
28     }
29 }
30 
~NRef()31 NRef::~NRef()
32 {
33     if (ref_ && env_) {
34         napi_delete_reference(env_, ref_);
35     }
36 }
37 
38 NRef::operator bool() const
39 {
40     return ref_ != nullptr;
41 }
42 
Deref(napi_env env)43 NVal NRef::Deref(napi_env env)
44 {
45     if (!ref_ || !env) {
46         return NVal();
47     }
48 
49     napi_value val = nullptr;
50     napi_get_reference_value(env, ref_, &val);
51     return {env, val};
52 }
53 
DeleteJsEnv()54 void NRef::DeleteJsEnv()
55 {
56     if (ref_ && env_) {
57         napi_delete_reference(env_, ref_);
58     }
59     ref_ = nullptr;
60 }
61 } // namespace LibN
62 } // namespace FileManagement
63 } // namespace OHOS
64