scoped_generic.h 11 KB

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