[libcxx-commits] [libcxx] [libc++] Refactor memory allocation in basic_string (PR #128423)

Louis Dionne via libcxx-commits libcxx-commits at lists.llvm.org
Wed Mar 26 08:33:28 PDT 2025


================
@@ -2144,6 +2119,58 @@ private:
     return __is_long() ? __get_long_pointer() : __get_short_pointer();
   }
 
+  _LIBCPP_HIDE_FROM_ABI static _LIBCPP_CONSTEXPR_SINCE_CXX20 __alloc_result
+  __allocate_long_buffer(_Allocator& __alloc, size_type __capacity) {
+    auto __buffer = std::__allocate_at_least(__alloc, __recommend(__capacity) + 1);
+
+    if (__libcpp_is_constant_evaluated()) {
+      for (size_type __i = 0; __i != __buffer.count; ++__i)
+        std::__construct_at(std::addressof(__buffer.ptr[__i]));
+    }
+
+    return __buffer;
+  }
+
+  _LIBCPP_HIDE_FROM_ABI static _LIBCPP_CONSTEXPR_SINCE_CXX20 void
+  __deallocate_long_buffer(_Allocator& __alloc, __alloc_result __allocation) {
+    __alloc_traits::deallocate(__alloc, __allocation.ptr, __allocation.count);
+  }
+
+  _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 void __reset_internal_buffer() {
+    __annotate_delete();
+    if (__is_long())
+      __deallocate_long_buffer(__alloc_, __get_internal_long_buffer());
+    __rep_.__s = __short();
+  }
+
+  _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 __alloc_result __get_internal_long_buffer() {
+    _LIBCPP_ASSERT_INTERNAL(__is_long(), "Trying to get buffer which doesn't exist!");
+    return __alloc_result(__get_long_pointer(), __get_long_cap());
+  }
+
+  _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 void
+  __replace_internal_buffer(__alloc_result __alloc, size_type __size) {
+    __reset_internal_buffer();
+    __rep_.__l = __long(__alloc, __size);
+  }
+
+  _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 pointer __init_internal_buffer(size_type __size) {
+    if (__libcpp_is_constant_evaluated())
+      __rep_ = __rep();
+
+    if (__size > max_size())
+      __throw_length_error();
+
+    if (__fits_in_sso(__size)) {
+      __set_short_size(__size);
+      __annotate_new(__size);
+      return __get_short_pointer();
+    }
----------------
ldionne wrote:

```suggestion
    } else { ... }
```

would be clearer IMO

https://github.com/llvm/llvm-project/pull/128423


More information about the libcxx-commits mailing list