scoped_generic.h 12 KB

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