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