callback_helpers.h 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. // This defines helpful methods for dealing with Callbacks. Because Callbacks
  5. // are implemented using templates, with a class per callback signature, adding
  6. // methods to Callback<> itself is unattractive (lots of extra code gets
  7. // generated). Instead, consider adding methods here.
  8. #ifndef BASE_CALLBACK_HELPERS_H_
  9. #define BASE_CALLBACK_HELPERS_H_
  10. #include <memory>
  11. #include <ostream>
  12. #include <type_traits>
  13. #include <utility>
  14. #include "base/atomicops.h"
  15. #include "base/base_export.h"
  16. #include "base/bind.h"
  17. #include "base/callback.h"
  18. #include "base/check.h"
  19. namespace base {
  20. namespace internal {
  21. template <typename T>
  22. struct IsBaseCallbackImpl : std::false_type {};
  23. template <typename R, typename... Args>
  24. struct IsBaseCallbackImpl<OnceCallback<R(Args...)>> : std::true_type {};
  25. template <typename R, typename... Args>
  26. struct IsBaseCallbackImpl<RepeatingCallback<R(Args...)>> : std::true_type {};
  27. template <typename T>
  28. struct IsOnceCallbackImpl : std::false_type {};
  29. template <typename R, typename... Args>
  30. struct IsOnceCallbackImpl<OnceCallback<R(Args...)>> : std::true_type {};
  31. } // namespace internal
  32. // IsBaseCallback<T>::value is true when T is any of the Closure or Callback
  33. // family of types.
  34. template <typename T>
  35. using IsBaseCallback = internal::IsBaseCallbackImpl<std::decay_t<T>>;
  36. // IsOnceCallback<T>::value is true when T is a OnceClosure or OnceCallback
  37. // type.
  38. template <typename T>
  39. using IsOnceCallback = internal::IsOnceCallbackImpl<std::decay_t<T>>;
  40. // SFINAE friendly enabler allowing to overload methods for both Repeating and
  41. // OnceCallbacks.
  42. //
  43. // Usage:
  44. // template <template <typename> class CallbackType,
  45. // ... other template args ...,
  46. // typename = EnableIfIsBaseCallback<CallbackType>>
  47. // void DoStuff(CallbackType<...> cb, ...);
  48. template <template <typename> class CallbackType>
  49. using EnableIfIsBaseCallback =
  50. std::enable_if_t<IsBaseCallback<CallbackType<void()>>::value>;
  51. namespace internal {
  52. template <typename... Args>
  53. class OnceCallbackHolder final {
  54. public:
  55. OnceCallbackHolder(OnceCallback<void(Args...)> callback,
  56. bool ignore_extra_runs)
  57. : callback_(std::move(callback)), ignore_extra_runs_(ignore_extra_runs) {
  58. DCHECK(callback_);
  59. }
  60. OnceCallbackHolder(const OnceCallbackHolder&) = delete;
  61. OnceCallbackHolder& operator=(const OnceCallbackHolder&) = delete;
  62. void Run(Args... args) {
  63. if (subtle::NoBarrier_AtomicExchange(&has_run_, 1)) {
  64. CHECK(ignore_extra_runs_) << "Both OnceCallbacks returned by "
  65. "base::SplitOnceCallback() were run. "
  66. "At most one of the pair should be run.";
  67. return;
  68. }
  69. DCHECK(callback_);
  70. std::move(callback_).Run(std::forward<Args>(args)...);
  71. }
  72. private:
  73. volatile subtle::Atomic32 has_run_ = 0;
  74. base::OnceCallback<void(Args...)> callback_;
  75. const bool ignore_extra_runs_;
  76. };
  77. } // namespace internal
  78. // Wraps the given OnceCallback and returns two OnceCallbacks with an identical
  79. // signature. On first invokation of either returned callbacks, the original
  80. // callback is invoked. Invoking the remaining callback results in a crash.
  81. template <typename... Args>
  82. std::pair<OnceCallback<void(Args...)>, OnceCallback<void(Args...)>>
  83. SplitOnceCallback(OnceCallback<void(Args...)> callback) {
  84. if (!callback) {
  85. // Empty input begets two empty outputs.
  86. return std::make_pair(OnceCallback<void(Args...)>(),
  87. OnceCallback<void(Args...)>());
  88. }
  89. using Helper = internal::OnceCallbackHolder<Args...>;
  90. auto wrapped_once = base::BindRepeating(
  91. &Helper::Run, std::make_unique<Helper>(std::move(callback),
  92. /*ignore_extra_runs=*/false));
  93. return std::make_pair(wrapped_once, wrapped_once);
  94. }
  95. // ScopedClosureRunner is akin to std::unique_ptr<> for Closures. It ensures
  96. // that the Closure is executed no matter how the current scope exits.
  97. // If you are looking for "ScopedCallback", "CallbackRunner", or
  98. // "CallbackScoper" this is the class you want.
  99. class BASE_EXPORT ScopedClosureRunner {
  100. public:
  101. ScopedClosureRunner();
  102. explicit ScopedClosureRunner(OnceClosure closure);
  103. ScopedClosureRunner(ScopedClosureRunner&& other);
  104. // Runs the current closure if it's set, then replaces it with the closure
  105. // from |other|. This is akin to how unique_ptr frees the contained pointer in
  106. // its move assignment operator. If you need to explicitly avoid running any
  107. // current closure, use ReplaceClosure().
  108. ScopedClosureRunner& operator=(ScopedClosureRunner&& other);
  109. ~ScopedClosureRunner();
  110. explicit operator bool() const { return !!closure_; }
  111. // Calls the current closure and resets it, so it wont be called again.
  112. void RunAndReset();
  113. // Replaces closure with the new one releasing the old one without calling it.
  114. void ReplaceClosure(OnceClosure closure);
  115. // Releases the Closure without calling.
  116. [[nodiscard]] OnceClosure Release();
  117. private:
  118. OnceClosure closure_;
  119. };
  120. // Returns a placeholder type that will implicitly convert into a null callback,
  121. // similar to how absl::nullopt / std::nullptr work in conjunction with
  122. // absl::optional and various smart pointer types.
  123. constexpr auto NullCallback() {
  124. return internal::NullCallbackTag();
  125. }
  126. // Returns a placeholder type that will implicitly convert into a callback that
  127. // does nothing, similar to how absl::nullopt / std::nullptr work in conjunction
  128. // with absl::optional and various smart pointer types.
  129. constexpr auto DoNothing() {
  130. return internal::DoNothingCallbackTag();
  131. }
  132. // Similar to the above, but with a type hint. Useful for disambiguating
  133. // among multiple function overloads that take callbacks with different
  134. // signatures:
  135. //
  136. // void F(base::OnceCallback<void()> callback); // 1
  137. // void F(base::OnceCallback<void(int)> callback); // 2
  138. //
  139. // F(base::NullCallbackAs<void()>()); // calls 1
  140. // F(base::DoNothingAs<void(int)>()); // calls 2
  141. template <typename Signature>
  142. constexpr auto NullCallbackAs() {
  143. return internal::NullCallbackTag::WithSignature<Signature>();
  144. }
  145. template <typename Signature>
  146. constexpr auto DoNothingAs() {
  147. return internal::DoNothingCallbackTag::WithSignature<Signature>();
  148. }
  149. // Useful for creating a Closure that will delete a pointer when invoked. Only
  150. // use this when necessary. In most cases MessageLoop::DeleteSoon() is a better
  151. // fit.
  152. template <typename T>
  153. void DeletePointer(T* obj) {
  154. delete obj;
  155. }
  156. } // namespace base
  157. #endif // BASE_CALLBACK_HELPERS_H_