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