Fix emulator build error
[platform/framework/web/chromium-efl.git] / base / functional / callback_helpers.h
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.
4
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.
9
10 #ifndef BASE_FUNCTIONAL_CALLBACK_HELPERS_H_
11 #define BASE_FUNCTIONAL_CALLBACK_HELPERS_H_
12
13 #include <atomic>
14 #include <memory>
15 #include <ostream>
16 #include <type_traits>
17 #include <utility>
18
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"
25
26 namespace base {
27
28 namespace internal {
29
30 template <typename T>
31 struct IsBaseCallbackImpl : std::false_type {};
32
33 template <typename R, typename... Args>
34 struct IsBaseCallbackImpl<OnceCallback<R(Args...)>> : std::true_type {};
35
36 template <typename R, typename... Args>
37 struct IsBaseCallbackImpl<RepeatingCallback<R(Args...)>> : std::true_type {};
38
39 template <typename T>
40 struct IsOnceCallbackImpl : std::false_type {};
41
42 template <typename R, typename... Args>
43 struct IsOnceCallbackImpl<OnceCallback<R(Args...)>> : std::true_type {};
44
45 }  // namespace internal
46
47 // IsBaseCallback<T>::value is true when T is any of the Closure or Callback
48 // family of types.
49 template <typename T>
50 using IsBaseCallback = internal::IsBaseCallbackImpl<std::decay_t<T>>;
51
52 // IsOnceCallback<T>::value is true when T is a OnceClosure or OnceCallback
53 // type.
54 template <typename T>
55 using IsOnceCallback = internal::IsOnceCallbackImpl<std::decay_t<T>>;
56
57 // SFINAE friendly enabler allowing to overload methods for both Repeating and
58 // OnceCallbacks.
59 //
60 // Usage:
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>;
68
69 namespace internal {
70
71 template <typename... Args>
72 class OnceCallbackHolder final {
73  public:
74   OnceCallbackHolder(OnceCallback<void(Args...)> callback,
75                      bool ignore_extra_runs)
76       : callback_(std::move(callback)), ignore_extra_runs_(ignore_extra_runs) {
77     DCHECK(callback_);
78   }
79   OnceCallbackHolder(const OnceCallbackHolder&) = delete;
80   OnceCallbackHolder& operator=(const OnceCallbackHolder&) = delete;
81
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.";
87       return;
88     }
89     DCHECK(callback_);
90     std::move(callback_).Run(std::forward<Args>(args)...);
91   }
92
93  private:
94   std::atomic<bool> has_run_{false};
95   base::OnceCallback<void(Args...)> callback_;
96   const bool ignore_extra_runs_;
97 };
98
99 template <typename... Args>
100 void ForwardRepeatingCallbacksImpl(
101     std::vector<RepeatingCallback<void(Args...)>> cbs,
102     Args... args) {
103   for (auto& cb : cbs) {
104     if (cb) {
105       cb.Run(std::forward<Args>(args)...);
106     }
107   }
108 }
109
110 }  // namespace internal
111
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.
116 //
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));
127 }
128 #endif
129
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
133 // must be copyable.
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...)>>>(
139           cbs));
140   return BindRepeating(&internal::ForwardRepeatingCallbacksImpl<Args...>,
141                        std::move(v));
142 }
143
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) {
150   if (!callback) {
151     // Empty input begets two empty outputs.
152     return std::make_pair(OnceCallback<void(Args...)>(),
153                           OnceCallback<void(Args...)>());
154   }
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);
160 }
161
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.
164 //
165 // Usage:
166 //   void LogError(char* error_message) {
167 //     if (error_message) {
168 //       cout << "Log: " << error_message << endl;
169 //     }
170 //   }
171 //   base::RepeatingCallback<void(int, char*)> cb =
172 //      base::IgnoreArgs<int>(base::BindRepeating(&LogError));
173 //   cb.Run(42, nullptr);
174 //
175 // Note in the example above that the type(s) passed to `IgnoreArgs`
176 // represent the additional prepended parameters (those which will be
177 // "ignored").
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)...);
185                         },
186                         std::move(callback))
187                   : RepeatingCallback<void(Preargs..., Args...)>();
188 }
189
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...,
196                            Args... args) {
197                           std::move(callback).Run(std::forward<Args>(args)...);
198                         },
199                         std::move(callback))
200                   : OnceCallback<void(Preargs..., Args...)>();
201 }
202
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 {
208  public:
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();
218
219   explicit operator bool() const { return !!closure_; }
220
221   // Calls the current closure and resets it, so it wont be called again.
222   void RunAndReset();
223
224   // Replaces closure with the new one releasing the old one without calling it.
225   void ReplaceClosure(OnceClosure closure);
226
227   // Releases the Closure without calling.
228   [[nodiscard]] OnceClosure Release();
229
230  private:
231   OnceClosure closure_;
232 };
233
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();
239 }
240
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();
246 }
247
248 // Similar to the above, but with a type hint. Useful for disambiguating
249 // among multiple function overloads that take callbacks with different
250 // signatures:
251 //
252 // void F(base::OnceCallback<void()> callback);     // 1
253 // void F(base::OnceCallback<void(int)> callback);  // 2
254 //
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>();
260 }
261
262 template <typename Signature>
263 constexpr auto DoNothingAs() {
264   return internal::DoNothingCallbackTag::WithSignature<Signature>();
265 }
266
267 // Similar to DoNothing above, but with bound arguments. This helper is useful
268 // for keeping objects alive until the callback runs.
269 // Example:
270 //
271 // void F(base::OnceCallback<void(int)> result_callback);
272 //
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)...);
279 }
280
281 // Creates a callback that returns `value` when invoked. This helper is useful
282 // for implementing factories that return a constant value.
283 // Example:
284 //
285 // void F(base::OnceCallback<Widget()> factory);
286 //
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));
293 }
294
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
297 // fit.
298 template <typename T>
299 void DeletePointer(T* obj) {
300   delete obj;
301 }
302
303 #if __OBJC__
304
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.
308 //
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)...);
318   };
319 }
320
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)...);
325   };
326 }
327
328 #endif  // __OBJC__
329
330 }  // namespace base
331
332 #endif  // BASE_FUNCTIONAL_CALLBACK_HELPERS_H_