/* * Copyright 2019 The WebRTC Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #ifndef RTC_BASE_TASK_UTILS_TO_QUEUED_TASK_H_ #define RTC_BASE_TASK_UTILS_TO_QUEUED_TASK_H_ #include #include #include #include "api/task_queue/queued_task.h" #include "rtc_base/task_utils/pending_task_safety_flag.h" namespace webrtc { namespace webrtc_new_closure_impl { // Simple implementation of QueuedTask for use with rtc::Bind and lambdas. template class ClosureTask : public QueuedTask { public: explicit ClosureTask(Closure&& closure) : closure_(std::forward(closure)) {} private: bool Run() override { closure_(); return true; } typename std::decay::type closure_; }; template class SafetyClosureTask : public QueuedTask { public: explicit SafetyClosureTask(rtc::scoped_refptr safety, Closure&& closure) : closure_(std::forward(closure)), safety_flag_(std::move(safety)) {} private: bool Run() override { if (safety_flag_->alive()) closure_(); return true; } typename std::decay::type closure_; rtc::scoped_refptr safety_flag_; }; // Extends ClosureTask to also allow specifying cleanup code. // This is useful when using lambdas if guaranteeing cleanup, even if a task // was dropped (queue is too full), is required. template class ClosureTaskWithCleanup : public ClosureTask { public: ClosureTaskWithCleanup(Closure&& closure, Cleanup&& cleanup) : ClosureTask(std::forward(closure)), cleanup_(std::forward(cleanup)) {} ~ClosureTaskWithCleanup() override { cleanup_(); } private: typename std::decay::type cleanup_; }; } // namespace webrtc_new_closure_impl // Convenience function to construct closures that can be passed directly // to methods that support std::unique_ptr but not template // based parameters. template std::unique_ptr ToQueuedTask(Closure&& closure) { return std::make_unique>( std::forward(closure)); } template std::unique_ptr ToQueuedTask( rtc::scoped_refptr safety, Closure&& closure) { return std::make_unique>( std::move(safety), std::forward(closure)); } template std::unique_ptr ToQueuedTask(const ScopedTaskSafety& safety, Closure&& closure) { return ToQueuedTask(safety.flag(), std::forward(closure)); } template ::type>::type, ScopedTaskSafety>::value>::type* = nullptr> std::unique_ptr ToQueuedTask(Closure&& closure, Cleanup&& cleanup) { return std::make_unique< webrtc_new_closure_impl::ClosureTaskWithCleanup>( std::forward(closure), std::forward(cleanup)); } } // namespace webrtc #endif // RTC_BASE_TASK_UTILS_TO_QUEUED_TASK_H_