• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "quickjs_headers.h"
17 
18 #include "native_value/quickjs_native_value.h"
19 #include "quickjs_native_reference.h"
20 
QuickJSNativeReference(QuickJSNativeEngine * engine,NativeValue * value,uint32_t initialRefcount,NativeFinalize callback,void * data,void * hint)21 QuickJSNativeReference::QuickJSNativeReference(
22     QuickJSNativeEngine* engine, NativeValue* value, uint32_t initialRefcount,
23     NativeFinalize callback, void* data, void* hint)
24     : engine_(engine), value_(*value), refCount_(initialRefcount), callback_(callback), data_(data),
25     hint_(hint)
26 {
27     for (uint32_t i = 0; i < initialRefcount; i++) {
28         JS_DupValue(engine_->GetContext(), value_);
29     }
30 }
31 
~QuickJSNativeReference()32 QuickJSNativeReference::~QuickJSNativeReference()
33 {
34     while (refCount_) {
35         refCount_--;
36         if (refCount_ == 0) {
37             FinalizeCallback();
38         }
39         JS_FreeValue(engine_->GetContext(), value_);
40     }
41 }
42 
Ref()43 uint32_t QuickJSNativeReference::Ref()
44 {
45     if (refCount_ >= 0) {
46         ++refCount_;
47         JS_DupValue(engine_->GetContext(), value_);
48     }
49     return refCount_;
50 }
51 
Unref()52 uint32_t QuickJSNativeReference::Unref()
53 {
54     if (refCount_ > 0) {
55         --refCount_;
56         if (refCount_ == 0) {
57             FinalizeCallback();
58         }
59         JS_FreeValue(engine_->GetContext(), value_);
60     }
61     return refCount_;
62 }
63 
Get()64 NativeValue* QuickJSNativeReference::Get()
65 {
66     return QuickJSNativeEngine::JSValueToNativeValue(engine_, JS_DupValue(engine_->GetContext(), value_));
67 }
68 
operator NativeValue*()69 QuickJSNativeReference::operator NativeValue*()
70 {
71     return Get();
72 }
73 
FinalizeCallback(void)74 void QuickJSNativeReference::FinalizeCallback(void)
75 {
76     if (callback_ != nullptr) {
77         callback_(engine_, data_, hint_);
78         JS_FreeFinalizer(value_);
79     }
80     callback_ = nullptr;
81     data_ = nullptr;
82     hint_ = nullptr;
83 }
84