Roll src/third_party/WebKit 6d85854:7e30d51 (svn 202247:202248)
[chromium-blink-merge.git] / base / callback_internal.h
blobb6353dc8e568449545d541f2dece3cabd2d55286
1 // Copyright (c) 2012 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.
5 // This file contains utility functions and classes that help the
6 // implementation, and management of the Callback objects.
8 #ifndef BASE_CALLBACK_INTERNAL_H_
9 #define BASE_CALLBACK_INTERNAL_H_
11 #include <stddef.h>
13 #include "base/atomic_ref_count.h"
14 #include "base/base_export.h"
15 #include "base/macros.h"
16 #include "base/memory/ref_counted.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "base/template_util.h"
20 namespace base {
21 namespace internal {
22 class CallbackBase;
24 // BindStateBase is used to provide an opaque handle that the Callback
25 // class can use to represent a function object with bound arguments. It
26 // behaves as an existential type that is used by a corresponding
27 // DoInvoke function to perform the function execution. This allows
28 // us to shield the Callback class from the types of the bound argument via
29 // "type erasure."
30 // At the base level, the only task is to add reference counting data. Don't use
31 // RefCountedThreadSafe since it requires the destructor to be a virtual method.
32 // Creating a vtable for every BindState template instantiation results in a lot
33 // of bloat. Its only task is to call the destructor which can be done with a
34 // function pointer.
35 class BindStateBase {
36 protected:
37 explicit BindStateBase(void (*destructor)(BindStateBase*))
38 : ref_count_(0), destructor_(destructor) {}
39 ~BindStateBase() = default;
41 private:
42 friend class scoped_refptr<BindStateBase>;
43 friend class CallbackBase;
45 void AddRef();
46 void Release();
48 AtomicRefCount ref_count_;
50 // Pointer to a function that will properly destroy |this|.
51 void (*destructor_)(BindStateBase*);
53 DISALLOW_COPY_AND_ASSIGN(BindStateBase);
56 // Holds the Callback methods that don't require specialization to reduce
57 // template bloat.
58 class BASE_EXPORT CallbackBase {
59 public:
60 CallbackBase(const CallbackBase& c);
61 CallbackBase& operator=(const CallbackBase& c);
63 // Returns true if Callback is null (doesn't refer to anything).
64 bool is_null() const { return bind_state_.get() == NULL; }
66 // Returns the Callback into an uninitialized state.
67 void Reset();
69 protected:
70 // In C++, it is safe to cast function pointers to function pointers of
71 // another type. It is not okay to use void*. We create a InvokeFuncStorage
72 // that that can store our function pointer, and then cast it back to
73 // the original type on usage.
74 typedef void(*InvokeFuncStorage)(void);
76 // Returns true if this callback equals |other|. |other| may be null.
77 bool Equals(const CallbackBase& other) const;
79 // Allow initializing of |bind_state_| via the constructor to avoid default
80 // initialization of the scoped_refptr. We do not also initialize
81 // |polymorphic_invoke_| here because doing a normal assignment in the
82 // derived Callback templates makes for much nicer compiler errors.
83 explicit CallbackBase(BindStateBase* bind_state);
85 // Force the destructor to be instantiated inside this translation unit so
86 // that our subclasses will not get inlined versions. Avoids more template
87 // bloat.
88 ~CallbackBase();
90 scoped_refptr<BindStateBase> bind_state_;
91 InvokeFuncStorage polymorphic_invoke_;
94 // A helper template to determine if given type is non-const move-only-type,
95 // i.e. if a value of the given type should be passed via .Pass() in a
96 // destructive way.
97 template <typename T> struct IsMoveOnlyType {
98 template <typename U>
99 static YesType Test(const typename U::MoveOnlyTypeForCPP03*);
101 template <typename U>
102 static NoType Test(...);
104 static const bool value = sizeof((Test<T>(0))) == sizeof(YesType) &&
105 !is_const<T>::value;
108 // Returns |Then| as SelectType::Type if |condition| is true. Otherwise returns
109 // |Else|.
110 template <bool condition, typename Then, typename Else>
111 struct SelectType {
112 typedef Then Type;
115 template <typename Then, typename Else>
116 struct SelectType<false, Then, Else> {
117 typedef Else Type;
120 template <typename>
121 struct CallbackParamTraitsForMoveOnlyType;
123 template <typename>
124 struct CallbackParamTraitsForNonMoveOnlyType;
126 // TODO(tzik): Use a default parameter once MSVS supports variadic templates
127 // with default values.
128 // http://connect.microsoft.com/VisualStudio/feedbackdetail/view/957801/compilation-error-with-variadic-templates
130 // This is a typetraits object that's used to take an argument type, and
131 // extract a suitable type for storing and forwarding arguments.
133 // In particular, it strips off references, and converts arrays to
134 // pointers for storage; and it avoids accidentally trying to create a
135 // "reference of a reference" if the argument is a reference type.
137 // This array type becomes an issue for storage because we are passing bound
138 // parameters by const reference. In this case, we end up passing an actual
139 // array type in the initializer list which C++ does not allow. This will
140 // break passing of C-string literals.
141 template <typename T>
142 struct CallbackParamTraits
143 : SelectType<IsMoveOnlyType<T>::value,
144 CallbackParamTraitsForMoveOnlyType<T>,
145 CallbackParamTraitsForNonMoveOnlyType<T> >::Type {
148 template <typename T>
149 struct CallbackParamTraitsForNonMoveOnlyType {
150 typedef const T& ForwardType;
151 typedef T StorageType;
154 // The Storage should almost be impossible to trigger unless someone manually
155 // specifies type of the bind parameters. However, in case they do,
156 // this will guard against us accidentally storing a reference parameter.
158 // The ForwardType should only be used for unbound arguments.
159 template <typename T>
160 struct CallbackParamTraitsForNonMoveOnlyType<T&> {
161 typedef T& ForwardType;
162 typedef T StorageType;
165 // Note that for array types, we implicitly add a const in the conversion. This
166 // means that it is not possible to bind array arguments to functions that take
167 // a non-const pointer. Trying to specialize the template based on a "const
168 // T[n]" does not seem to match correctly, so we are stuck with this
169 // restriction.
170 template <typename T, size_t n>
171 struct CallbackParamTraitsForNonMoveOnlyType<T[n]> {
172 typedef const T* ForwardType;
173 typedef const T* StorageType;
176 // See comment for CallbackParamTraits<T[n]>.
177 template <typename T>
178 struct CallbackParamTraitsForNonMoveOnlyType<T[]> {
179 typedef const T* ForwardType;
180 typedef const T* StorageType;
183 // Parameter traits for movable-but-not-copyable scopers.
185 // Callback<>/Bind() understands movable-but-not-copyable semantics where
186 // the type cannot be copied but can still have its state destructively
187 // transferred (aka. moved) to another instance of the same type by calling a
188 // helper function. When used with Bind(), this signifies transferal of the
189 // object's state to the target function.
191 // For these types, the ForwardType must not be a const reference, or a
192 // reference. A const reference is inappropriate, and would break const
193 // correctness, because we are implementing a destructive move. A non-const
194 // reference cannot be used with temporaries which means the result of a
195 // function or a cast would not be usable with Callback<> or Bind().
196 template <typename T>
197 struct CallbackParamTraitsForMoveOnlyType {
198 typedef T ForwardType;
199 typedef T StorageType;
202 // CallbackForward() is a very limited simulation of C++11's std::forward()
203 // used by the Callback/Bind system for a set of movable-but-not-copyable
204 // types. It is needed because forwarding a movable-but-not-copyable
205 // argument to another function requires us to invoke the proper move
206 // operator to create a rvalue version of the type. The supported types are
207 // whitelisted below as overloads of the CallbackForward() function. The
208 // default template compiles out to be a no-op.
210 // In C++11, std::forward would replace all uses of this function. However, it
211 // is impossible to implement a general std::forward with C++11 due to a lack
212 // of rvalue references.
214 // In addition to Callback/Bind, this is used by PostTaskAndReplyWithResult to
215 // simulate std::forward() and forward the result of one Callback as a
216 // parameter to another callback. This is to support Callbacks that return
217 // the movable-but-not-copyable types whitelisted above.
218 template <typename T>
219 typename enable_if<!IsMoveOnlyType<T>::value, T>::type& CallbackForward(T& t) {
220 return t;
223 template <typename T>
224 typename enable_if<IsMoveOnlyType<T>::value, T>::type CallbackForward(T& t) {
225 return t.Pass();
228 } // namespace internal
229 } // namespace base
231 #endif // BASE_CALLBACK_INTERNAL_H_