basic_any.hpp 23 KB

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