• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023 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 #ifndef DISTRIBUTEDDATAMGR_APPDATAMGR_UV_QUEUE_H
16 #define DISTRIBUTEDDATAMGR_APPDATAMGR_UV_QUEUE_H
17 #include <functional>
18 #include "napi/native_api.h"
19 #include "napi/native_common.h"
20 #include "napi/native_node_api.h"
21 #include "uv.h"
22 
23 namespace OHOS::AppDataMgrJsKit {
24 class UvQueue final {
25 public:
26     using ArgsGenerator = std::function<void(napi_env env, int& argc, napi_value* argv)>;
27     using CallbackGetter = std::function<napi_value(napi_env env)>;
28     struct UvCallback {
29         napi_ref callback_ = nullptr;
30         bool repeat_ = false;
31         CallbackGetter getter_;
callback_UvCallback32         UvCallback(napi_ref callback, bool repeat = false) : callback_(callback), repeat_(repeat) {}
UvCallbackUvCallback33         UvCallback(CallbackGetter getter) : getter_(std::move(getter)) {}
IsNullUvCallback34         bool IsNull()
35         {
36             return (callback_ == nullptr && getter_ == nullptr);
37         }
38     };
39 
40     explicit UvQueue(napi_env env);
41     ~UvQueue();
42 
43     napi_env GetEnv();
44     void AsyncCall(UvCallback callback, ArgsGenerator genArgs = ArgsGenerator());
45 private:
46     struct UvEntry {
47         napi_env env;
48         napi_ref callback;
49         bool repeat = false;
50         CallbackGetter getter;
51         ArgsGenerator args;
~UvEntryUvEntry52         ~UvEntry()
53         {
54             if (callback != nullptr && !repeat) {
55                 napi_delete_reference(env, callback);
56             }
57         }
58     };
59     napi_env env_ = nullptr;
60     uv_loop_s* loop_ = nullptr;
61 };
62 } // namespace OHOS::AppDataMgrJsKit
63 #endif // DISTRIBUTEDDATAMGR_APPDATAMGR_UV_QUEUE_H
64