blob: fefd7a2b2010ed118ef278cb54a60e1eee132190 [file] [log] [blame]
willchan@chromium.org9be58392012-03-23 09:08:42 +09001// Copyright (c) 2012 The Chromium Authors. All rights reserved.
ajwong@chromium.orge2cca632011-02-15 10:27:38 +09002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// This file contains utility functions and classes that help the
6// implementation, and management of the Callback objects.
7
ajwong@chromium.orgfa0ff432011-02-19 08:29:31 +09008#ifndef BASE_CALLBACK_INTERNAL_H_
9#define BASE_CALLBACK_INTERNAL_H_
ajwong@chromium.orge2cca632011-02-15 10:27:38 +090010
jhawkins@chromium.org8e73d062011-04-05 03:04:37 +090011#include <stddef.h>
12
tapted9cef4212015-05-14 17:03:32 +090013#include "base/atomic_ref_count.h"
darin@chromium.orge585bed2011-08-06 00:34:00 +090014#include "base/base_export.h"
tapted9cef4212015-05-14 17:03:32 +090015#include "base/macros.h"
levin@chromium.org5c528682011-03-28 10:54:15 +090016#include "base/memory/ref_counted.h"
ajwong@chromium.orgf66a7db2011-12-23 06:12:58 +090017#include "base/memory/scoped_ptr.h"
tapted9cef4212015-05-14 17:03:32 +090018#include "base/template_util.h"
ajwong@chromium.orge2cca632011-02-15 10:27:38 +090019
willchan@chromium.org9be58392012-03-23 09:08:42 +090020template <typename T>
21class ScopedVector;
22
ajwong@chromium.orge2cca632011-02-15 10:27:38 +090023namespace base {
24namespace internal {
tapted9cef4212015-05-14 17:03:32 +090025class CallbackBase;
ajwong@chromium.orge2cca632011-02-15 10:27:38 +090026
ajwong@chromium.orgc9c79af2011-11-22 04:23:44 +090027// BindStateBase is used to provide an opaque handle that the Callback
ajwong@chromium.orge2cca632011-02-15 10:27:38 +090028// class can use to represent a function object with bound arguments. It
29// behaves as an existential type that is used by a corresponding
30// DoInvoke function to perform the function execution. This allows
31// us to shield the Callback class from the types of the bound argument via
32// "type erasure."
tapted9cef4212015-05-14 17:03:32 +090033// At the base level, the only task is to add reference counting data. Don't use
34// RefCountedThreadSafe since it requires the destructor to be a virtual method.
35// Creating a vtable for every BindState template instantiation results in a lot
36// of bloat. Its only task is to call the destructor which can be done with a
37// function pointer.
38class BindStateBase {
ajwong@chromium.orge2cca632011-02-15 10:27:38 +090039 protected:
tapted9cef4212015-05-14 17:03:32 +090040 explicit BindStateBase(void (*destructor)(BindStateBase*))
41 : ref_count_(0), destructor_(destructor) {}
42 ~BindStateBase() = default;
43
44 private:
45 friend class scoped_refptr<BindStateBase>;
46 friend class CallbackBase;
47
48 void AddRef();
49 void Release();
50
51 AtomicRefCount ref_count_;
52
53 // Pointer to a function that will properly destroy |this|.
54 void (*destructor_)(BindStateBase*);
55
56 DISALLOW_COPY_AND_ASSIGN(BindStateBase);
ajwong@chromium.orge2cca632011-02-15 10:27:38 +090057};
58
ajwong@chromium.orgfa0ff432011-02-19 08:29:31 +090059// Holds the Callback methods that don't require specialization to reduce
60// template bloat.
darin@chromium.orge585bed2011-08-06 00:34:00 +090061class BASE_EXPORT CallbackBase {
ajwong@chromium.orgfa0ff432011-02-19 08:29:31 +090062 public:
dcheng60283a82014-11-26 14:04:55 +090063 CallbackBase(const CallbackBase& c);
64 CallbackBase& operator=(const CallbackBase& c);
65
ajwong@chromium.orgfa0ff432011-02-19 08:29:31 +090066 // Returns true if Callback is null (doesn't refer to anything).
ricea61846ae2014-09-17 11:12:53 +090067 bool is_null() const { return bind_state_.get() == NULL; }
ajwong@chromium.orgfa0ff432011-02-19 08:29:31 +090068
jhawkins@chromium.org4d570be2011-10-26 08:19:51 +090069 // Returns the Callback into an uninitialized state.
ajwong@chromium.orgfa0ff432011-02-19 08:29:31 +090070 void Reset();
71
ajwong@chromium.org3bc50ce2011-09-10 12:14:35 +090072 protected:
ajwong@chromium.orgfa0ff432011-02-19 08:29:31 +090073 // In C++, it is safe to cast function pointers to function pointers of
74 // another type. It is not okay to use void*. We create a InvokeFuncStorage
75 // that that can store our function pointer, and then cast it back to
76 // the original type on usage.
77 typedef void(*InvokeFuncStorage)(void);
78
jhawkins@chromium.org4d570be2011-10-26 08:19:51 +090079 // Returns true if this callback equals |other|. |other| may be null.
80 bool Equals(const CallbackBase& other) const;
81
ajwong@chromium.orgabd70002011-12-20 09:10:04 +090082 // Allow initializing of |bind_state_| via the constructor to avoid default
83 // initialization of the scoped_refptr. We do not also initialize
84 // |polymorphic_invoke_| here because doing a normal assignment in the
85 // derived Callback templates makes for much nicer compiler errors.
86 explicit CallbackBase(BindStateBase* bind_state);
ajwong@chromium.orgfa0ff432011-02-19 08:29:31 +090087
jhawkins@chromium.org4d570be2011-10-26 08:19:51 +090088 // Force the destructor to be instantiated inside this translation unit so
ajwong@chromium.orgfa0ff432011-02-19 08:29:31 +090089 // that our subclasses will not get inlined versions. Avoids more template
90 // bloat.
91 ~CallbackBase();
92
ajwong@chromium.orgc9c79af2011-11-22 04:23:44 +090093 scoped_refptr<BindStateBase> bind_state_;
ajwong@chromium.orgfa0ff432011-02-19 08:29:31 +090094 InvokeFuncStorage polymorphic_invoke_;
95};
96
kinuko@chromium.org288f27a2013-10-22 18:18:20 +090097// A helper template to determine if given type is non-const move-only-type,
98// i.e. if a value of the given type should be passed via .Pass() in a
99// destructive way.
100template <typename T> struct IsMoveOnlyType {
101 template <typename U>
102 static YesType Test(const typename U::MoveOnlyTypeForCPP03*);
103
104 template <typename U>
105 static NoType Test(...);
106
brucedawson137c1532014-10-29 07:18:04 +0900107 static const bool value = sizeof((Test<T>(0))) == sizeof(YesType) &&
kinuko@chromium.org288f27a2013-10-22 18:18:20 +0900108 !is_const<T>::value;
109};
110
tzikf9c38192014-11-20 10:08:20 +0900111// Returns |Then| as SelectType::Type if |condition| is true. Otherwise returns
112// |Else|.
113template <bool condition, typename Then, typename Else>
114struct SelectType {
115 typedef Then Type;
116};
117
118template <typename Then, typename Else>
119struct SelectType<false, Then, Else> {
120 typedef Else Type;
121};
122
123template <typename>
124struct CallbackParamTraitsForMoveOnlyType;
125
126template <typename>
127struct CallbackParamTraitsForNonMoveOnlyType;
128
129// TODO(tzik): Use a default parameter once MSVS supports variadic templates
130// with default values.
131// http://connect.microsoft.com/VisualStudio/feedbackdetail/view/957801/compilation-error-with-variadic-templates
132//
ajwong@chromium.orga7e74822011-03-24 11:02:17 +0900133// This is a typetraits object that's used to take an argument type, and
134// extract a suitable type for storing and forwarding arguments.
135//
136// In particular, it strips off references, and converts arrays to
137// pointers for storage; and it avoids accidentally trying to create a
138// "reference of a reference" if the argument is a reference type.
139//
140// This array type becomes an issue for storage because we are passing bound
141// parameters by const reference. In this case, we end up passing an actual
142// array type in the initializer list which C++ does not allow. This will
143// break passing of C-string literals.
tzikf9c38192014-11-20 10:08:20 +0900144template <typename T>
145struct CallbackParamTraits
146 : SelectType<IsMoveOnlyType<T>::value,
147 CallbackParamTraitsForMoveOnlyType<T>,
148 CallbackParamTraitsForNonMoveOnlyType<T> >::Type {
149};
150
151template <typename T>
152struct CallbackParamTraitsForNonMoveOnlyType {
ajwong@chromium.orga7e74822011-03-24 11:02:17 +0900153 typedef const T& ForwardType;
154 typedef T StorageType;
155};
156
157// The Storage should almost be impossible to trigger unless someone manually
158// specifies type of the bind parameters. However, in case they do,
159// this will guard against us accidentally storing a reference parameter.
160//
161// The ForwardType should only be used for unbound arguments.
162template <typename T>
tzikf9c38192014-11-20 10:08:20 +0900163struct CallbackParamTraitsForNonMoveOnlyType<T&> {
ajwong@chromium.orga7e74822011-03-24 11:02:17 +0900164 typedef T& ForwardType;
165 typedef T StorageType;
166};
167
168// Note that for array types, we implicitly add a const in the conversion. This
169// means that it is not possible to bind array arguments to functions that take
170// a non-const pointer. Trying to specialize the template based on a "const
171// T[n]" does not seem to match correctly, so we are stuck with this
172// restriction.
173template <typename T, size_t n>
tzikf9c38192014-11-20 10:08:20 +0900174struct CallbackParamTraitsForNonMoveOnlyType<T[n]> {
ajwong@chromium.orga7e74822011-03-24 11:02:17 +0900175 typedef const T* ForwardType;
176 typedef const T* StorageType;
177};
178
ajwong@chromium.orgc9c79af2011-11-22 04:23:44 +0900179// See comment for CallbackParamTraits<T[n]>.
ajwong@chromium.orga7e74822011-03-24 11:02:17 +0900180template <typename T>
tzikf9c38192014-11-20 10:08:20 +0900181struct CallbackParamTraitsForNonMoveOnlyType<T[]> {
ajwong@chromium.orga7e74822011-03-24 11:02:17 +0900182 typedef const T* ForwardType;
183 typedef const T* StorageType;
184};
185
ajwong@chromium.orgf66a7db2011-12-23 06:12:58 +0900186// Parameter traits for movable-but-not-copyable scopers.
187//
188// Callback<>/Bind() understands movable-but-not-copyable semantics where
189// the type cannot be copied but can still have its state destructively
190// transferred (aka. moved) to another instance of the same type by calling a
191// helper function. When used with Bind(), this signifies transferal of the
192// object's state to the target function.
193//
194// For these types, the ForwardType must not be a const reference, or a
195// reference. A const reference is inappropriate, and would break const
196// correctness, because we are implementing a destructive move. A non-const
197// reference cannot be used with temporaries which means the result of a
198// function or a cast would not be usable with Callback<> or Bind().
willchan@chromium.org9be58392012-03-23 09:08:42 +0900199template <typename T>
tzikf9c38192014-11-20 10:08:20 +0900200struct CallbackParamTraitsForMoveOnlyType {
kinuko@chromium.org288f27a2013-10-22 18:18:20 +0900201 typedef T ForwardType;
202 typedef T StorageType;
willchan@chromium.org9be58392012-03-23 09:08:42 +0900203};
204
ajwong@chromium.orgf66a7db2011-12-23 06:12:58 +0900205// CallbackForward() is a very limited simulation of C++11's std::forward()
206// used by the Callback/Bind system for a set of movable-but-not-copyable
207// types. It is needed because forwarding a movable-but-not-copyable
208// argument to another function requires us to invoke the proper move
209// operator to create a rvalue version of the type. The supported types are
210// whitelisted below as overloads of the CallbackForward() function. The
211// default template compiles out to be a no-op.
212//
213// In C++11, std::forward would replace all uses of this function. However, it
214// is impossible to implement a general std::forward with C++11 due to a lack
215// of rvalue references.
rsleevi@chromium.org85c5f232012-05-04 07:34:17 +0900216//
217// In addition to Callback/Bind, this is used by PostTaskAndReplyWithResult to
218// simulate std::forward() and forward the result of one Callback as a
219// parameter to another callback. This is to support Callbacks that return
220// the movable-but-not-copyable types whitelisted above.
ajwong@chromium.orgf66a7db2011-12-23 06:12:58 +0900221template <typename T>
kinuko@chromium.org288f27a2013-10-22 18:18:20 +0900222typename enable_if<!IsMoveOnlyType<T>::value, T>::type& CallbackForward(T& t) {
223 return t;
willchan@chromium.org9be58392012-03-23 09:08:42 +0900224}
225
226template <typename T>
kinuko@chromium.org288f27a2013-10-22 18:18:20 +0900227typename enable_if<IsMoveOnlyType<T>::value, T>::type CallbackForward(T& t) {
228 return t.Pass();
229}
ajwong@chromium.orgf66a7db2011-12-23 06:12:58 +0900230
ajwong@chromium.orge2cca632011-02-15 10:27:38 +0900231} // namespace internal
232} // namespace base
233
ajwong@chromium.orgfa0ff432011-02-19 08:29:31 +0900234#endif // BASE_CALLBACK_INTERNAL_H_