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_H
17 #define META_API_TASK_H
18 
19 #include <base/containers/type_traits.h>
20 
21 #include <meta/interface/detail/any.h>
22 #include <meta/interface/interface_helpers.h>
23 #include <meta/interface/intf_task_queue.h>
24 
META_BEGIN_NAMESPACE()25 META_BEGIN_NAMESPACE()
26 
27 /**
28  * @brief Implementation of waitable task for task queues (see ITaskQueue::AddWaitableTask)
29  */
30 template<typename Func>
31 class QueueWaitableTask : public IntroduceInterfaces<ITaskQueueWaitableTask> {
32 public:
33     QueueWaitableTask(Func func) : func_(BASE_NS::move(func)) {}
34 
35     IAny::Ptr Invoke() override
36     {
37         using Result = BASE_NS::remove_reference_t<decltype(func_())>;
38         if constexpr (!BASE_NS::is_same_v<Result, void>) {
39             return IAny::Ptr(new Any<Result>(func_()));
40         } else {
41             func_();
42             return nullptr;
43         }
44     }
45 
46 private:
47     Func func_;
48 };
49 
50 /**
51  * @brief Create waitable task from callable entity (e.g. lambda).
52  */
53 template<typename Func>
CreateWaitableTask(Func func)54 ITaskQueueWaitableTask::Ptr CreateWaitableTask(Func func)
55 {
56     return ITaskQueueWaitableTask::Ptr(new QueueWaitableTask(BASE_NS::move(func)));
57 }
58 
59 META_END_NAMESPACE()
60 
61 #endif
62