memory.h 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  1. // Copyright 2017 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //
  15. // -----------------------------------------------------------------------------
  16. // File: memory.h
  17. // -----------------------------------------------------------------------------
  18. //
  19. // This header file contains utility functions for managing the creation and
  20. // conversion of smart pointers. This file is an extension to the C++
  21. // standard <memory> library header file.
  22. #ifndef Y_ABSL_MEMORY_MEMORY_H_
  23. #define Y_ABSL_MEMORY_MEMORY_H_
  24. #include <cstddef>
  25. #include <limits>
  26. #include <memory>
  27. #include <new>
  28. #include <type_traits>
  29. #include <utility>
  30. #include "y_absl/base/macros.h"
  31. #include "y_absl/meta/type_traits.h"
  32. namespace y_absl {
  33. Y_ABSL_NAMESPACE_BEGIN
  34. // -----------------------------------------------------------------------------
  35. // Function Template: WrapUnique()
  36. // -----------------------------------------------------------------------------
  37. //
  38. // Adopts ownership from a raw pointer and transfers it to the returned
  39. // `std::unique_ptr`, whose type is deduced. Because of this deduction, *do not*
  40. // specify the template type `T` when calling `WrapUnique`.
  41. //
  42. // Example:
  43. // X* NewX(int, int);
  44. // auto x = WrapUnique(NewX(1, 2)); // 'x' is std::unique_ptr<X>.
  45. //
  46. // Do not call WrapUnique with an explicit type, as in
  47. // `WrapUnique<X>(NewX(1, 2))`. The purpose of WrapUnique is to automatically
  48. // deduce the pointer type. If you wish to make the type explicit, just use
  49. // `std::unique_ptr` directly.
  50. //
  51. // auto x = std::unique_ptr<X>(NewX(1, 2));
  52. // - or -
  53. // std::unique_ptr<X> x(NewX(1, 2));
  54. //
  55. // While `y_absl::WrapUnique` is useful for capturing the output of a raw
  56. // pointer factory, prefer 'y_absl::make_unique<T>(args...)' over
  57. // 'y_absl::WrapUnique(new T(args...))'.
  58. //
  59. // auto x = WrapUnique(new X(1, 2)); // works, but nonideal.
  60. // auto x = make_unique<X>(1, 2); // safer, standard, avoids raw 'new'.
  61. //
  62. // Note that `y_absl::WrapUnique(p)` is valid only if `delete p` is a valid
  63. // expression. In particular, `y_absl::WrapUnique()` cannot wrap pointers to
  64. // arrays, functions or void, and it must not be used to capture pointers
  65. // obtained from array-new expressions (even though that would compile!).
  66. template <typename T>
  67. std::unique_ptr<T> WrapUnique(T* ptr) {
  68. static_assert(!std::is_array<T>::value, "array types are unsupported");
  69. static_assert(std::is_object<T>::value, "non-object types are unsupported");
  70. return std::unique_ptr<T>(ptr);
  71. }
  72. namespace memory_internal {
  73. // Traits to select proper overload and return type for `y_absl::make_unique<>`.
  74. template <typename T>
  75. struct MakeUniqueResult {
  76. using scalar = std::unique_ptr<T>;
  77. };
  78. template <typename T>
  79. struct MakeUniqueResult<T[]> {
  80. using array = std::unique_ptr<T[]>;
  81. };
  82. template <typename T, size_t N>
  83. struct MakeUniqueResult<T[N]> {
  84. using invalid = void;
  85. };
  86. } // namespace memory_internal
  87. // gcc 4.8 has __cplusplus at 201301 but the libstdc++ shipped with it doesn't
  88. // define make_unique. Other supported compilers either just define __cplusplus
  89. // as 201103 but have make_unique (msvc), or have make_unique whenever
  90. // __cplusplus > 201103 (clang).
  91. #if defined(__cpp_lib_make_unique)
  92. using std::make_unique;
  93. #else
  94. // -----------------------------------------------------------------------------
  95. // Function Template: make_unique<T>()
  96. // -----------------------------------------------------------------------------
  97. //
  98. // Creates a `std::unique_ptr<>`, while avoiding issues creating temporaries
  99. // during the construction process. `y_absl::make_unique<>` also avoids redundant
  100. // type declarations, by avoiding the need to explicitly use the `new` operator.
  101. //
  102. // This implementation of `y_absl::make_unique<>` is designed for C++11 code and
  103. // will be replaced in C++14 by the equivalent `std::make_unique<>` abstraction.
  104. // `y_absl::make_unique<>` is designed to be 100% compatible with
  105. // `std::make_unique<>` so that the eventual migration will involve a simple
  106. // rename operation.
  107. //
  108. // For more background on why `std::unique_ptr<T>(new T(a,b))` is problematic,
  109. // see Herb Sutter's explanation on
  110. // (Exception-Safe Function Calls)[https://herbsutter.com/gotw/_102/].
  111. // (In general, reviewers should treat `new T(a,b)` with scrutiny.)
  112. //
  113. // Example usage:
  114. //
  115. // auto p = make_unique<X>(args...); // 'p' is a std::unique_ptr<X>
  116. // auto pa = make_unique<X[]>(5); // 'pa' is a std::unique_ptr<X[]>
  117. //
  118. // Three overloads of `y_absl::make_unique` are required:
  119. //
  120. // - For non-array T:
  121. //
  122. // Allocates a T with `new T(std::forward<Args> args...)`,
  123. // forwarding all `args` to T's constructor.
  124. // Returns a `std::unique_ptr<T>` owning that object.
  125. //
  126. // - For an array of unknown bounds T[]:
  127. //
  128. // `y_absl::make_unique<>` will allocate an array T of type U[] with
  129. // `new U[n]()` and return a `std::unique_ptr<U[]>` owning that array.
  130. //
  131. // Note that 'U[n]()' is different from 'U[n]', and elements will be
  132. // value-initialized. Note as well that `std::unique_ptr` will perform its
  133. // own destruction of the array elements upon leaving scope, even though
  134. // the array [] does not have a default destructor.
  135. //
  136. // NOTE: an array of unknown bounds T[] may still be (and often will be)
  137. // initialized to have a size, and will still use this overload. E.g:
  138. //
  139. // auto my_array = y_absl::make_unique<int[]>(10);
  140. //
  141. // - For an array of known bounds T[N]:
  142. //
  143. // `y_absl::make_unique<>` is deleted (like with `std::make_unique<>`) as
  144. // this overload is not useful.
  145. //
  146. // NOTE: an array of known bounds T[N] is not considered a useful
  147. // construction, and may cause undefined behavior in templates. E.g:
  148. //
  149. // auto my_array = y_absl::make_unique<int[10]>();
  150. //
  151. // In those cases, of course, you can still use the overload above and
  152. // simply initialize it to its desired size:
  153. //
  154. // auto my_array = y_absl::make_unique<int[]>(10);
  155. // `y_absl::make_unique` overload for non-array types.
  156. template <typename T, typename... Args>
  157. typename memory_internal::MakeUniqueResult<T>::scalar make_unique(
  158. Args&&... args) {
  159. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  160. }
  161. // `y_absl::make_unique` overload for an array T[] of unknown bounds.
  162. // The array allocation needs to use the `new T[size]` form and cannot take
  163. // element constructor arguments. The `std::unique_ptr` will manage destructing
  164. // these array elements.
  165. template <typename T>
  166. typename memory_internal::MakeUniqueResult<T>::array make_unique(size_t n) {
  167. return std::unique_ptr<T>(new typename y_absl::remove_extent_t<T>[n]());
  168. }
  169. // `y_absl::make_unique` overload for an array T[N] of known bounds.
  170. // This construction will be rejected.
  171. template <typename T, typename... Args>
  172. typename memory_internal::MakeUniqueResult<T>::invalid make_unique(
  173. Args&&... /* args */) = delete;
  174. #endif
  175. // -----------------------------------------------------------------------------
  176. // Function Template: RawPtr()
  177. // -----------------------------------------------------------------------------
  178. //
  179. // Extracts the raw pointer from a pointer-like value `ptr`. `y_absl::RawPtr` is
  180. // useful within templates that need to handle a complement of raw pointers,
  181. // `std::nullptr_t`, and smart pointers.
  182. template <typename T>
  183. auto RawPtr(T&& ptr) -> decltype(std::addressof(*ptr)) {
  184. // ptr is a forwarding reference to support Ts with non-const operators.
  185. return (ptr != nullptr) ? std::addressof(*ptr) : nullptr;
  186. }
  187. inline std::nullptr_t RawPtr(std::nullptr_t) { return nullptr; }
  188. // -----------------------------------------------------------------------------
  189. // Function Template: ShareUniquePtr()
  190. // -----------------------------------------------------------------------------
  191. //
  192. // Adopts a `std::unique_ptr` rvalue and returns a `std::shared_ptr` of deduced
  193. // type. Ownership (if any) of the held value is transferred to the returned
  194. // shared pointer.
  195. //
  196. // Example:
  197. //
  198. // auto up = y_absl::make_unique<int>(10);
  199. // auto sp = y_absl::ShareUniquePtr(std::move(up)); // shared_ptr<int>
  200. // CHECK_EQ(*sp, 10);
  201. // CHECK(up == nullptr);
  202. //
  203. // Note that this conversion is correct even when T is an array type, and more
  204. // generally it works for *any* deleter of the `unique_ptr` (single-object
  205. // deleter, array deleter, or any custom deleter), since the deleter is adopted
  206. // by the shared pointer as well. The deleter is copied (unless it is a
  207. // reference).
  208. //
  209. // Implements the resolution of [LWG 2415](http://wg21.link/lwg2415), by which a
  210. // null shared pointer does not attempt to call the deleter.
  211. template <typename T, typename D>
  212. std::shared_ptr<T> ShareUniquePtr(std::unique_ptr<T, D>&& ptr) {
  213. return ptr ? std::shared_ptr<T>(std::move(ptr)) : std::shared_ptr<T>();
  214. }
  215. // -----------------------------------------------------------------------------
  216. // Function Template: WeakenPtr()
  217. // -----------------------------------------------------------------------------
  218. //
  219. // Creates a weak pointer associated with a given shared pointer. The returned
  220. // value is a `std::weak_ptr` of deduced type.
  221. //
  222. // Example:
  223. //
  224. // auto sp = std::make_shared<int>(10);
  225. // auto wp = y_absl::WeakenPtr(sp);
  226. // CHECK_EQ(sp.get(), wp.lock().get());
  227. // sp.reset();
  228. // CHECK(wp.lock() == nullptr);
  229. //
  230. template <typename T>
  231. std::weak_ptr<T> WeakenPtr(const std::shared_ptr<T>& ptr) {
  232. return std::weak_ptr<T>(ptr);
  233. }
  234. namespace memory_internal {
  235. // ExtractOr<E, O, D>::type evaluates to E<O> if possible. Otherwise, D.
  236. template <template <typename> class Extract, typename Obj, typename Default,
  237. typename>
  238. struct ExtractOr {
  239. using type = Default;
  240. };
  241. template <template <typename> class Extract, typename Obj, typename Default>
  242. struct ExtractOr<Extract, Obj, Default, void_t<Extract<Obj>>> {
  243. using type = Extract<Obj>;
  244. };
  245. template <template <typename> class Extract, typename Obj, typename Default>
  246. using ExtractOrT = typename ExtractOr<Extract, Obj, Default, void>::type;
  247. // Extractors for the features of allocators.
  248. template <typename T>
  249. using GetPointer = typename T::pointer;
  250. template <typename T>
  251. using GetConstPointer = typename T::const_pointer;
  252. template <typename T>
  253. using GetVoidPointer = typename T::void_pointer;
  254. template <typename T>
  255. using GetConstVoidPointer = typename T::const_void_pointer;
  256. template <typename T>
  257. using GetDifferenceType = typename T::difference_type;
  258. template <typename T>
  259. using GetSizeType = typename T::size_type;
  260. template <typename T>
  261. using GetPropagateOnContainerCopyAssignment =
  262. typename T::propagate_on_container_copy_assignment;
  263. template <typename T>
  264. using GetPropagateOnContainerMoveAssignment =
  265. typename T::propagate_on_container_move_assignment;
  266. template <typename T>
  267. using GetPropagateOnContainerSwap = typename T::propagate_on_container_swap;
  268. template <typename T>
  269. using GetIsAlwaysEqual = typename T::is_always_equal;
  270. template <typename T>
  271. struct GetFirstArg;
  272. template <template <typename...> class Class, typename T, typename... Args>
  273. struct GetFirstArg<Class<T, Args...>> {
  274. using type = T;
  275. };
  276. template <typename Ptr, typename = void>
  277. struct ElementType {
  278. using type = typename GetFirstArg<Ptr>::type;
  279. };
  280. template <typename T>
  281. struct ElementType<T, void_t<typename T::element_type>> {
  282. using type = typename T::element_type;
  283. };
  284. template <typename T, typename U>
  285. struct RebindFirstArg;
  286. template <template <typename...> class Class, typename T, typename... Args,
  287. typename U>
  288. struct RebindFirstArg<Class<T, Args...>, U> {
  289. using type = Class<U, Args...>;
  290. };
  291. template <typename T, typename U, typename = void>
  292. struct RebindPtr {
  293. using type = typename RebindFirstArg<T, U>::type;
  294. };
  295. template <typename T, typename U>
  296. struct RebindPtr<T, U, void_t<typename T::template rebind<U>>> {
  297. using type = typename T::template rebind<U>;
  298. };
  299. template <typename T, typename U>
  300. constexpr bool HasRebindAlloc(...) {
  301. return false;
  302. }
  303. template <typename T, typename U>
  304. constexpr bool HasRebindAlloc(typename T::template rebind<U>::other*) {
  305. return true;
  306. }
  307. template <typename T, typename U, bool = HasRebindAlloc<T, U>(nullptr)>
  308. struct RebindAlloc {
  309. using type = typename RebindFirstArg<T, U>::type;
  310. };
  311. template <typename T, typename U>
  312. struct RebindAlloc<T, U, true> {
  313. using type = typename T::template rebind<U>::other;
  314. };
  315. } // namespace memory_internal
  316. // -----------------------------------------------------------------------------
  317. // Class Template: pointer_traits
  318. // -----------------------------------------------------------------------------
  319. //
  320. // An implementation of C++11's std::pointer_traits.
  321. //
  322. // Provided for portability on toolchains that have a working C++11 compiler,
  323. // but the standard library is lacking in C++11 support. For example, some
  324. // version of the Android NDK.
  325. //
  326. template <typename Ptr>
  327. struct pointer_traits {
  328. using pointer = Ptr;
  329. // element_type:
  330. // Ptr::element_type if present. Otherwise T if Ptr is a template
  331. // instantiation Template<T, Args...>
  332. using element_type = typename memory_internal::ElementType<Ptr>::type;
  333. // difference_type:
  334. // Ptr::difference_type if present, otherwise std::ptrdiff_t
  335. using difference_type =
  336. memory_internal::ExtractOrT<memory_internal::GetDifferenceType, Ptr,
  337. std::ptrdiff_t>;
  338. // rebind:
  339. // Ptr::rebind<U> if exists, otherwise Template<U, Args...> if Ptr is a
  340. // template instantiation Template<T, Args...>
  341. template <typename U>
  342. using rebind = typename memory_internal::RebindPtr<Ptr, U>::type;
  343. // pointer_to:
  344. // Calls Ptr::pointer_to(r)
  345. static pointer pointer_to(element_type& r) { // NOLINT(runtime/references)
  346. return Ptr::pointer_to(r);
  347. }
  348. };
  349. // Specialization for T*.
  350. template <typename T>
  351. struct pointer_traits<T*> {
  352. using pointer = T*;
  353. using element_type = T;
  354. using difference_type = std::ptrdiff_t;
  355. template <typename U>
  356. using rebind = U*;
  357. // pointer_to:
  358. // Calls std::addressof(r)
  359. static pointer pointer_to(
  360. element_type& r) noexcept { // NOLINT(runtime/references)
  361. return std::addressof(r);
  362. }
  363. };
  364. // -----------------------------------------------------------------------------
  365. // Class Template: allocator_traits
  366. // -----------------------------------------------------------------------------
  367. //
  368. // A C++11 compatible implementation of C++17's std::allocator_traits.
  369. //
  370. #if __cplusplus >= 201703L || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
  371. using std::allocator_traits;
  372. #else // __cplusplus >= 201703L
  373. template <typename Alloc>
  374. struct allocator_traits {
  375. using allocator_type = Alloc;
  376. // value_type:
  377. // Alloc::value_type
  378. using value_type = typename Alloc::value_type;
  379. // pointer:
  380. // Alloc::pointer if present, otherwise value_type*
  381. using pointer = memory_internal::ExtractOrT<memory_internal::GetPointer,
  382. Alloc, value_type*>;
  383. // const_pointer:
  384. // Alloc::const_pointer if present, otherwise
  385. // y_absl::pointer_traits<pointer>::rebind<const value_type>
  386. using const_pointer =
  387. memory_internal::ExtractOrT<memory_internal::GetConstPointer, Alloc,
  388. typename y_absl::pointer_traits<pointer>::
  389. template rebind<const value_type>>;
  390. // void_pointer:
  391. // Alloc::void_pointer if present, otherwise
  392. // y_absl::pointer_traits<pointer>::rebind<void>
  393. using void_pointer = memory_internal::ExtractOrT<
  394. memory_internal::GetVoidPointer, Alloc,
  395. typename y_absl::pointer_traits<pointer>::template rebind<void>>;
  396. // const_void_pointer:
  397. // Alloc::const_void_pointer if present, otherwise
  398. // y_absl::pointer_traits<pointer>::rebind<const void>
  399. using const_void_pointer = memory_internal::ExtractOrT<
  400. memory_internal::GetConstVoidPointer, Alloc,
  401. typename y_absl::pointer_traits<pointer>::template rebind<const void>>;
  402. // difference_type:
  403. // Alloc::difference_type if present, otherwise
  404. // y_absl::pointer_traits<pointer>::difference_type
  405. using difference_type = memory_internal::ExtractOrT<
  406. memory_internal::GetDifferenceType, Alloc,
  407. typename y_absl::pointer_traits<pointer>::difference_type>;
  408. // size_type:
  409. // Alloc::size_type if present, otherwise
  410. // std::make_unsigned<difference_type>::type
  411. using size_type = memory_internal::ExtractOrT<
  412. memory_internal::GetSizeType, Alloc,
  413. typename std::make_unsigned<difference_type>::type>;
  414. // propagate_on_container_copy_assignment:
  415. // Alloc::propagate_on_container_copy_assignment if present, otherwise
  416. // std::false_type
  417. using propagate_on_container_copy_assignment = memory_internal::ExtractOrT<
  418. memory_internal::GetPropagateOnContainerCopyAssignment, Alloc,
  419. std::false_type>;
  420. // propagate_on_container_move_assignment:
  421. // Alloc::propagate_on_container_move_assignment if present, otherwise
  422. // std::false_type
  423. using propagate_on_container_move_assignment = memory_internal::ExtractOrT<
  424. memory_internal::GetPropagateOnContainerMoveAssignment, Alloc,
  425. std::false_type>;
  426. // propagate_on_container_swap:
  427. // Alloc::propagate_on_container_swap if present, otherwise std::false_type
  428. using propagate_on_container_swap =
  429. memory_internal::ExtractOrT<memory_internal::GetPropagateOnContainerSwap,
  430. Alloc, std::false_type>;
  431. // is_always_equal:
  432. // Alloc::is_always_equal if present, otherwise std::is_empty<Alloc>::type
  433. using is_always_equal =
  434. memory_internal::ExtractOrT<memory_internal::GetIsAlwaysEqual, Alloc,
  435. typename std::is_empty<Alloc>::type>;
  436. // rebind_alloc:
  437. // Alloc::rebind<T>::other if present, otherwise Alloc<T, Args> if this Alloc
  438. // is Alloc<U, Args>
  439. template <typename T>
  440. using rebind_alloc = typename memory_internal::RebindAlloc<Alloc, T>::type;
  441. // rebind_traits:
  442. // y_absl::allocator_traits<rebind_alloc<T>>
  443. template <typename T>
  444. using rebind_traits = y_absl::allocator_traits<rebind_alloc<T>>;
  445. // allocate(Alloc& a, size_type n):
  446. // Calls a.allocate(n)
  447. static pointer allocate(Alloc& a, // NOLINT(runtime/references)
  448. size_type n) {
  449. return a.allocate(n);
  450. }
  451. // allocate(Alloc& a, size_type n, const_void_pointer hint):
  452. // Calls a.allocate(n, hint) if possible.
  453. // If not possible, calls a.allocate(n)
  454. static pointer allocate(Alloc& a, size_type n, // NOLINT(runtime/references)
  455. const_void_pointer hint) {
  456. return allocate_impl(0, a, n, hint);
  457. }
  458. // deallocate(Alloc& a, pointer p, size_type n):
  459. // Calls a.deallocate(p, n)
  460. static void deallocate(Alloc& a, pointer p, // NOLINT(runtime/references)
  461. size_type n) {
  462. a.deallocate(p, n);
  463. }
  464. // construct(Alloc& a, T* p, Args&&... args):
  465. // Calls a.construct(p, std::forward<Args>(args)...) if possible.
  466. // If not possible, calls
  467. // ::new (static_cast<void*>(p)) T(std::forward<Args>(args)...)
  468. template <typename T, typename... Args>
  469. static void construct(Alloc& a, T* p, // NOLINT(runtime/references)
  470. Args&&... args) {
  471. construct_impl(0, a, p, std::forward<Args>(args)...);
  472. }
  473. // destroy(Alloc& a, T* p):
  474. // Calls a.destroy(p) if possible. If not possible, calls p->~T().
  475. template <typename T>
  476. static void destroy(Alloc& a, T* p) { // NOLINT(runtime/references)
  477. destroy_impl(0, a, p);
  478. }
  479. // max_size(const Alloc& a):
  480. // Returns a.max_size() if possible. If not possible, returns
  481. // std::numeric_limits<size_type>::max() / sizeof(value_type)
  482. static size_type max_size(const Alloc& a) { return max_size_impl(0, a); }
  483. // select_on_container_copy_construction(const Alloc& a):
  484. // Returns a.select_on_container_copy_construction() if possible.
  485. // If not possible, returns a.
  486. static Alloc select_on_container_copy_construction(const Alloc& a) {
  487. return select_on_container_copy_construction_impl(0, a);
  488. }
  489. private:
  490. template <typename A>
  491. static auto allocate_impl(int, A& a, // NOLINT(runtime/references)
  492. size_type n, const_void_pointer hint)
  493. -> decltype(a.allocate(n, hint)) {
  494. return a.allocate(n, hint);
  495. }
  496. static pointer allocate_impl(char, Alloc& a, // NOLINT(runtime/references)
  497. size_type n, const_void_pointer) {
  498. return a.allocate(n);
  499. }
  500. template <typename A, typename... Args>
  501. static auto construct_impl(int, A& a, // NOLINT(runtime/references)
  502. Args&&... args)
  503. -> decltype(a.construct(std::forward<Args>(args)...)) {
  504. a.construct(std::forward<Args>(args)...);
  505. }
  506. template <typename T, typename... Args>
  507. static void construct_impl(char, Alloc&, T* p, Args&&... args) {
  508. ::new (static_cast<void*>(p)) T(std::forward<Args>(args)...);
  509. }
  510. template <typename A, typename T>
  511. static auto destroy_impl(int, A& a, // NOLINT(runtime/references)
  512. T* p) -> decltype(a.destroy(p)) {
  513. a.destroy(p);
  514. }
  515. template <typename T>
  516. static void destroy_impl(char, Alloc&, T* p) {
  517. p->~T();
  518. }
  519. template <typename A>
  520. static auto max_size_impl(int, const A& a) -> decltype(a.max_size()) {
  521. return a.max_size();
  522. }
  523. static size_type max_size_impl(char, const Alloc&) {
  524. return (std::numeric_limits<size_type>::max)() / sizeof(value_type);
  525. }
  526. template <typename A>
  527. static auto select_on_container_copy_construction_impl(int, const A& a)
  528. -> decltype(a.select_on_container_copy_construction()) {
  529. return a.select_on_container_copy_construction();
  530. }
  531. static Alloc select_on_container_copy_construction_impl(char,
  532. const Alloc& a) {
  533. return a;
  534. }
  535. };
  536. #endif // __cplusplus >= 201703L
  537. namespace memory_internal {
  538. // This template alias transforms Alloc::is_nothrow into a metafunction with
  539. // Alloc as a parameter so it can be used with ExtractOrT<>.
  540. template <typename Alloc>
  541. using GetIsNothrow = typename Alloc::is_nothrow;
  542. } // namespace memory_internal
  543. // Y_ABSL_ALLOCATOR_NOTHROW is a build time configuration macro for user to
  544. // specify whether the default allocation function can throw or never throws.
  545. // If the allocation function never throws, user should define it to a non-zero
  546. // value (e.g. via `-DABSL_ALLOCATOR_NOTHROW`).
  547. // If the allocation function can throw, user should leave it undefined or
  548. // define it to zero.
  549. //
  550. // allocator_is_nothrow<Alloc> is a traits class that derives from
  551. // Alloc::is_nothrow if present, otherwise std::false_type. It's specialized
  552. // for Alloc = std::allocator<T> for any type T according to the state of
  553. // Y_ABSL_ALLOCATOR_NOTHROW.
  554. //
  555. // default_allocator_is_nothrow is a class that derives from std::true_type
  556. // when the default allocator (global operator new) never throws, and
  557. // std::false_type when it can throw. It is a convenience shorthand for writing
  558. // allocator_is_nothrow<std::allocator<T>> (T can be any type).
  559. // NOTE: allocator_is_nothrow<std::allocator<T>> is guaranteed to derive from
  560. // the same type for all T, because users should specialize neither
  561. // allocator_is_nothrow nor std::allocator.
  562. template <typename Alloc>
  563. struct allocator_is_nothrow
  564. : memory_internal::ExtractOrT<memory_internal::GetIsNothrow, Alloc,
  565. std::false_type> {};
  566. #if defined(Y_ABSL_ALLOCATOR_NOTHROW) && Y_ABSL_ALLOCATOR_NOTHROW
  567. template <typename T>
  568. struct allocator_is_nothrow<std::allocator<T>> : std::true_type {};
  569. struct default_allocator_is_nothrow : std::true_type {};
  570. #else
  571. struct default_allocator_is_nothrow : std::false_type {};
  572. #endif
  573. namespace memory_internal {
  574. template <typename Allocator, typename Iterator, typename... Args>
  575. void ConstructRange(Allocator& alloc, Iterator first, Iterator last,
  576. const Args&... args) {
  577. for (Iterator cur = first; cur != last; ++cur) {
  578. Y_ABSL_INTERNAL_TRY {
  579. std::allocator_traits<Allocator>::construct(alloc, std::addressof(*cur),
  580. args...);
  581. }
  582. Y_ABSL_INTERNAL_CATCH_ANY {
  583. while (cur != first) {
  584. --cur;
  585. std::allocator_traits<Allocator>::destroy(alloc, std::addressof(*cur));
  586. }
  587. Y_ABSL_INTERNAL_RETHROW;
  588. }
  589. }
  590. }
  591. template <typename Allocator, typename Iterator, typename InputIterator>
  592. void CopyRange(Allocator& alloc, Iterator destination, InputIterator first,
  593. InputIterator last) {
  594. for (Iterator cur = destination; first != last;
  595. static_cast<void>(++cur), static_cast<void>(++first)) {
  596. Y_ABSL_INTERNAL_TRY {
  597. std::allocator_traits<Allocator>::construct(alloc, std::addressof(*cur),
  598. *first);
  599. }
  600. Y_ABSL_INTERNAL_CATCH_ANY {
  601. while (cur != destination) {
  602. --cur;
  603. std::allocator_traits<Allocator>::destroy(alloc, std::addressof(*cur));
  604. }
  605. Y_ABSL_INTERNAL_RETHROW;
  606. }
  607. }
  608. }
  609. } // namespace memory_internal
  610. Y_ABSL_NAMESPACE_END
  611. } // namespace y_absl
  612. #endif // Y_ABSL_MEMORY_MEMORY_H_