[libcxx-commits] [libcxx] [libc++][format] Discard contents since null-terminator in character arrays in formatting (PR #116571)

Louis Dionne via libcxx-commits libcxx-commits at lists.llvm.org
Thu Nov 28 12:02:48 PST 2024


================
@@ -189,14 +197,16 @@ _LIBCPP_HIDE_FROM_ABI basic_format_arg<_Context> __create_format_arg(_Tp& __valu
     return basic_format_arg<_Context>{__arg, static_cast<unsigned long long>(__value)};
   else if constexpr (__arg == __arg_t::__string_view)
     // Using std::size on a character array will add the NUL-terminator to the size.
-    if constexpr (is_array_v<_Dp>)
-      return basic_format_arg<_Context>{
-          __arg, basic_string_view<typename _Context::char_type>{__value, extent_v<_Dp> - 1}};
-    else
-      // When the _Traits or _Allocator are different an implicit conversion will
-      // fail.
-      return basic_format_arg<_Context>{
-          __arg, basic_string_view<typename _Context::char_type>{__value.data(), __value.size()}};
+    if constexpr (__is_bounded_array_of<_Dp, __context_char_type>) {
+      if (const auto __pzero = char_traits<__context_char_type>::find(__value, extent_v<_Dp>, __context_char_type{}))
+        return basic_format_arg<_Context>{
+            __arg, basic_string_view<__context_char_type>{__value, static_cast<size_t>(__pzero - __value)}};
+      else
+        // The behavior is undefined in this case.
+        return basic_format_arg<_Context>{__arg, basic_string_view<__context_char_type>{__value, extent_v<_Dp>}};
+    } else
----------------
ldionne wrote:

I would add braces here since there's a lot of nested `if-else`s around.

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


More information about the libcxx-commits mailing list