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

Louis Dionne via libcxx-commits libcxx-commits at lists.llvm.org
Wed May 14 09:59:28 PDT 2025


================
@@ -389,6 +395,22 @@ __bitset<_N_words, _Size>::to_ullong(true_type, true_type) const {
   return __r;
 }
 
+template <size_t _N_words, 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<_N_words, _Size>::__to_string(_CharT __zero, _CharT __one) const {
+  basic_string<_CharT, _Traits, _Allocator> __r(_Size, __zero);
+  for (size_t __i = 0, __bits = 0; __i < _N_words; ++__i, __bits += __bits_per_word) {
+    __storage_type __word = std::__invert_if<!_Spare>(__first_[__i]);
+    if (__i == _N_words - 1 && _Size - __bits < __bits_per_word)
+      __word &= (__storage_type(1) << (_Size - __bits)) - 1;
+    for (; __word; __word &= (__word - 1))
+      __r[_Size - 1 - (__bits + std::__countr_zero(__word))] = __one;
+  }
+
+  return __r;
+}
----------------
ldionne wrote:

Let's define this inline in the class, IMO that's a bit less confusing. Generally speaking we've been moving towards more inline definitions.

Also, let's make it protected since it's only used from the derived class `bitset`.

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


More information about the libcxx-commits mailing list