1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // This defines helpful methods for dealing with Callbacks. Because Callbacks
6 // are implemented using templates, with a class per callback signature, adding
7 // methods to Callback<> itself is unattractive (lots of extra code gets
8 // generated). Instead, consider adding methods here.
10 #ifndef BASE_FUNCTIONAL_CALLBACK_HELPERS_H_
11 #define BASE_FUNCTIONAL_CALLBACK_HELPERS_H_
16 #include <type_traits>
19 #include "base/atomicops.h"
20 #include "base/base_export.h"
21 #include "base/check.h"
22 #include "base/functional/bind.h"
23 #include "base/functional/callback.h"
24 #include "base/functional/callback_tags.h"
31 struct IsBaseCallbackImpl : std::false_type {};
33 template <typename R, typename... Args>
34 struct IsBaseCallbackImpl<OnceCallback<R(Args...)>> : std::true_type {};
36 template <typename R, typename... Args>
37 struct IsBaseCallbackImpl<RepeatingCallback<R(Args...)>> : std::true_type {};
40 struct IsOnceCallbackImpl : std::false_type {};
42 template <typename R, typename... Args>
43 struct IsOnceCallbackImpl<OnceCallback<R(Args...)>> : std::true_type {};
45 } // namespace internal
47 // IsBaseCallback<T>::value is true when T is any of the Closure or Callback
50 using IsBaseCallback = internal::IsBaseCallbackImpl<std::decay_t<T>>;
52 // IsOnceCallback<T>::value is true when T is a OnceClosure or OnceCallback
55 using IsOnceCallback = internal::IsOnceCallbackImpl<std::decay_t<T>>;
57 // SFINAE friendly enabler allowing to overload methods for both Repeating and
61 // template <template <typename> class CallbackType,
62 // ... other template args ...,
63 // typename = EnableIfIsBaseCallback<CallbackType>>
64 // void DoStuff(CallbackType<...> cb, ...);
65 template <template <typename> class CallbackType>
66 using EnableIfIsBaseCallback =
67 std::enable_if_t<IsBaseCallback<CallbackType<void()>>::value>;
71 template <typename... Args>
72 class OnceCallbackHolder final {
74 OnceCallbackHolder(OnceCallback<void(Args...)> callback,
75 bool ignore_extra_runs)
76 : callback_(std::move(callback)), ignore_extra_runs_(ignore_extra_runs) {
79 OnceCallbackHolder(const OnceCallbackHolder&) = delete;
80 OnceCallbackHolder& operator=(const OnceCallbackHolder&) = delete;
82 void Run(Args... args) {
83 if (has_run_.exchange(true, std::memory_order_relaxed)) {
84 CHECK(ignore_extra_runs_) << "Both OnceCallbacks returned by "
85 "base::SplitOnceCallback() were run. "
86 "At most one of the pair should be run.";
90 std::move(callback_).Run(std::forward<Args>(args)...);
94 std::atomic<bool> has_run_{false};
95 base::OnceCallback<void(Args...)> callback_;
96 const bool ignore_extra_runs_;
99 template <typename... Args>
100 void ForwardRepeatingCallbacksImpl(
101 std::vector<RepeatingCallback<void(Args...)>> cbs,
103 for (auto& cb : cbs) {
105 cb.Run(std::forward<Args>(args)...);
110 } // namespace internal
112 #if defined(ENABLE_WRT_JS) // Remove this after removing usage in electron
113 // Wraps the given OnceCallback into a RepeatingCallback that relays its
114 // invocation to the original OnceCallback on the first invocation. The
115 // following invocations are just ignored.
117 // Note that this deliberately subverts the Once/Repeating paradigm of Callbacks
118 // but helps ease the migration from old-style Callbacks. Avoid if possible; use
119 // if necessary for migration. TODO(tzik): Remove it. https://crbug.com/730593
120 template <typename... Args>
121 RepeatingCallback<void(Args...)> AdaptCallbackForRepeating(
122 OnceCallback<void(Args...)> callback) {
123 using Helper = internal::OnceCallbackHolder<Args...>;
124 return base::BindRepeating(
125 &Helper::Run, std::make_unique<Helper>(std::move(callback),
126 /*ignore_extra_runs=*/true));
130 // Wraps the given RepeatingCallbacks and return one RepeatingCallbacks with an
131 // identical signature. On invocation of this callback, all the given
132 // RepeatingCallbacks will be called with the same arguments. Unbound arguments
134 template <typename... Args>
135 RepeatingCallback<void(Args...)> ForwardRepeatingCallbacks(
136 std::initializer_list<RepeatingCallback<void(Args...)>>&& cbs) {
137 std::vector<RepeatingCallback<void(Args...)>> v(
138 std::forward<std::initializer_list<RepeatingCallback<void(Args...)>>>(
140 return BindRepeating(&internal::ForwardRepeatingCallbacksImpl<Args...>,
144 // Wraps the given OnceCallback and returns two OnceCallbacks with an identical
145 // signature. On first invokation of either returned callbacks, the original
146 // callback is invoked. Invoking the remaining callback results in a crash.
147 template <typename... Args>
148 std::pair<OnceCallback<void(Args...)>, OnceCallback<void(Args...)>>
149 SplitOnceCallback(OnceCallback<void(Args...)> callback) {
151 // Empty input begets two empty outputs.
152 return std::make_pair(OnceCallback<void(Args...)>(),
153 OnceCallback<void(Args...)>());
155 using Helper = internal::OnceCallbackHolder<Args...>;
156 auto wrapped_once = base::BindRepeating(
157 &Helper::Run, std::make_unique<Helper>(std::move(callback),
158 /*ignore_extra_runs=*/false));
159 return std::make_pair(wrapped_once, wrapped_once);
162 // Adapts `callback` for use in a context which is expecting a callback with
163 // additional parameters. Returns a null callback if `callback` is null.
166 // void LogError(char* error_message) {
167 // if (error_message) {
168 // cout << "Log: " << error_message << endl;
171 // base::RepeatingCallback<void(int, char*)> cb =
172 // base::IgnoreArgs<int>(base::BindRepeating(&LogError));
173 // cb.Run(42, nullptr);
175 // Note in the example above that the type(s) passed to `IgnoreArgs`
176 // represent the additional prepended parameters (those which will be
178 template <typename... Preargs, typename... Args>
179 RepeatingCallback<void(Preargs..., Args...)> IgnoreArgs(
180 RepeatingCallback<void(Args...)> callback) {
181 return callback ? BindRepeating(
182 [](RepeatingCallback<void(Args...)> callback,
183 Preargs..., Args... args) {
184 std::move(callback).Run(std::forward<Args>(args)...);
187 : RepeatingCallback<void(Preargs..., Args...)>();
190 // As above, but for OnceCallback.
191 template <typename... Preargs, typename... Args>
192 OnceCallback<void(Preargs..., Args...)> IgnoreArgs(
193 OnceCallback<void(Args...)> callback) {
194 return callback ? BindOnce(
195 [](OnceCallback<void(Args...)> callback, Preargs...,
197 std::move(callback).Run(std::forward<Args>(args)...);
200 : OnceCallback<void(Preargs..., Args...)>();
203 // ScopedClosureRunner is akin to std::unique_ptr<> for Closures. It ensures
204 // that the Closure is executed no matter how the current scope exits.
205 // If you are looking for "ScopedCallback", "CallbackRunner", or
206 // "CallbackScoper" this is the class you want.
207 class BASE_EXPORT ScopedClosureRunner {
209 ScopedClosureRunner();
210 explicit ScopedClosureRunner(OnceClosure closure);
211 ScopedClosureRunner(ScopedClosureRunner&& other);
212 // Runs the current closure if it's set, then replaces it with the closure
213 // from |other|. This is akin to how unique_ptr frees the contained pointer in
214 // its move assignment operator. If you need to explicitly avoid running any
215 // current closure, use ReplaceClosure().
216 ScopedClosureRunner& operator=(ScopedClosureRunner&& other);
217 ~ScopedClosureRunner();
219 explicit operator bool() const { return !!closure_; }
221 // Calls the current closure and resets it, so it wont be called again.
224 // Replaces closure with the new one releasing the old one without calling it.
225 void ReplaceClosure(OnceClosure closure);
227 // Releases the Closure without calling.
228 [[nodiscard]] OnceClosure Release();
231 OnceClosure closure_;
234 // Returns a placeholder type that will implicitly convert into a null callback,
235 // similar to how absl::nullopt / std::nullptr work in conjunction with
236 // absl::optional and various smart pointer types.
237 constexpr auto NullCallback() {
238 return internal::NullCallbackTag();
241 // Returns a placeholder type that will implicitly convert into a callback that
242 // does nothing, similar to how absl::nullopt / std::nullptr work in conjunction
243 // with absl::optional and various smart pointer types.
244 constexpr auto DoNothing() {
245 return internal::DoNothingCallbackTag();
248 // Similar to the above, but with a type hint. Useful for disambiguating
249 // among multiple function overloads that take callbacks with different
252 // void F(base::OnceCallback<void()> callback); // 1
253 // void F(base::OnceCallback<void(int)> callback); // 2
255 // F(base::NullCallbackAs<void()>()); // calls 1
256 // F(base::DoNothingAs<void(int)>()); // calls 2
257 template <typename Signature>
258 constexpr auto NullCallbackAs() {
259 return internal::NullCallbackTag::WithSignature<Signature>();
262 template <typename Signature>
263 constexpr auto DoNothingAs() {
264 return internal::DoNothingCallbackTag::WithSignature<Signature>();
267 // Similar to DoNothing above, but with bound arguments. This helper is useful
268 // for keeping objects alive until the callback runs.
271 // void F(base::OnceCallback<void(int)> result_callback);
273 // std::unique_ptr<MyClass> ptr;
274 // F(base::DoNothingWithBoundArgs(std::move(ptr)));
275 template <typename... Args>
276 constexpr auto DoNothingWithBoundArgs(Args&&... args) {
277 return internal::DoNothingCallbackTag::WithBoundArguments(
278 std::forward<Args>(args)...);
281 // Creates a callback that returns `value` when invoked. This helper is useful
282 // for implementing factories that return a constant value.
285 // void F(base::OnceCallback<Widget()> factory);
287 // Widget widget = ...;
288 // F(base::ReturnValueOnce(std::move(widget)));
289 template <typename T>
290 constexpr OnceCallback<T(void)> ReturnValueOnce(T value) {
291 static_assert(!std::is_reference_v<T>);
292 return base::BindOnce([](T value) { return value; }, std::move(value));
295 // Useful for creating a Closure that will delete a pointer when invoked. Only
296 // use this when necessary. In most cases MessageLoop::DeleteSoon() is a better
298 template <typename T>
299 void DeletePointer(T* obj) {
305 // Creates an Objective-C block with the same signature as the corresponding
306 // callback. Can be used to implement a callback based API internally based
307 // on a block based Objective-C API.
309 // Overloaded to work with both repeating and one shot callbacks. Calling the
310 // block wrapping a base::OnceCallback<...> multiple times will crash (there
311 // is no way to mark the block as callable only once). Only use that when you
312 // know that Objective-C API will only invoke the block once.
313 template <typename R, typename... Args>
314 auto CallbackToBlock(base::OnceCallback<R(Args...)> callback) {
315 __block base::OnceCallback<R(Args...)> block_callback = std::move(callback);
316 return ^(Args... args) {
317 return std::move(block_callback).Run(std::forward<Args>(args)...);
321 template <typename R, typename... Args>
322 auto CallbackToBlock(base::RepeatingCallback<R(Args...)> callback) {
323 return ^(Args... args) {
324 return callback.Run(std::forward<Args>(args)...);
332 #endif // BASE_FUNCTIONAL_CALLBACK_HELPERS_H_