scoped_generic.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. // Copyright 2014 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. #ifndef BASE_SCOPED_GENERIC_H_
  5. #define BASE_SCOPED_GENERIC_H_
  6. #include <stdlib.h>
  7. #include <ostream>
  8. #include <algorithm>
  9. #include "base/compiler_specific.h"
  10. #include "base/logging.h"
  11. #include "base/macros.h"
  12. namespace base {
  13. // This class acts like unique_ptr with a custom deleter (although is slightly
  14. // less fancy in some of the more escoteric respects) except that it keeps a
  15. // copy of the object rather than a pointer, and we require that the contained
  16. // object has some kind of "invalid" value.
  17. //
  18. // Defining a scoper based on this class allows you to get a scoper for
  19. // non-pointer types without having to write custom code for set, reset, and
  20. // move, etc. and get almost identical semantics that people are used to from
  21. // unique_ptr.
  22. //
  23. // It is intended that you will typedef this class with an appropriate deleter
  24. // to implement clean up tasks for objects that act like pointers from a
  25. // resource management standpoint but aren't, such as file descriptors and
  26. // various types of operating system handles. Using unique_ptr for these
  27. // things requires that you keep a pointer to the handle valid for the lifetime
  28. // of the scoper (which is easy to mess up).
  29. //
  30. // For an object to be able to be put into a ScopedGeneric, it must support
  31. // standard copyable semantics and have a specific "invalid" value. The traits
  32. // must define a free function and also the invalid value to assign for
  33. // default-constructed and released objects.
  34. //
  35. // struct FooScopedTraits {
  36. // // It's assumed that this is a fast inline function with little-to-no
  37. // // penalty for duplicate calls. This must be a static function even
  38. // // for stateful traits.
  39. // static int InvalidValue() {
  40. // return 0;
  41. // }
  42. //
  43. // // This free function will not be called if f == InvalidValue()!
  44. // static void Free(int f) {
  45. // ::FreeFoo(f);
  46. // }
  47. // };
  48. //
  49. // typedef ScopedGeneric<int, FooScopedTraits> ScopedFoo;
  50. //
  51. // A Traits type may choose to track ownership of objects in parallel with
  52. // ScopedGeneric. To do so, it must implement the Acquire and Release methods,
  53. // which will be called by ScopedGeneric during ownership transfers and extend
  54. // the ScopedGenericOwnershipTracking tag type.
  55. //
  56. // struct BarScopedTraits : public ScopedGenericOwnershipTracking {
  57. // using ScopedGenericType = ScopedGeneric<int, BarScopedTraits>;
  58. // static int InvalidValue() {
  59. // return 0;
  60. // }
  61. //
  62. // static void Free(int b) {
  63. // ::FreeBar(b);
  64. // }
  65. //
  66. // static void Acquire(const ScopedGenericType& owner, int b) {
  67. // ::TrackAcquisition(b, owner);
  68. // }
  69. //
  70. // static void Release(const ScopedGenericType& owner, int b) {
  71. // ::TrackRelease(b, owner);
  72. // }
  73. // };
  74. //
  75. // typedef ScopedGeneric<int, BarScopedTraits> ScopedBar;
  76. struct ScopedGenericOwnershipTracking {};
  77. template<typename T, typename Traits>
  78. class ScopedGeneric {
  79. private:
  80. // This must be first since it's used inline below.
  81. //
  82. // Use the empty base class optimization to allow us to have a D
  83. // member, while avoiding any space overhead for it when D is an
  84. // empty class. See e.g. http://www.cantrip.org/emptyopt.html for a good
  85. // discussion of this technique.
  86. struct Data : public Traits {
  87. explicit Data(const T& in) : generic(in) {}
  88. Data(const T& in, const Traits& other) : Traits(other), generic(in) {}
  89. T generic;
  90. };
  91. public:
  92. typedef T element_type;
  93. typedef Traits traits_type;
  94. ScopedGeneric() : data_(traits_type::InvalidValue()) {}
  95. // Constructor. Takes responsibility for freeing the resource associated with
  96. // the object T.
  97. explicit ScopedGeneric(const element_type& value) : data_(value) {
  98. TrackAcquire(data_.generic);
  99. }
  100. // Constructor. Allows initialization of a stateful traits object.
  101. ScopedGeneric(const element_type& value, const traits_type& traits)
  102. : data_(value, traits) {
  103. TrackAcquire(data_.generic);
  104. }
  105. // Move constructor. Allows initialization from a ScopedGeneric rvalue.
  106. ScopedGeneric(ScopedGeneric<T, Traits>&& rvalue)
  107. : data_(rvalue.release(), rvalue.get_traits()) {
  108. TrackAcquire(data_.generic);
  109. }
  110. virtual ~ScopedGeneric() {
  111. CHECK(!receiving_) << "ScopedGeneric destroyed with active receiver";
  112. FreeIfNecessary();
  113. }
  114. // operator=. Allows assignment from a ScopedGeneric rvalue.
  115. ScopedGeneric& operator=(ScopedGeneric<T, Traits>&& rvalue) {
  116. reset(rvalue.release());
  117. return *this;
  118. }
  119. // Frees the currently owned object, if any. Then takes ownership of a new
  120. // object, if given. Self-resets are not allowd as on unique_ptr. See
  121. // http://crbug.com/162971
  122. void reset(const element_type& value = traits_type::InvalidValue()) {
  123. if (data_.generic != traits_type::InvalidValue() && data_.generic == value)
  124. abort();
  125. FreeIfNecessary();
  126. data_.generic = value;
  127. TrackAcquire(value);
  128. }
  129. void swap(ScopedGeneric& other) {
  130. if (&other == this) {
  131. return;
  132. }
  133. TrackRelease(data_.generic);
  134. other.TrackRelease(other.data_.generic);
  135. // Standard swap idiom: 'using std::swap' ensures that std::swap is
  136. // present in the overload set, but we call swap unqualified so that
  137. // any more-specific overloads can be used, if available.
  138. using std::swap;
  139. swap(static_cast<Traits&>(data_), static_cast<Traits&>(other.data_));
  140. swap(data_.generic, other.data_.generic);
  141. TrackAcquire(data_.generic);
  142. other.TrackAcquire(other.data_.generic);
  143. }
  144. // Release the object. The return value is the current object held by this
  145. // object. After this operation, this object will hold a null value, and
  146. // will not own the object any more.
  147. element_type release() WARN_UNUSED_RESULT {
  148. element_type old_generic = data_.generic;
  149. data_.generic = traits_type::InvalidValue();
  150. TrackRelease(old_generic);
  151. return old_generic;
  152. }
  153. // A helper class that provides a T* that can be used to take ownership of
  154. // a value returned from a function via out-parameter. When the Receiver is
  155. // destructed (which should usually be at the end of the statement in which
  156. // receive is called), ScopedGeneric::reset() will be called with the
  157. // Receiver's value.
  158. //
  159. // In the simple case of a function that assigns the value before it returns,
  160. // C++'s lifetime extension can be used as follows:
  161. //
  162. // ScopedFoo foo;
  163. // bool result = GetFoo(ScopedFoo::Receiver(foo).get());
  164. //
  165. // Note that the lifetime of the Receiver is extended until the semicolon,
  166. // and ScopedGeneric is assigned the value upon destruction of the Receiver,
  167. // so the following code would not work:
  168. //
  169. // // BROKEN!
  170. // ScopedFoo foo;
  171. // UseFoo(&foo, GetFoo(ScopedFoo::Receiver(foo).get()));
  172. //
  173. // In more complicated scenarios, you may need to provide an explicit scope
  174. // for the Receiver, as in the following:
  175. //
  176. // std::vector<ScopedFoo> foos(64);
  177. //
  178. // {
  179. // std::vector<ScopedFoo::Receiver> foo_receivers;
  180. // for (auto foo : foos) {
  181. // foo_receivers_.emplace_back(foo);
  182. // }
  183. // for (auto receiver : foo_receivers) {
  184. // SubmitGetFooRequest(receiver.get());
  185. // }
  186. // WaitForFooRequests();
  187. // }
  188. // UseFoos(foos);
  189. class Receiver {
  190. public:
  191. explicit Receiver(ScopedGeneric& parent) : scoped_generic_(&parent) {
  192. CHECK(!scoped_generic_->receiving_)
  193. << "attempted to construct Receiver for ScopedGeneric with existing "
  194. "Receiver";
  195. scoped_generic_->receiving_ = true;
  196. }
  197. ~Receiver() {
  198. if (scoped_generic_) {
  199. CHECK(scoped_generic_->receiving_);
  200. scoped_generic_->reset(value_);
  201. scoped_generic_->receiving_ = false;
  202. }
  203. }
  204. Receiver(Receiver&& move) {
  205. CHECK(!used_) << "moving into already-used Receiver";
  206. CHECK(!move.used_) << "moving from already-used Receiver";
  207. scoped_generic_ = move.scoped_generic_;
  208. move.scoped_generic_ = nullptr;
  209. }
  210. Receiver& operator=(Receiver&& move) {
  211. CHECK(!used_) << "moving into already-used Receiver";
  212. CHECK(!move.used_) << "moving from already-used Receiver";
  213. scoped_generic_ = move.scoped_generic_;
  214. move.scoped_generic_ = nullptr;
  215. }
  216. // We hand out a pointer to a field in Receiver instead of directly to
  217. // ScopedGeneric's internal storage in order to make it so that users can't
  218. // accidentally silently break ScopedGeneric's invariants. This way, an
  219. // incorrect use-after-scope-exit is more detectable by ASan or static
  220. // analysis tools, as the pointer is only valid for the lifetime of the
  221. // Receiver, not the ScopedGeneric.
  222. T* get() {
  223. used_ = true;
  224. return &value_;
  225. }
  226. private:
  227. T value_ = Traits::InvalidValue();
  228. ScopedGeneric* scoped_generic_;
  229. bool used_ = false;
  230. DISALLOW_COPY_AND_ASSIGN(Receiver);
  231. };
  232. const element_type& get() const { return data_.generic; }
  233. // Returns true if this object doesn't hold the special null value for the
  234. // associated data type.
  235. bool is_valid() const { return data_.generic != traits_type::InvalidValue(); }
  236. bool operator==(const element_type& value) const {
  237. return data_.generic == value;
  238. }
  239. bool operator!=(const element_type& value) const {
  240. return data_.generic != value;
  241. }
  242. Traits& get_traits() { return data_; }
  243. const Traits& get_traits() const { return data_; }
  244. private:
  245. void FreeIfNecessary() {
  246. if (data_.generic != traits_type::InvalidValue()) {
  247. TrackRelease(data_.generic);
  248. data_.Free(data_.generic);
  249. data_.generic = traits_type::InvalidValue();
  250. }
  251. }
  252. template <typename Void = void>
  253. typename std::enable_if_t<
  254. std::is_base_of<ScopedGenericOwnershipTracking, Traits>::value,
  255. Void>
  256. TrackAcquire(const T& value) {
  257. if (value != traits_type::InvalidValue()) {
  258. data_.Acquire(static_cast<const ScopedGeneric&>(*this), value);
  259. }
  260. }
  261. template <typename Void = void>
  262. typename std::enable_if_t<
  263. !std::is_base_of<ScopedGenericOwnershipTracking, Traits>::value,
  264. Void>
  265. TrackAcquire(const T& value) {}
  266. template <typename Void = void>
  267. typename std::enable_if_t<
  268. std::is_base_of<ScopedGenericOwnershipTracking, Traits>::value,
  269. Void>
  270. TrackRelease(const T& value) {
  271. if (value != traits_type::InvalidValue()) {
  272. data_.Release(static_cast<const ScopedGeneric&>(*this), value);
  273. }
  274. }
  275. template <typename Void = void>
  276. typename std::enable_if_t<
  277. !std::is_base_of<ScopedGenericOwnershipTracking, Traits>::value,
  278. Void>
  279. TrackRelease(const T& value) {}
  280. // Forbid comparison. If U != T, it totally doesn't make sense, and if U ==
  281. // T, it still doesn't make sense because you should never have the same
  282. // object owned by two different ScopedGenerics.
  283. template <typename T2, typename Traits2> bool operator==(
  284. const ScopedGeneric<T2, Traits2>& p2) const;
  285. template <typename T2, typename Traits2> bool operator!=(
  286. const ScopedGeneric<T2, Traits2>& p2) const;
  287. Data data_;
  288. bool receiving_ = false;
  289. DISALLOW_COPY_AND_ASSIGN(ScopedGeneric);
  290. };
  291. template<class T, class Traits>
  292. void swap(const ScopedGeneric<T, Traits>& a,
  293. const ScopedGeneric<T, Traits>& b) {
  294. a.swap(b);
  295. }
  296. template<class T, class Traits>
  297. bool operator==(const T& value, const ScopedGeneric<T, Traits>& scoped) {
  298. return value == scoped.get();
  299. }
  300. template<class T, class Traits>
  301. bool operator!=(const T& value, const ScopedGeneric<T, Traits>& scoped) {
  302. return value != scoped.get();
  303. }
  304. } // namespace base
  305. #endif // BASE_SCOPED_GENERIC_H_