UNPKG

1.78 kBtext/x-cView Raw
1/**
2 * @license
3 * Copyright 2019 Google LLC. All Rights Reserved.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 * =============================================================================
16 */
17
18#ifndef TF_NODEJS_NAPI_AUTO_REF_H_
19#define TF_NODEJS_NAPI_AUTO_REF_H_
20
21#include <node_api.h>
22#include "utils.h"
23
24namespace tfnodejs {
25
26// Helper class to automatically cleanup napi_ref instances.
27class NapiAutoRef {
28 public:
29 NapiAutoRef() : env_(nullptr), ref_(nullptr) {}
30
31 napi_status Init(napi_env env, napi_value value) {
32 env_ = env;
33 return napi_create_reference(env_, value, 1, &ref_);
34 }
35
36 napi_status Cleanup() {
37 if (!env_ || !ref_) {
38#if DEBUG
39 NAPI_THROW_ERROR(env_, "Uninitialized reference attempted to cleanup");
40#endif
41 return napi_invalid_arg;
42 }
43
44 napi_status nstatus = napi_delete_reference(env_, ref_);
45 env_ = nullptr;
46 ref_ = nullptr;
47 return nstatus;
48 }
49
50 virtual ~NapiAutoRef() {
51 if (env_) {
52#if DEBUG
53 NAPI_THROW_ERROR(env_, "Non-cleaned up napi_env instance");
54#endif
55 }
56 if (ref_) {
57#if DEBUG
58 NAPI_THROW_ERROR(env_, "Non-cleaned up napi_ref instance");
59#endif
60 }
61 }
62
63 private:
64 napi_env env_;
65 napi_ref ref_;
66};
67
68} // namespace tfnodejs
69
70#endif // TF_NODEJS_NAPI_AUTO_REF_H_