@@ -2384,6 +2384,19 @@ private:
23842384 return __guess;
23852385 }
23862386
2387+ _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 size_type
2388+ __get_amortized_growth_capacity (size_type __required_capacity) {
2389+ size_type __max_size = max_size ();
2390+ if (__required_capacity > __max_size)
2391+ __throw_length_error ();
2392+ size_type __current_cap = capacity ();
2393+ _LIBCPP_ASSERT_INTERNAL (
2394+ __current_cap < __required_capacity, " Trying to grow string even though there is enough capacity already?" );
2395+ if (__current_cap > __max_size / 2 - __alignment)
2396+ return __max_size;
2397+ return std::max (__required_capacity, 2 * __current_cap);
2398+ }
2399+
23872400 inline _LIBCPP_CONSTEXPR_SINCE_CXX20 void __init (const value_type* __s, size_type __sz);
23882401 inline _LIBCPP_CONSTEXPR_SINCE_CXX20 void __init (size_type __n, value_type __c);
23892402
@@ -2714,14 +2727,10 @@ _LIBCPP_CONSTEXPR_SINCE_CXX20 void basic_string<_CharT, _Traits, _Allocator>::__
27142727 size_type __n_del,
27152728 size_type __n_add,
27162729 const value_type* __p_new_stuff) {
2717- size_type __ms = max_size ();
2718- if (__delta_cap > __ms - __old_cap)
2719- __throw_length_error ();
2730+ __long __buffer = __allocate_long_buffer (__alloc_, __get_amortized_growth_capacity (__old_cap + __delta_cap));
27202731 pointer __old_p = __get_pointer ();
2721- size_type __cap = __old_cap < __ms / 2 - __alignment ? std::max (__old_cap + __delta_cap, 2 * __old_cap) : __ms;
27222732 __annotate_delete ();
2723- auto __guard = std::__make_scope_guard (__annotate_new_size (*this ));
2724- __long __buffer = __allocate_long_buffer (__alloc_, __cap);
2733+ auto __guard = std::__make_scope_guard (__annotate_new_size (*this ));
27252734 if (__n_copy != 0 )
27262735 traits_type::copy (std::__to_address (__buffer.__data_ ), std::__to_address (__old_p), __n_copy);
27272736 if (__n_add != 0 )
@@ -2751,12 +2760,8 @@ _LIBCPP_DEPRECATED_("use __grow_by_without_replace") basic_string<_CharT, _Trait
27512760 size_type __n_copy,
27522761 size_type __n_del,
27532762 size_type __n_add) {
2754- size_type __ms = max_size ();
2755- if (__delta_cap > __ms - __old_cap)
2756- this ->__throw_length_error ();
2763+ __long __buffer = __allocate_long_buffer (__alloc_, __get_amortized_growth_capacity (__old_cap + __delta_cap));
27572764 pointer __old_p = __get_pointer ();
2758- size_type __cap = __old_cap < __ms / 2 - __alignment ? std::max (__old_cap + __delta_cap, 2 * __old_cap) : __ms;
2759- __long __buffer = __allocate_long_buffer (__alloc_, __cap);
27602765 if (__n_copy != 0 )
27612766 traits_type::copy (std::__to_address (__buffer.__data_ ), std::__to_address (__old_p), __n_copy);
27622767 size_type __sec_cp_sz = __old_sz - __n_del - __n_copy;
0 commit comments