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