basic_any.hpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. // Copyright Ruslan Arutyunyan, 2019-2021.
  2. // Copyright Antony Polukhin, 2021-2024.
  3. //
  4. // Distributed under the Boost Software License, Version 1.0. (See
  5. // accompanying file LICENSE_1_0.txt or copy at
  6. // http://www.boost.org/LICENSE_1_0.txt)
  7. // Contributed by Ruslan Arutyunyan
  8. #ifndef BOOST_ANYS_BASIC_ANY_HPP_INCLUDED
  9. #define BOOST_ANYS_BASIC_ANY_HPP_INCLUDED
  10. #include <boost/config.hpp>
  11. #ifdef BOOST_HAS_PRAGMA_ONCE
  12. # pragma once
  13. #endif
  14. /// \file boost/any/basic_any.hpp
  15. /// \brief \copybrief boost::anys::basic_any
  16. #include <boost/any/bad_any_cast.hpp>
  17. #include <boost/any/fwd.hpp>
  18. #include <boost/assert.hpp>
  19. #include <boost/type_index.hpp>
  20. #include <boost/throw_exception.hpp>
  21. #include <memory> // for std::addressof
  22. #include <type_traits>
  23. namespace boost {
  24. namespace anys {
  25. /// \brief A class with customizable Small Object Optimization whose
  26. /// instances can hold instances of any type that satisfies
  27. /// \forcedlink{ValueType} requirements. Use boost::any instead if not sure.
  28. ///
  29. /// boost::anys::basic_any is the drop-in replacement for boost::any
  30. /// that provides control over Small Object Optimization via
  31. /// `OptimizeForSize` and `OptimizeForAlignment` template parameters.
  32. ///
  33. /// There are certain applications that require boost::any
  34. /// functionality, do know the typical/maximal size of the stored object and
  35. /// wish to avoid dynamic memory allocation overhead. For the convenience
  36. /// such applications may create a typedef for boost::anys::basic_any
  37. /// with the `OptimizeForSize` and `OptimizeForAlignment` template
  38. /// parameters set to typical/maximal size and alignment of types
  39. /// respectively. Memory allocation would be avoided for storing nothrow
  40. /// move constructible types with size and alignment less than or
  41. /// equal to the `OptimizeForSize` and `OptimizeForAlignment` values.
  42. ///
  43. /// Otherwise just use boost::any.
  44. template <std::size_t OptimizeForSize, std::size_t OptimizeForAlignment>
  45. class basic_any
  46. {
  47. static_assert(OptimizeForSize > 0 && OptimizeForAlignment > 0, "Size and Align shall be positive values");
  48. static_assert(OptimizeForSize >= OptimizeForAlignment, "Size shall non less than Align");
  49. static_assert((OptimizeForAlignment & (OptimizeForAlignment - 1)) == 0, "Align shall be a power of 2");
  50. static_assert(OptimizeForSize % OptimizeForAlignment == 0, "Size shall be multiple of alignment");
  51. private:
  52. /// @cond
  53. enum operation
  54. {
  55. Destroy,
  56. Move,
  57. Copy,
  58. AnyCast,
  59. UnsafeCast,
  60. Typeinfo
  61. };
  62. template <typename ValueType>
  63. static void* small_manager(operation op, basic_any& left, const basic_any* right, const boost::typeindex::type_info* info)
  64. {
  65. switch (op)
  66. {
  67. case Destroy:
  68. BOOST_ASSERT(!left.empty());
  69. reinterpret_cast<ValueType*>(&left.content.small_value)->~ValueType();
  70. break;
  71. case Move: {
  72. BOOST_ASSERT(left.empty());
  73. BOOST_ASSERT(right);
  74. BOOST_ASSERT(!right->empty());
  75. BOOST_ASSERT(right->type() == boost::typeindex::type_id<ValueType>());
  76. ValueType* value = reinterpret_cast<ValueType*>(&const_cast<basic_any*>(right)->content.small_value);
  77. new (&left.content.small_value) ValueType(std::move(*value));
  78. left.man = right->man;
  79. reinterpret_cast<ValueType const*>(&right->content.small_value)->~ValueType();
  80. const_cast<basic_any*>(right)->man = 0;
  81. };
  82. break;
  83. case Copy:
  84. BOOST_ASSERT(left.empty());
  85. BOOST_ASSERT(right);
  86. BOOST_ASSERT(!right->empty());
  87. BOOST_ASSERT(right->type() == boost::typeindex::type_id<ValueType>());
  88. new (&left.content.small_value) ValueType(*reinterpret_cast<const ValueType*>(&right->content.small_value));
  89. left.man = right->man;
  90. break;
  91. case AnyCast:
  92. BOOST_ASSERT(info);
  93. BOOST_ASSERT(!left.empty());
  94. return boost::typeindex::type_id<ValueType>() == *info ?
  95. reinterpret_cast<typename std::remove_cv<ValueType>::type *>(&left.content.small_value) : 0;
  96. case UnsafeCast:
  97. BOOST_ASSERT(!left.empty());
  98. return reinterpret_cast<typename std::remove_cv<ValueType>::type *>(&left.content.small_value);
  99. case Typeinfo:
  100. return const_cast<void*>(static_cast<const void*>(&boost::typeindex::type_id<ValueType>().type_info()));
  101. }
  102. return 0;
  103. }
  104. template <typename ValueType>
  105. static void* large_manager(operation op, basic_any& left, const basic_any* right, const boost::typeindex::type_info* info)
  106. {
  107. switch (op)
  108. {
  109. case Destroy:
  110. BOOST_ASSERT(!left.empty());
  111. delete static_cast<ValueType*>(left.content.large_value);
  112. break;
  113. case Move:
  114. BOOST_ASSERT(left.empty());
  115. BOOST_ASSERT(right);
  116. BOOST_ASSERT(!right->empty());
  117. BOOST_ASSERT(right->type() == boost::typeindex::type_id<ValueType>());
  118. left.content.large_value = right->content.large_value;
  119. left.man = right->man;
  120. const_cast<basic_any*>(right)->content.large_value = 0;
  121. const_cast<basic_any*>(right)->man = 0;
  122. break;
  123. case Copy:
  124. BOOST_ASSERT(left.empty());
  125. BOOST_ASSERT(right);
  126. BOOST_ASSERT(!right->empty());
  127. BOOST_ASSERT(right->type() == boost::typeindex::type_id<ValueType>());
  128. left.content.large_value = new ValueType(*static_cast<const ValueType*>(right->content.large_value));
  129. left.man = right->man;
  130. break;
  131. case AnyCast:
  132. BOOST_ASSERT(info);
  133. BOOST_ASSERT(!left.empty());
  134. return boost::typeindex::type_id<ValueType>() == *info ?
  135. static_cast<typename std::remove_cv<ValueType>::type *>(left.content.large_value) : 0;
  136. case UnsafeCast:
  137. BOOST_ASSERT(!left.empty());
  138. return reinterpret_cast<typename std::remove_cv<ValueType>::type *>(left.content.large_value);
  139. case Typeinfo:
  140. return const_cast<void*>(static_cast<const void*>(&boost::typeindex::type_id<ValueType>().type_info()));
  141. }
  142. return 0;
  143. }
  144. template <typename ValueType>
  145. struct is_small_object : std::integral_constant<bool, sizeof(ValueType) <= OptimizeForSize &&
  146. alignof(ValueType) <= OptimizeForAlignment &&
  147. std::is_nothrow_move_constructible<ValueType>::value>
  148. {};
  149. template <typename ValueType>
  150. static void create(basic_any& any, const ValueType& value, std::true_type)
  151. {
  152. typedef typename std::decay<const ValueType>::type DecayedType;
  153. any.man = &small_manager<DecayedType>;
  154. new (&any.content.small_value) ValueType(value);
  155. }
  156. template <typename ValueType>
  157. static void create(basic_any& any, const ValueType& value, std::false_type)
  158. {
  159. typedef typename std::decay<const ValueType>::type DecayedType;
  160. any.man = &large_manager<DecayedType>;
  161. any.content.large_value = new DecayedType(value);
  162. }
  163. template <typename ValueType>
  164. static void create(basic_any& any, ValueType&& value, std::true_type)
  165. {
  166. typedef typename std::decay<const ValueType>::type DecayedType;
  167. any.man = &small_manager<DecayedType>;
  168. new (&any.content.small_value) DecayedType(std::forward<ValueType>(value));
  169. }
  170. template <typename ValueType>
  171. static void create(basic_any& any, ValueType&& value, std::false_type)
  172. {
  173. typedef typename std::decay<const ValueType>::type DecayedType;
  174. any.man = &large_manager<DecayedType>;
  175. any.content.large_value = new DecayedType(std::forward<ValueType>(value));
  176. }
  177. /// @endcond
  178. public: // non-type template parameters accessors
  179. static constexpr std::size_t buffer_size = OptimizeForSize;
  180. static constexpr std::size_t buffer_align = OptimizeForAlignment;
  181. public: // structors
  182. /// \post this->empty() is true.
  183. constexpr basic_any() noexcept
  184. : man(0), content()
  185. {
  186. }
  187. /// Makes a copy of `value`, so
  188. /// that the initial content of the new instance is equivalent
  189. /// in both type and value to `value`.
  190. ///
  191. /// Does not dynamically allocate if `ValueType` is nothrow
  192. /// move constructible and `sizeof(value) <= OptimizeForSize` and
  193. /// `alignof(value) <= OptimizeForAlignment`.
  194. ///
  195. /// \throws std::bad_alloc or any exceptions arising from the copy
  196. /// constructor of the contained type.
  197. template<typename ValueType>
  198. basic_any(const ValueType & value)
  199. : man(0), content()
  200. {
  201. static_assert(
  202. !std::is_same<ValueType, boost::any>::value,
  203. "boost::anys::basic_any shall not be constructed from boost::any"
  204. );
  205. static_assert(
  206. !anys::detail::is_basic_any<ValueType>::value,
  207. "boost::anys::basic_any<A, B> shall not be constructed from boost::anys::basic_any<C, D>"
  208. );
  209. create(*this, value, is_small_object<ValueType>());
  210. }
  211. /// Copy constructor that copies content of
  212. /// `other` into new instance, so that any content
  213. /// is equivalent in both type and value to the content of
  214. /// `other`, or empty if `other` is empty.
  215. ///
  216. /// \throws May fail with a `std::bad_alloc`
  217. /// exception or any exceptions arising from the copy
  218. /// constructor of the contained type.
  219. basic_any(const basic_any & other)
  220. : man(0), content()
  221. {
  222. if (other.man)
  223. {
  224. other.man(Copy, *this, &other, 0);
  225. }
  226. }
  227. /// Move constructor that moves content of
  228. /// `other` into new instance and leaves `other` empty.
  229. ///
  230. /// \post other->empty() is true
  231. /// \throws Nothing.
  232. basic_any(basic_any&& other) noexcept
  233. : man(0), content()
  234. {
  235. if (other.man)
  236. {
  237. other.man(Move, *this, &other, 0);
  238. }
  239. }
  240. /// Forwards `value`, so
  241. /// that the initial content of the new instance is equivalent
  242. /// in both type and value to `value` before the forward.
  243. ///
  244. /// Does not dynamically allocate if `ValueType` is nothrow
  245. /// move constructible and `sizeof(value) <= OptimizeForSize` and
  246. /// `alignof(value) <= OptimizeForAlignment`.
  247. ///
  248. /// \throws std::bad_alloc or any exceptions arising from the move or
  249. /// copy constructor of the contained type.
  250. template<typename ValueType>
  251. basic_any(ValueType&& value
  252. , typename std::enable_if<!std::is_same<basic_any&, ValueType>::value >::type* = 0 // disable if value has type `basic_any&`
  253. , typename std::enable_if<!std::is_const<ValueType>::value >::type* = 0) // disable if value has type `const ValueType&&`
  254. : man(0), content()
  255. {
  256. typedef typename std::decay<ValueType>::type DecayedType;
  257. static_assert(
  258. !std::is_same<DecayedType, boost::any>::value,
  259. "boost::anys::basic_any shall not be constructed from boost::any"
  260. );
  261. static_assert(
  262. !anys::detail::is_basic_any<DecayedType>::value,
  263. "boost::anys::basic_any<A, B> shall not be constructed from boost::anys::basic_any<C, D>"
  264. );
  265. create(*this, static_cast<ValueType&&>(value), is_small_object<DecayedType>());
  266. }
  267. /// Releases any and all resources used in management of instance.
  268. ///
  269. /// \throws Nothing.
  270. ~basic_any() noexcept
  271. {
  272. if (man)
  273. {
  274. man(Destroy, *this, 0, 0);
  275. }
  276. }
  277. public: // modifiers
  278. /// Exchange of the contents of `*this` and `rhs`.
  279. ///
  280. /// \returns `*this`
  281. /// \throws Nothing.
  282. basic_any & swap(basic_any & rhs) noexcept
  283. {
  284. if (this == &rhs)
  285. {
  286. return *this;
  287. }
  288. if (man && rhs.man)
  289. {
  290. basic_any tmp;
  291. rhs.man(Move, tmp, &rhs, 0);
  292. man(Move, rhs, this, 0);
  293. tmp.man(Move, *this, &tmp, 0);
  294. }
  295. else if (man)
  296. {
  297. man(Move, rhs, this, 0);
  298. }
  299. else if (rhs.man)
  300. {
  301. rhs.man(Move, *this, &rhs, 0);
  302. }
  303. return *this;
  304. }
  305. /// Copies content of `rhs` into
  306. /// current instance, discarding previous content, so that the
  307. /// new content is equivalent in both type and value to the
  308. /// content of `rhs`, or empty if `rhs.empty()`.
  309. ///
  310. /// \throws std::bad_alloc
  311. /// or any exceptions arising from the copy constructor of the
  312. /// contained type. Assignment satisfies the strong guarantee
  313. /// of exception safety.
  314. basic_any & operator=(const basic_any& rhs)
  315. {
  316. basic_any(rhs).swap(*this);
  317. return *this;
  318. }
  319. /// Moves content of `rhs` into
  320. /// current instance, discarding previous content, so that the
  321. /// new content is equivalent in both type and value to the
  322. /// content of `rhs` before move, or empty if
  323. /// `rhs.empty()`.
  324. ///
  325. /// \post `rhs->empty()` is true
  326. /// \throws Nothing.
  327. basic_any & operator=(basic_any&& rhs) noexcept
  328. {
  329. rhs.swap(*this);
  330. basic_any().swap(rhs);
  331. return *this;
  332. }
  333. /// Forwards `rhs`,
  334. /// discarding previous content, so that the new content of is
  335. /// equivalent in both type and value to
  336. /// `rhs` before forward.
  337. ///
  338. /// Does not dynamically allocate if `ValueType` is nothrow
  339. /// move constructible and `sizeof(value) <= OptimizeForSize` and
  340. /// `alignof(value) <= OptimizeForAlignment`.
  341. ///
  342. /// \throws std::bad_alloc
  343. /// or any exceptions arising from the move or copy constructor of the
  344. /// contained type. Assignment satisfies the strong guarantee
  345. /// of exception safety.
  346. template <class ValueType>
  347. basic_any & operator=(ValueType&& rhs)
  348. {
  349. typedef typename std::decay<ValueType>::type DecayedType;
  350. static_assert(
  351. !std::is_same<DecayedType, boost::any>::value,
  352. "boost::any shall not be assigned into boost::anys::basic_any"
  353. );
  354. static_assert(
  355. !anys::detail::is_basic_any<DecayedType>::value || std::is_same<DecayedType, basic_any>::value,
  356. "boost::anys::basic_any<A, B> shall not be assigned into boost::anys::basic_any<C, D>"
  357. );
  358. basic_any(std::forward<ValueType>(rhs)).swap(*this);
  359. return *this;
  360. }
  361. public: // queries
  362. /// \returns `true` if instance is empty, otherwise `false`.
  363. /// \throws Nothing.
  364. bool empty() const noexcept
  365. {
  366. return !man;
  367. }
  368. /// \post this->empty() is true
  369. void clear() noexcept
  370. {
  371. basic_any().swap(*this);
  372. }
  373. /// \returns the `typeid` of the
  374. /// contained value if instance is non-empty, otherwise
  375. /// `typeid(void)`.
  376. ///
  377. /// Useful for querying against types known either at compile time or
  378. /// only at runtime.
  379. const boost::typeindex::type_info& type() const BOOST_NOEXCEPT
  380. {
  381. return man
  382. ? *static_cast<const boost::typeindex::type_info*>(man(Typeinfo, const_cast<basic_any&>(*this), 0, 0))
  383. : boost::typeindex::type_id<void>().type_info();
  384. }
  385. private: // representation
  386. /// @cond
  387. template<typename ValueType, std::size_t Size, std::size_t Alignment>
  388. friend ValueType * any_cast(basic_any<Size, Alignment> *) noexcept;
  389. template<typename ValueType, std::size_t Size, std::size_t Alignment>
  390. friend ValueType * unsafe_any_cast(basic_any<Size, Alignment> *) noexcept;
  391. typedef void*(*manager)(operation op, basic_any& left, const basic_any* right, const boost::typeindex::type_info* info);
  392. manager man;
  393. union content {
  394. void * large_value;
  395. alignas(OptimizeForAlignment) unsigned char small_value[OptimizeForSize];
  396. } content;
  397. /// @endcond
  398. };
  399. /// Exchange of the contents of `lhs` and `rhs`.
  400. /// \throws Nothing.
  401. template<std::size_t OptimizeForSize, std::size_t OptimizeForAlignment>
  402. void swap(basic_any<OptimizeForSize, OptimizeForAlignment>& lhs, basic_any<OptimizeForSize, OptimizeForAlignment>& rhs) noexcept
  403. {
  404. lhs.swap(rhs);
  405. }
  406. /// \returns Pointer to a ValueType stored in `operand`, nullptr if
  407. /// `operand` does not contain specified `ValueType`.
  408. template<typename ValueType, std::size_t Size, std::size_t Alignment>
  409. ValueType * any_cast(basic_any<Size, Alignment> * operand) noexcept
  410. {
  411. return operand->man ?
  412. static_cast<typename std::remove_cv<ValueType>::type *>(operand->man(basic_any<Size, Alignment>::AnyCast, *operand, 0, &boost::typeindex::type_id<ValueType>().type_info()))
  413. : 0;
  414. }
  415. /// \returns Const pointer to a ValueType stored in `operand`, nullptr if
  416. /// `operand` does not contain specified `ValueType`.
  417. template<typename ValueType, std::size_t OptimizeForSize, std::size_t OptimizeForAlignment>
  418. inline const ValueType * any_cast(const basic_any<OptimizeForSize, OptimizeForAlignment> * operand) noexcept
  419. {
  420. return boost::anys::any_cast<ValueType>(const_cast<basic_any<OptimizeForSize, OptimizeForAlignment> *>(operand));
  421. }
  422. /// \returns ValueType stored in `operand`
  423. /// \throws boost::bad_any_cast if `operand` does not contain
  424. /// specified ValueType.
  425. template<typename ValueType, std::size_t OptimizeForSize, std::size_t OptimizeForAlignment>
  426. ValueType any_cast(basic_any<OptimizeForSize, OptimizeForAlignment> & operand)
  427. {
  428. typedef typename std::remove_reference<ValueType>::type nonref;
  429. nonref * result = boost::anys::any_cast<nonref>(std::addressof(operand));
  430. if(!result)
  431. boost::throw_exception(bad_any_cast());
  432. // Attempt to avoid construction of a temporary object in cases when
  433. // `ValueType` is not a reference. Example:
  434. // `static_cast<std::string>(*result);`
  435. // which is equal to `std::string(*result);`
  436. typedef typename std::conditional<
  437. std::is_reference<ValueType>::value,
  438. ValueType,
  439. typename std::add_lvalue_reference<ValueType>::type
  440. >::type ref_type;
  441. #ifdef BOOST_MSVC
  442. # pragma warning(push)
  443. # pragma warning(disable: 4172) // "returning address of local variable or temporary" but *result is not local!
  444. #endif
  445. return static_cast<ref_type>(*result);
  446. #ifdef BOOST_MSVC
  447. # pragma warning(pop)
  448. #endif
  449. }
  450. /// \returns `ValueType` stored in `operand`
  451. /// \throws boost::bad_any_cast if `operand` does not contain
  452. /// specified `ValueType`.
  453. template<typename ValueType, std::size_t OptimizeForSize, std::size_t OptimizeForAlignment>
  454. inline ValueType any_cast(const basic_any<OptimizeForSize, OptimizeForAlignment> & operand)
  455. {
  456. typedef typename std::remove_reference<ValueType>::type nonref;
  457. return boost::anys::any_cast<const nonref &>(const_cast<basic_any<OptimizeForSize, OptimizeForAlignment> &>(operand));
  458. }
  459. /// \returns `ValueType` stored in `operand`, leaving the `operand` empty.
  460. /// \throws boost::bad_any_cast if `operand` does not contain
  461. /// specified `ValueType`.
  462. template<typename ValueType, std::size_t OptimizeForSize, std::size_t OptimizeForAlignment>
  463. inline ValueType any_cast(basic_any<OptimizeForSize, OptimizeForAlignment>&& operand)
  464. {
  465. static_assert(
  466. std::is_rvalue_reference<ValueType&&>::value /*true if ValueType is rvalue or just a value*/
  467. || std::is_const< typename std::remove_reference<ValueType>::type >::value,
  468. "boost::any_cast shall not be used for getting nonconst references to temporary objects"
  469. );
  470. return boost::anys::any_cast<ValueType>(operand);
  471. }
  472. /// @cond
  473. // Note: The "unsafe" versions of any_cast are not part of the
  474. // public interface and may be removed at any time. They are
  475. // required where we know what type is stored in the any and can't
  476. // use typeid() comparison, e.g., when our types may travel across
  477. // different shared libraries.
  478. template<typename ValueType, std::size_t OptimizedForSize, std::size_t OptimizeForAlignment>
  479. inline ValueType * unsafe_any_cast(basic_any<OptimizedForSize, OptimizeForAlignment> * operand) noexcept
  480. {
  481. return static_cast<ValueType*>(operand->man(basic_any<OptimizedForSize, OptimizeForAlignment>::UnsafeCast, *operand, 0, 0));
  482. }
  483. template<typename ValueType, std::size_t OptimizeForSize, std::size_t OptimizeForAlignment>
  484. inline const ValueType * unsafe_any_cast(const basic_any<OptimizeForSize, OptimizeForAlignment> * operand) noexcept
  485. {
  486. return boost::anys::unsafe_any_cast<ValueType>(const_cast<basic_any<OptimizeForSize, OptimizeForAlignment> *>(operand));
  487. }
  488. /// @endcond
  489. } // namespace anys
  490. using boost::anys::any_cast;
  491. using boost::anys::unsafe_any_cast;
  492. } // namespace boost
  493. #endif // #ifndef BOOST_ANYS_BASIC_ANY_HPP_INCLUDED