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. 4 5 // This file contains utility functions and classes that help the 6 // implementation, and management of the Callback objects. 7 8 #ifndef BASE_CALLBACK_INTERNAL_H_ 9 #define BASE_CALLBACK_INTERNAL_H_ 10 11 #include <stddef.h> 12 #include <map> 13 #include <memory> 14 #include <type_traits> 15 #include <vector> 16 17 #include "base/base_export.h" 18 #include "base/macros.h" 19 #include "base/memory/ref_counted.h" 20 #include "base/memory/scoped_ptr.h" 21 #include "base/template_util.h" 22 23 namespace base { 24 namespace internal { 25 class CallbackBase; 26 27 // BindStateBase is used to provide an opaque handle that the Callback 28 // 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." 33 // 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. 38 class BindStateBase { 39 protected: BindStateBase(void (* destructor)(BindStateBase *))40 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 std::atomic<int32_t> ref_count_; 52 53 // Pointer to a function that will properly destroy |this|. 54 void (*destructor_)(BindStateBase*); 55 56 DISALLOW_COPY_AND_ASSIGN(BindStateBase); 57 }; 58 59 // Holds the Callback methods that don't require specialization to reduce 60 // template bloat. 61 class BASE_EXPORT CallbackBase { 62 public: 63 CallbackBase(const CallbackBase& c); 64 CallbackBase& operator=(const CallbackBase& c); 65 66 // Returns true if Callback is null (doesn't refer to anything). is_null()67 bool is_null() const { return bind_state_.get() == NULL; } 68 69 // Returns the Callback into an uninitialized state. 70 void Reset(); 71 72 protected: 73 // 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 using InvokeFuncStorage = void(*)(); 78 79 // Returns true if this callback equals |other|. |other| may be null. 80 bool Equals(const CallbackBase& other) const; 81 82 // 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); 87 88 // Force the destructor to be instantiated inside this translation unit so 89 // that our subclasses will not get inlined versions. Avoids more template 90 // bloat. 91 ~CallbackBase(); 92 93 scoped_refptr<BindStateBase> bind_state_; 94 InvokeFuncStorage polymorphic_invoke_; 95 }; 96 97 // 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 std::move() in a 99 // destructive way. Types are considered to be move-only if they have a 100 // sentinel MoveOnlyTypeForCPP03 member: a class typically gets this from using 101 // the DISALLOW_COPY_AND_ASSIGN_WITH_MOVE_FOR_BIND macro. 102 // It would be easy to generalize this trait to all move-only types... but this 103 // confuses template deduction in VS2013 with certain types such as 104 // std::unique_ptr. 105 // TODO(dcheng): Revisit this when Windows switches to VS2015 by default. 106 template <typename T> struct IsMoveOnlyType { 107 template <typename U> 108 static YesType Test(const typename U::MoveOnlyTypeForCPP03*); 109 110 template <typename U> 111 static NoType Test(...); 112 113 static const bool value = sizeof((Test<T>(0))) == sizeof(YesType) && 114 !std::is_const<T>::value; 115 }; 116 117 // Specialization of IsMoveOnlyType so that std::unique_ptr is still considered 118 // move-only, even without the sentinel member. 119 template <typename T> 120 struct IsMoveOnlyType<std::unique_ptr<T>> : std::true_type {}; 121 122 template <typename> 123 struct CallbackParamTraitsForMoveOnlyType; 124 125 template <typename> 126 struct CallbackParamTraitsForNonMoveOnlyType; 127 128 // TODO(tzik): Use a default parameter once MSVS supports variadic templates 129 // with default values. 130 // http://connect.microsoft.com/VisualStudio/feedbackdetail/view/957801/compilation-error-with-variadic-templates 131 // 132 // This is a typetraits object that's used to take an argument type, and 133 // extract a suitable type for storing and forwarding arguments. 134 // 135 // In particular, it strips off references, and converts arrays to 136 // pointers for storage; and it avoids accidentally trying to create a 137 // "reference of a reference" if the argument is a reference type. 138 // 139 // This array type becomes an issue for storage because we are passing bound 140 // parameters by const reference. In this case, we end up passing an actual 141 // array type in the initializer list which C++ does not allow. This will 142 // break passing of C-string literals. 143 template <typename T> 144 struct CallbackParamTraits 145 : std::conditional<IsMoveOnlyType<T>::value, 146 CallbackParamTraitsForMoveOnlyType<T>, 147 CallbackParamTraitsForNonMoveOnlyType<T>>::type { 148 }; 149 150 template <typename T> 151 struct CallbackParamTraitsForNonMoveOnlyType { 152 using ForwardType = const T&; 153 using StorageType = T; 154 }; 155 156 // The Storage should almost be impossible to trigger unless someone manually 157 // specifies type of the bind parameters. However, in case they do, 158 // this will guard against us accidentally storing a reference parameter. 159 // 160 // The ForwardType should only be used for unbound arguments. 161 template <typename T> 162 struct CallbackParamTraitsForNonMoveOnlyType<T&> { 163 using ForwardType = T&; 164 using StorageType = T; 165 }; 166 167 // Note that for array types, we implicitly add a const in the conversion. This 168 // means that it is not possible to bind array arguments to functions that take 169 // a non-const pointer. Trying to specialize the template based on a "const 170 // T[n]" does not seem to match correctly, so we are stuck with this 171 // restriction. 172 template <typename T, size_t n> 173 struct CallbackParamTraitsForNonMoveOnlyType<T[n]> { 174 using ForwardType = const T*; 175 using StorageType = const T*; 176 }; 177 178 // See comment for CallbackParamTraits<T[n]>. 179 template <typename T> 180 struct CallbackParamTraitsForNonMoveOnlyType<T[]> { 181 using ForwardType = const T*; 182 using StorageType = const T*; 183 }; 184 185 // Parameter traits for movable-but-not-copyable scopers. 186 // 187 // Callback<>/Bind() understands movable-but-not-copyable semantics where 188 // the type cannot be copied but can still have its state destructively 189 // transferred (aka. moved) to another instance of the same type by calling a 190 // helper function. When used with Bind(), this signifies transferal of the 191 // object's state to the target function. 192 // 193 // For these types, the ForwardType must not be a const reference, or a 194 // reference. A const reference is inappropriate, and would break const 195 // correctness, because we are implementing a destructive move. A non-const 196 // reference cannot be used with temporaries which means the result of a 197 // function or a cast would not be usable with Callback<> or Bind(). 198 template <typename T> 199 struct CallbackParamTraitsForMoveOnlyType { 200 using ForwardType = T; 201 using StorageType = T; 202 }; 203 204 // CallbackForward() is a very limited simulation of C++11's std::forward() 205 // used by the Callback/Bind system for a set of movable-but-not-copyable 206 // types. It is needed because forwarding a movable-but-not-copyable 207 // argument to another function requires us to invoke the proper move 208 // operator to create a rvalue version of the type. The supported types are 209 // whitelisted below as overloads of the CallbackForward() function. The 210 // default template compiles out to be a no-op. 211 // 212 // In C++11, std::forward would replace all uses of this function. However, it 213 // is impossible to implement a general std::forward without C++11 due to a lack 214 // of rvalue references. 215 // 216 // In addition to Callback/Bind, this is used by PostTaskAndReplyWithResult to 217 // simulate std::forward() and forward the result of one Callback as a 218 // parameter to another callback. This is to support Callbacks that return 219 // the movable-but-not-copyable types whitelisted above. 220 template <typename T> 221 typename std::enable_if<!IsMoveOnlyType<T>::value, T>::type& CallbackForward( 222 T& t) { 223 return t; 224 } 225 226 template <typename T> 227 typename std::enable_if<IsMoveOnlyType<T>::value, T>::type CallbackForward( 228 T& t) { 229 return std::move(t); 230 } 231 232 } // namespace internal 233 } // namespace base 234 235 #endif // BASE_CALLBACK_INTERNAL_H_ 236