• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2011 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 
5 #ifndef BASE_BIND_H_
6 #define BASE_BIND_H_
7 
8 #include <utility>
9 
10 #include "base/bind_internal.h"
11 #include "base/compiler_specific.h"
12 #include "build/build_config.h"
13 
14 #if defined(OS_MACOSX) && !HAS_FEATURE(objc_arc)
15 #include "base/mac/scoped_block.h"
16 #endif
17 
18 // -----------------------------------------------------------------------------
19 // Usage documentation
20 // -----------------------------------------------------------------------------
21 //
22 // Overview:
23 // base::BindOnce() and base::BindRepeating() are helpers for creating
24 // base::OnceCallback and base::RepeatingCallback objects respectively.
25 //
26 // For a runnable object of n-arity, the base::Bind*() family allows partial
27 // application of the first m arguments. The remaining n - m arguments must be
28 // passed when invoking the callback with Run().
29 //
30 //   // The first argument is bound at callback creation; the remaining
31 //   // two must be passed when calling Run() on the callback object.
32 //   base::OnceCallback<void(int, long)> cb = base::BindOnce(
33 //       [](short x, int y, long z) { return x * y * z; }, 42);
34 //
35 // When binding to a method, the receiver object must also be specified at
36 // callback creation time. When Run() is invoked, the method will be invoked on
37 // the specified receiver object.
38 //
39 //   class C : public base::RefCounted<C> { void F(); };
40 //   auto instance = base::MakeRefCounted<C>();
41 //   auto cb = base::BindOnce(&C::F, instance);
42 //   cb.Run();  // Identical to instance->F()
43 //
44 // base::Bind is currently a type alias for base::BindRepeating(). In the
45 // future, we expect to flip this to default to base::BindOnce().
46 //
47 // See //docs/callback.md for the full documentation.
48 //
49 // -----------------------------------------------------------------------------
50 // Implementation notes
51 // -----------------------------------------------------------------------------
52 //
53 // If you're reading the implementation, before proceeding further, you should
54 // read the top comment of base/bind_internal.h for a definition of common
55 // terms and concepts.
56 
57 namespace base {
58 
59 namespace internal {
60 
61 // IsOnceCallback<T> is a std::true_type if |T| is a OnceCallback.
62 template <typename T>
63 struct IsOnceCallback : std::false_type {};
64 
65 template <typename Signature>
66 struct IsOnceCallback<OnceCallback<Signature>> : std::true_type {};
67 
68 // Helper to assert that parameter |i| of type |Arg| can be bound, which means:
69 // - |Arg| can be retained internally as |Storage|.
70 // - |Arg| can be forwarded as |Unwrapped| to |Param|.
71 template <size_t i,
72           typename Arg,
73           typename Storage,
74           typename Unwrapped,
75           typename Param>
76 struct AssertConstructible {
77  private:
78   static constexpr bool param_is_forwardable =
79       std::is_constructible<Param, Unwrapped>::value;
80   // Unlike the check for binding into storage below, the check for
81   // forwardability drops the const qualifier for repeating callbacks. This is
82   // to try to catch instances where std::move()--which forwards as a const
83   // reference with repeating callbacks--is used instead of base::Passed().
84   static_assert(
85       param_is_forwardable ||
86           !std::is_constructible<Param, std::decay_t<Unwrapped>&&>::value,
87       "Bound argument |i| is move-only but will be forwarded by copy. "
88       "Ensure |Arg| is bound using base::Passed(), not std::move().");
89   static_assert(
90       param_is_forwardable,
91       "Bound argument |i| of type |Arg| cannot be forwarded as "
92       "|Unwrapped| to the bound functor, which declares it as |Param|.");
93 
94   static constexpr bool arg_is_storable =
95       std::is_constructible<Storage, Arg>::value;
96   static_assert(arg_is_storable ||
97                     !std::is_constructible<Storage, std::decay_t<Arg>&&>::value,
98                 "Bound argument |i| is move-only but will be bound by copy. "
99                 "Ensure |Arg| is mutable and bound using std::move().");
100   static_assert(arg_is_storable,
101                 "Bound argument |i| of type |Arg| cannot be converted and "
102                 "bound as |Storage|.");
103 };
104 
105 // Takes three same-length TypeLists, and applies AssertConstructible for each
106 // triples.
107 template <typename Index,
108           typename Args,
109           typename UnwrappedTypeList,
110           typename ParamsList>
111 struct AssertBindArgsValidity;
112 
113 template <size_t... Ns,
114           typename... Args,
115           typename... Unwrapped,
116           typename... Params>
117 struct AssertBindArgsValidity<std::index_sequence<Ns...>,
118                               TypeList<Args...>,
119                               TypeList<Unwrapped...>,
120                               TypeList<Params...>>
121     : AssertConstructible<Ns, Args, std::decay_t<Args>, Unwrapped, Params>... {
122   static constexpr bool ok = true;
123 };
124 
125 // The implementation of TransformToUnwrappedType below.
126 template <bool is_once, typename T>
127 struct TransformToUnwrappedTypeImpl;
128 
129 template <typename T>
130 struct TransformToUnwrappedTypeImpl<true, T> {
131   using StoredType = std::decay_t<T>;
132   using ForwardType = StoredType&&;
133   using Unwrapped = decltype(Unwrap(std::declval<ForwardType>()));
134 };
135 
136 template <typename T>
137 struct TransformToUnwrappedTypeImpl<false, T> {
138   using StoredType = std::decay_t<T>;
139   using ForwardType = const StoredType&;
140   using Unwrapped = decltype(Unwrap(std::declval<ForwardType>()));
141 };
142 
143 // Transform |T| into `Unwrapped` type, which is passed to the target function.
144 // Example:
145 //   In is_once == true case,
146 //     `int&&` -> `int&&`,
147 //     `const int&` -> `int&&`,
148 //     `OwnedWrapper<int>&` -> `int*&&`.
149 //   In is_once == false case,
150 //     `int&&` -> `const int&`,
151 //     `const int&` -> `const int&`,
152 //     `OwnedWrapper<int>&` -> `int* const &`.
153 template <bool is_once, typename T>
154 using TransformToUnwrappedType =
155     typename TransformToUnwrappedTypeImpl<is_once, T>::Unwrapped;
156 
157 // Transforms |Args| into `Unwrapped` types, and packs them into a TypeList.
158 // If |is_method| is true, tries to dereference the first argument to support
159 // smart pointers.
160 template <bool is_once, bool is_method, typename... Args>
161 struct MakeUnwrappedTypeListImpl {
162   using Type = TypeList<TransformToUnwrappedType<is_once, Args>...>;
163 };
164 
165 // Performs special handling for this pointers.
166 // Example:
167 //   int* -> int*,
168 //   std::unique_ptr<int> -> int*.
169 template <bool is_once, typename Receiver, typename... Args>
170 struct MakeUnwrappedTypeListImpl<is_once, true, Receiver, Args...> {
171   using UnwrappedReceiver = TransformToUnwrappedType<is_once, Receiver>;
172   using Type = TypeList<decltype(&*std::declval<UnwrappedReceiver>()),
173                         TransformToUnwrappedType<is_once, Args>...>;
174 };
175 
176 template <bool is_once, bool is_method, typename... Args>
177 using MakeUnwrappedTypeList =
178     typename MakeUnwrappedTypeListImpl<is_once, is_method, Args...>::Type;
179 
180 }  // namespace internal
181 
182 // Bind as OnceCallback.
183 template <typename Functor, typename... Args>
184 inline OnceCallback<MakeUnboundRunType<Functor, Args...>>
185 BindOnce(Functor&& functor, Args&&... args) {
186   static_assert(!internal::IsOnceCallback<std::decay_t<Functor>>() ||
187                     (std::is_rvalue_reference<Functor&&>() &&
188                      !std::is_const<std::remove_reference_t<Functor>>()),
189                 "BindOnce requires non-const rvalue for OnceCallback binding."
190                 " I.e.: base::BindOnce(std::move(callback)).");
191 
192   // This block checks if each |args| matches to the corresponding params of the
193   // target function. This check does not affect the behavior of Bind, but its
194   // error message should be more readable.
195   using Helper = internal::BindTypeHelper<Functor, Args...>;
196   using FunctorTraits = typename Helper::FunctorTraits;
197   using BoundArgsList = typename Helper::BoundArgsList;
198   using UnwrappedArgsList =
199       internal::MakeUnwrappedTypeList<true, FunctorTraits::is_method,
200                                       Args&&...>;
201   using BoundParamsList = typename Helper::BoundParamsList;
202   static_assert(internal::AssertBindArgsValidity<
203                     std::make_index_sequence<Helper::num_bounds>, BoundArgsList,
204                     UnwrappedArgsList, BoundParamsList>::ok,
205                 "The bound args need to be convertible to the target params.");
206 
207   using BindState = internal::MakeBindStateType<Functor, Args...>;
208   using UnboundRunType = MakeUnboundRunType<Functor, Args...>;
209   using Invoker = internal::Invoker<BindState, UnboundRunType>;
210   using CallbackType = OnceCallback<UnboundRunType>;
211 
212   // Store the invoke func into PolymorphicInvoke before casting it to
213   // InvokeFuncStorage, so that we can ensure its type matches to
214   // PolymorphicInvoke, to which CallbackType will cast back.
215   using PolymorphicInvoke = typename CallbackType::PolymorphicInvoke;
216   PolymorphicInvoke invoke_func = &Invoker::RunOnce;
217 
218   using InvokeFuncStorage = internal::BindStateBase::InvokeFuncStorage;
219   return CallbackType(new BindState(
220       reinterpret_cast<InvokeFuncStorage>(invoke_func),
221       std::forward<Functor>(functor),
222       std::forward<Args>(args)...));
223 }
224 
225 // Bind as RepeatingCallback.
226 template <typename Functor, typename... Args>
227 inline RepeatingCallback<MakeUnboundRunType<Functor, Args...>>
228 BindRepeating(Functor&& functor, Args&&... args) {
229   static_assert(
230       !internal::IsOnceCallback<std::decay_t<Functor>>(),
231       "BindRepeating cannot bind OnceCallback. Use BindOnce with std::move().");
232 
233   // This block checks if each |args| matches to the corresponding params of the
234   // target function. This check does not affect the behavior of Bind, but its
235   // error message should be more readable.
236   using Helper = internal::BindTypeHelper<Functor, Args...>;
237   using FunctorTraits = typename Helper::FunctorTraits;
238   using BoundArgsList = typename Helper::BoundArgsList;
239   using UnwrappedArgsList =
240       internal::MakeUnwrappedTypeList<false, FunctorTraits::is_method,
241                                       Args&&...>;
242   using BoundParamsList = typename Helper::BoundParamsList;
243   static_assert(internal::AssertBindArgsValidity<
244                     std::make_index_sequence<Helper::num_bounds>, BoundArgsList,
245                     UnwrappedArgsList, BoundParamsList>::ok,
246                 "The bound args need to be convertible to the target params.");
247 
248   using BindState = internal::MakeBindStateType<Functor, Args...>;
249   using UnboundRunType = MakeUnboundRunType<Functor, Args...>;
250   using Invoker = internal::Invoker<BindState, UnboundRunType>;
251   using CallbackType = RepeatingCallback<UnboundRunType>;
252 
253   // Store the invoke func into PolymorphicInvoke before casting it to
254   // InvokeFuncStorage, so that we can ensure its type matches to
255   // PolymorphicInvoke, to which CallbackType will cast back.
256   using PolymorphicInvoke = typename CallbackType::PolymorphicInvoke;
257   PolymorphicInvoke invoke_func = &Invoker::Run;
258 
259   using InvokeFuncStorage = internal::BindStateBase::InvokeFuncStorage;
260   return CallbackType(new BindState(
261       reinterpret_cast<InvokeFuncStorage>(invoke_func),
262       std::forward<Functor>(functor),
263       std::forward<Args>(args)...));
264 }
265 
266 // Unannotated Bind.
267 // TODO(tzik): Deprecate this and migrate to OnceCallback and
268 // RepeatingCallback, once they get ready.
269 template <typename Functor, typename... Args>
270 inline Callback<MakeUnboundRunType<Functor, Args...>>
271 Bind(Functor&& functor, Args&&... args) {
272   return base::BindRepeating(std::forward<Functor>(functor),
273                              std::forward<Args>(args)...);
274 }
275 
276 // Special cases for binding to a base::Callback without extra bound arguments.
277 template <typename Signature>
278 OnceCallback<Signature> BindOnce(OnceCallback<Signature> closure) {
279   return closure;
280 }
281 
282 template <typename Signature>
283 RepeatingCallback<Signature> BindRepeating(
284     RepeatingCallback<Signature> closure) {
285   return closure;
286 }
287 
288 template <typename Signature>
289 Callback<Signature> Bind(Callback<Signature> closure) {
290   return closure;
291 }
292 
293 // Unretained() allows Bind() to bind a non-refcounted class, and to disable
294 // refcounting on arguments that are refcounted objects.
295 //
296 // EXAMPLE OF Unretained():
297 //
298 //   class Foo {
299 //    public:
300 //     void func() { cout << "Foo:f" << endl; }
301 //   };
302 //
303 //   // In some function somewhere.
304 //   Foo foo;
305 //   Closure foo_callback =
306 //       Bind(&Foo::func, Unretained(&foo));
307 //   foo_callback.Run();  // Prints "Foo:f".
308 //
309 // Without the Unretained() wrapper on |&foo|, the above call would fail
310 // to compile because Foo does not support the AddRef() and Release() methods.
311 template <typename T>
312 static inline internal::UnretainedWrapper<T> Unretained(T* o) {
313   return internal::UnretainedWrapper<T>(o);
314 }
315 
316 // RetainedRef() accepts a ref counted object and retains a reference to it.
317 // When the callback is called, the object is passed as a raw pointer.
318 //
319 // EXAMPLE OF RetainedRef():
320 //
321 //    void foo(RefCountedBytes* bytes) {}
322 //
323 //    scoped_refptr<RefCountedBytes> bytes = ...;
324 //    Closure callback = Bind(&foo, base::RetainedRef(bytes));
325 //    callback.Run();
326 //
327 // Without RetainedRef, the scoped_refptr would try to implicitly convert to
328 // a raw pointer and fail compilation:
329 //
330 //    Closure callback = Bind(&foo, bytes); // ERROR!
331 template <typename T>
332 static inline internal::RetainedRefWrapper<T> RetainedRef(T* o) {
333   return internal::RetainedRefWrapper<T>(o);
334 }
335 template <typename T>
336 static inline internal::RetainedRefWrapper<T> RetainedRef(scoped_refptr<T> o) {
337   return internal::RetainedRefWrapper<T>(std::move(o));
338 }
339 
340 // ConstRef() allows binding a constant reference to an argument rather
341 // than a copy.
342 //
343 // EXAMPLE OF ConstRef():
344 //
345 //   void foo(int arg) { cout << arg << endl }
346 //
347 //   int n = 1;
348 //   Closure no_ref = Bind(&foo, n);
349 //   Closure has_ref = Bind(&foo, ConstRef(n));
350 //
351 //   no_ref.Run();  // Prints "1"
352 //   has_ref.Run();  // Prints "1"
353 //
354 //   n = 2;
355 //   no_ref.Run();  // Prints "1"
356 //   has_ref.Run();  // Prints "2"
357 //
358 // Note that because ConstRef() takes a reference on |n|, |n| must outlive all
359 // its bound callbacks.
360 template <typename T>
361 static inline internal::ConstRefWrapper<T> ConstRef(const T& o) {
362   return internal::ConstRefWrapper<T>(o);
363 }
364 
365 // Owned() transfers ownership of an object to the Callback resulting from
366 // bind; the object will be deleted when the Callback is deleted.
367 //
368 // EXAMPLE OF Owned():
369 //
370 //   void foo(int* arg) { cout << *arg << endl }
371 //
372 //   int* pn = new int(1);
373 //   Closure foo_callback = Bind(&foo, Owned(pn));
374 //
375 //   foo_callback.Run();  // Prints "1"
376 //   foo_callback.Run();  // Prints "1"
377 //   *n = 2;
378 //   foo_callback.Run();  // Prints "2"
379 //
380 //   foo_callback.Reset();  // |pn| is deleted.  Also will happen when
381 //                          // |foo_callback| goes out of scope.
382 //
383 // Without Owned(), someone would have to know to delete |pn| when the last
384 // reference to the Callback is deleted.
385 template <typename T>
386 static inline internal::OwnedWrapper<T> Owned(T* o) {
387   return internal::OwnedWrapper<T>(o);
388 }
389 
390 // Passed() is for transferring movable-but-not-copyable types (eg. unique_ptr)
391 // through a Callback. Logically, this signifies a destructive transfer of
392 // the state of the argument into the target function.  Invoking
393 // Callback::Run() twice on a Callback that was created with a Passed()
394 // argument will CHECK() because the first invocation would have already
395 // transferred ownership to the target function.
396 //
397 // Note that Passed() is not necessary with BindOnce(), as std::move() does the
398 // same thing. Avoid Passed() in favor of std::move() with BindOnce().
399 //
400 // EXAMPLE OF Passed():
401 //
402 //   void TakesOwnership(std::unique_ptr<Foo> arg) { }
403 //   std::unique_ptr<Foo> CreateFoo() { return std::make_unique<Foo>();
404 //   }
405 //
406 //   auto f = std::make_unique<Foo>();
407 //
408 //   // |cb| is given ownership of Foo(). |f| is now NULL.
409 //   // You can use std::move(f) in place of &f, but it's more verbose.
410 //   Closure cb = Bind(&TakesOwnership, Passed(&f));
411 //
412 //   // Run was never called so |cb| still owns Foo() and deletes
413 //   // it on Reset().
414 //   cb.Reset();
415 //
416 //   // |cb| is given a new Foo created by CreateFoo().
417 //   cb = Bind(&TakesOwnership, Passed(CreateFoo()));
418 //
419 //   // |arg| in TakesOwnership() is given ownership of Foo(). |cb|
420 //   // no longer owns Foo() and, if reset, would not delete Foo().
421 //   cb.Run();  // Foo() is now transferred to |arg| and deleted.
422 //   cb.Run();  // This CHECK()s since Foo() already been used once.
423 //
424 // We offer 2 syntaxes for calling Passed().  The first takes an rvalue and
425 // is best suited for use with the return value of a function or other temporary
426 // rvalues. The second takes a pointer to the scoper and is just syntactic sugar
427 // to avoid having to write Passed(std::move(scoper)).
428 //
429 // Both versions of Passed() prevent T from being an lvalue reference. The first
430 // via use of enable_if, and the second takes a T* which will not bind to T&.
431 template <typename T,
432           std::enable_if_t<!std::is_lvalue_reference<T>::value>* = nullptr>
433 static inline internal::PassedWrapper<T> Passed(T&& scoper) {
434   return internal::PassedWrapper<T>(std::move(scoper));
435 }
436 template <typename T>
437 static inline internal::PassedWrapper<T> Passed(T* scoper) {
438   return internal::PassedWrapper<T>(std::move(*scoper));
439 }
440 
441 // IgnoreResult() is used to adapt a function or Callback with a return type to
442 // one with a void return. This is most useful if you have a function with,
443 // say, a pesky ignorable bool return that you want to use with PostTask or
444 // something else that expect a Callback with a void return.
445 //
446 // EXAMPLE OF IgnoreResult():
447 //
448 //   int DoSomething(int arg) { cout << arg << endl; }
449 //
450 //   // Assign to a Callback with a void return type.
451 //   Callback<void(int)> cb = Bind(IgnoreResult(&DoSomething));
452 //   cb->Run(1);  // Prints "1".
453 //
454 //   // Prints "1" on |ml|.
455 //   ml->PostTask(FROM_HERE, Bind(IgnoreResult(&DoSomething), 1);
456 template <typename T>
457 static inline internal::IgnoreResultHelper<T> IgnoreResult(T data) {
458   return internal::IgnoreResultHelper<T>(std::move(data));
459 }
460 
461 #if defined(OS_MACOSX) && !HAS_FEATURE(objc_arc)
462 
463 // RetainBlock() is used to adapt an Objective-C block when Automated Reference
464 // Counting (ARC) is disabled. This is unnecessary when ARC is enabled, as the
465 // BindOnce and BindRepeating already support blocks then.
466 //
467 // EXAMPLE OF RetainBlock():
468 //
469 //   // Wrap the block and bind it to a callback.
470 //   Callback<void(int)> cb = Bind(RetainBlock(^(int n) { NSLog(@"%d", n); }));
471 //   cb.Run(1);  // Logs "1".
472 template <typename R, typename... Args>
473 base::mac::ScopedBlock<R (^)(Args...)> RetainBlock(R (^block)(Args...)) {
474   return base::mac::ScopedBlock<R (^)(Args...)>(block,
475                                                 base::scoped_policy::RETAIN);
476 }
477 
478 #endif  // defined(OS_MACOSX) && !HAS_FEATURE(objc_arc)
479 
480 }  // namespace base
481 
482 #endif  // BASE_BIND_H_
483