blob: 5088af91eeb01001ef2692a61e044353a013c013 [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
18#include "absl/memory/memory.h"
19#include "api/task_queue/queued_task.h"
20
21namespace webrtc {
22namespace webrtc_new_closure_impl {
23// Simple implementation of QueuedTask for use with rtc::Bind and lambdas.
24template <typename Closure>
25class ClosureTask : public QueuedTask {
26 public:
27 explicit ClosureTask(Closure&& closure)
28 : closure_(std::forward<Closure>(closure)) {}
29
30 private:
31 bool Run() override {
32 closure_();
33 return true;
34 }
35
36 typename std::decay<Closure>::type closure_;
37};
38
39// Extends ClosureTask to also allow specifying cleanup code.
40// This is useful when using lambdas if guaranteeing cleanup, even if a task
41// was dropped (queue is too full), is required.
42template <typename Closure, typename Cleanup>
43class ClosureTaskWithCleanup : public ClosureTask<Closure> {
44 public:
45 ClosureTaskWithCleanup(Closure&& closure, Cleanup&& cleanup)
46 : ClosureTask<Closure>(std::forward<Closure>(closure)),
47 cleanup_(std::forward<Cleanup>(cleanup)) {}
48 ~ClosureTaskWithCleanup() override { cleanup_(); }
49
50 private:
51 typename std::decay<Cleanup>::type cleanup_;
52};
53} // namespace webrtc_new_closure_impl
54
55// Convenience function to construct closures that can be passed directly
56// to methods that support std::unique_ptr<QueuedTask> but not template
57// based parameters.
58template <typename Closure>
59std::unique_ptr<QueuedTask> ToQueuedTask(Closure&& closure) {
60 return absl::make_unique<webrtc_new_closure_impl::ClosureTask<Closure>>(
61 std::forward<Closure>(closure));
62}
63
64template <typename Closure, typename Cleanup>
65std::unique_ptr<QueuedTask> ToQueuedTask(Closure&& closure, Cleanup&& cleanup) {
66 return absl::make_unique<
67 webrtc_new_closure_impl::ClosureTaskWithCleanup<Closure, Cleanup>>(
68 std::forward<Closure>(closure), std::forward<Cleanup>(cleanup));
69}
70
71} // namespace webrtc
72
73#endif // RTC_BASE_TASK_UTILS_TO_QUEUED_TASK_H_