File indexing completed on 2026-05-03 08:13:57
0001
0002
0003
0004
0005
0006
0007
0008
0009
0010 #ifndef _LIBCPP___MEMORY_UNIQUE_TEMPORARY_BUFFER_H
0011 #define _LIBCPP___MEMORY_UNIQUE_TEMPORARY_BUFFER_H
0012
0013 #include <__assert>
0014 #include <__config>
0015
0016 #include <__cstddef/ptrdiff_t.h>
0017 #include <__memory/allocator.h>
0018 #include <__memory/unique_ptr.h>
0019 #include <__new/allocate.h>
0020 #include <__new/global_new_delete.h>
0021 #include <__type_traits/is_constant_evaluated.h>
0022
0023 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
0024 # pragma GCC system_header
0025 #endif
0026
0027 _LIBCPP_BEGIN_NAMESPACE_STD
0028
0029 template <class _Tp>
0030 struct __temporary_buffer_deleter {
0031 ptrdiff_t __count_;
0032
0033 _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR __temporary_buffer_deleter() _NOEXCEPT : __count_(0) {}
0034 _LIBCPP_HIDE_FROM_ABI
0035 _LIBCPP_CONSTEXPR explicit __temporary_buffer_deleter(ptrdiff_t __count) _NOEXCEPT : __count_(__count) {}
0036
0037 _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX23 void operator()(_Tp* __ptr) _NOEXCEPT {
0038 if (__libcpp_is_constant_evaluated()) {
0039 allocator<_Tp>().deallocate(__ptr, __count_);
0040 return;
0041 }
0042
0043 std::__libcpp_deallocate_unsized<_Tp>(__ptr);
0044 }
0045 };
0046
0047 template <class _Tp>
0048 using __unique_temporary_buffer _LIBCPP_NODEBUG = unique_ptr<_Tp, __temporary_buffer_deleter<_Tp> >;
0049
0050 template <class _Tp>
0051 inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_NO_CFI _LIBCPP_CONSTEXPR_SINCE_CXX23 __unique_temporary_buffer<_Tp>
0052 __allocate_unique_temporary_buffer(ptrdiff_t __count) {
0053 using __deleter_type = __temporary_buffer_deleter<_Tp>;
0054 using __unique_buffer_type = __unique_temporary_buffer<_Tp>;
0055
0056 if (__libcpp_is_constant_evaluated()) {
0057 return __unique_buffer_type(allocator<_Tp>().allocate(__count), __deleter_type(__count));
0058 }
0059
0060 _Tp* __ptr = nullptr;
0061 const ptrdiff_t __max_count =
0062 (~ptrdiff_t(0) ^ ptrdiff_t(ptrdiff_t(1) << (sizeof(ptrdiff_t) * __CHAR_BIT__ - 1))) / sizeof(_Tp);
0063 if (__count > __max_count)
0064 __count = __max_count;
0065 while (__count > 0) {
0066 #if _LIBCPP_HAS_ALIGNED_ALLOCATION
0067 if (__is_overaligned_for_new(_LIBCPP_ALIGNOF(_Tp))) {
0068 align_val_t __al = align_val_t(_LIBCPP_ALIGNOF(_Tp));
0069 __ptr = static_cast<_Tp*>(::operator new(__count * sizeof(_Tp), __al, nothrow));
0070 } else {
0071 __ptr = static_cast<_Tp*>(::operator new(__count * sizeof(_Tp), nothrow));
0072 }
0073 #else
0074 if (__is_overaligned_for_new(_LIBCPP_ALIGNOF(_Tp))) {
0075
0076 return __unique_buffer_type();
0077 }
0078
0079 __ptr = static_cast<_Tp*>(::operator new(__count * sizeof(_Tp), nothrow));
0080 #endif
0081
0082 if (__ptr) {
0083 break;
0084 }
0085 __count /= 2;
0086 }
0087
0088 return __unique_buffer_type(__ptr, __deleter_type(__count));
0089 }
0090
0091 _LIBCPP_END_NAMESPACE_STD
0092
0093 #endif