blob: ab5e2c9235f9cec5da5520d1d79506eaa374bd27 [file] [log] [blame]
Danil Chapovalov3b548dd2019-03-01 14:58:44 +01001/*
2 * Copyright 2019 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#ifndef RTC_BASE_TASK_UTILS_TO_QUEUED_TASK_H_
12#define RTC_BASE_TASK_UTILS_TO_QUEUED_TASK_H_
13
14#include <memory>
15#include <type_traits>
16#include <utility>
17
Danil Chapovalov3b548dd2019-03-01 14:58:44 +010018#include "api/task_queue/queued_task.h"
19
20namespace webrtc {
21namespace webrtc_new_closure_impl {
22// Simple implementation of QueuedTask for use with rtc::Bind and lambdas.
23template <typename Closure>
24class ClosureTask : public QueuedTask {
25 public:
26 explicit ClosureTask(Closure&& closure)
27 : closure_(std::forward<Closure>(closure)) {}
28
29 private:
30 bool Run() override {
31 closure_();
32 return true;
33 }
34
35 typename std::decay<Closure>::type closure_;
36};
37
38// Extends ClosureTask to also allow specifying cleanup code.
39// This is useful when using lambdas if guaranteeing cleanup, even if a task
40// was dropped (queue is too full), is required.
41template <typename Closure, typename Cleanup>
42class ClosureTaskWithCleanup : public ClosureTask<Closure> {
43 public:
44 ClosureTaskWithCleanup(Closure&& closure, Cleanup&& cleanup)
45 : ClosureTask<Closure>(std::forward<Closure>(closure)),
46 cleanup_(std::forward<Cleanup>(cleanup)) {}
47 ~ClosureTaskWithCleanup() override { cleanup_(); }
48
49 private:
50 typename std::decay<Cleanup>::type cleanup_;
51};
52} // namespace webrtc_new_closure_impl
53
54// Convenience function to construct closures that can be passed directly
55// to methods that support std::unique_ptr<QueuedTask> but not template
56// based parameters.
57template <typename Closure>
58std::unique_ptr<QueuedTask> ToQueuedTask(Closure&& closure) {
Mirko Bonadei317a1f02019-09-17 17:06:18 +020059 return std::make_unique<webrtc_new_closure_impl::ClosureTask<Closure>>(
Danil Chapovalov3b548dd2019-03-01 14:58:44 +010060 std::forward<Closure>(closure));
61}
62
63template <typename Closure, typename Cleanup>
64std::unique_ptr<QueuedTask> ToQueuedTask(Closure&& closure, Cleanup&& cleanup) {
Mirko Bonadei317a1f02019-09-17 17:06:18 +020065 return std::make_unique<
Danil Chapovalov3b548dd2019-03-01 14:58:44 +010066 webrtc_new_closure_impl::ClosureTaskWithCleanup<Closure, Cleanup>>(
67 std::forward<Closure>(closure), std::forward<Cleanup>(cleanup));
68}
69
70} // namespace webrtc
71
72#endif // RTC_BASE_TASK_UTILS_TO_QUEUED_TASK_H_