1 /*
2  * Copyright (c) 2024 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 #ifndef META_API_TASK_QUEUE_H
17 #define META_API_TASK_QUEUE_H
18 
19 #include <base/containers/type_traits.h>
20 
21 #include <meta/api/task.h>
22 #include <meta/interface/detail/any.h>
23 #include <meta/interface/interface_helpers.h>
24 #include <meta/interface/intf_promise.h>
25 #include <meta/interface/intf_task_queue_registry.h>
26 
META_BEGIN_NAMESPACE()27 META_BEGIN_NAMESPACE()
28 
29 template<typename Func>
30 auto CreateFutureFromResultFunction(Func func)
31 {
32     // todo: add support for lighter promise construction
33     auto p = GetObjectRegistry().Create<IPromise>(ClassId::Promise);
34     auto fut = p->GetFuture();
35     p->Set(QueueWaitableTask(BASE_NS::move(func)).Invoke());
36     return Future<PlainType_t<decltype(func())>>(fut);
37 }
38 
39 template<typename Func>
AddFutureTaskOrRunDirectly(const ITaskQueue::Ptr & queue,Func func)40 auto AddFutureTaskOrRunDirectly(const ITaskQueue::Ptr& queue, Func func)
41 {
42     auto q = GetTaskQueueRegistry().GetCurrentTaskQueue();
43     if (q == queue) {
44         return CreateFutureFromResultFunction(BASE_NS::move(func));
45     }
46     return Future<PlainType_t<decltype(func())>>(queue->AddWaitableTask(CreateWaitableTask(func)));
47 }
48 
49 META_END_NAMESPACE()
50 
51 #endif
52