1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
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 |
|
24 | namespace tfnodejs {
|
25 |
|
26 |
|
27 | class 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 | }
|
69 |
|
70 | #endif
|