[libcxx-commits] [libcxx] [libc++] Optimize bitset::to_string (PR #128832)

Nikolas Klauser via libcxx-commits libcxx-commits at lists.llvm.org
Wed Feb 26 06:59:34 PST 2025


================
@@ -529,6 +555,21 @@ inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX23 unsigned long long __
   return __first_;
 }
 
+template <size_t _Size>
+template <bool _Spare, class _CharT, class _Traits, class _Allocator>
+_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX23 basic_string<_CharT, _Traits, _Allocator>
+__bitset<1, _Size>::__to_string(_CharT __zero, _CharT __one) const {
+  basic_string<_CharT, _Traits, _Allocator> __r(_Size, __zero);
+  __storage_type __word = std::__invert_if<!_Spare>(__first_);
+  if (_Size < __bits_per_word)
+    __word &= (__storage_type(1) << _Size) - 1;
+  for (; __word; __word &= (__word - 1)) {
+    size_t __pos           = std::__countr_zero(__word);
+    __r[_Size - 1 - __pos] = __one;
----------------
philnik777 wrote:

```suggestion
    __r[_Size - 1 - __pos] = _Sparse ? __zero : __one;
```
I think this makes it clear that we select the `__zero` or `__one` character depending on the sparseness and not unconditionall.

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


More information about the libcxx-commits mailing list