Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

std::bitset formatting (nested_formatter) does not work with wchar_t #4285

Closed
Boddlnagg opened this issue Jan 2, 2025 · 2 comments · Fixed by #4286
Closed

std::bitset formatting (nested_formatter) does not work with wchar_t #4285

Boddlnagg opened this issue Jan 2, 2025 · 2 comments · Fixed by #4286

Comments

@Boddlnagg
Copy link

I tried to test the formatting of std::bitset using fmt/std.h, but with wchar_t (and char16_t) instead of char, using this test:

TEST(std_test, format_bitset_Wide) {
  auto bs = std::bitset<6>(42);
  EXPECT_EQ(fmt::format(L"{}", bs), L"101010");
  EXPECT_EQ(fmt::format(L"{:0>8}", bs), L"00101010");
  EXPECT_EQ(fmt::format(L"{:-^12}", bs), L"---101010---");
}

It didn't compile until I applied the following changes to std.h:

--- a/include/fmt/std.h
+++ b/include/fmt/std.h
@@ -184,7 +184,7 @@ FMT_END_NAMESPACE
 FMT_BEGIN_NAMESPACE
 FMT_EXPORT
 template <std::size_t N, typename Char>
-struct formatter<std::bitset<N>, Char> : nested_formatter<string_view> {
+struct formatter<std::bitset<N>, Char> : nested_formatter<basic_string_view<Char>, Char> {
  private:
   // Functor because C++11 doesn't support generic lambdas.
   struct writer {
@@ -204,7 +204,7 @@ struct formatter<std::bitset<N>, Char> : nested_formatter<string_view> {
   template <typename FormatContext>
   auto format(const std::bitset<N>& bs, FormatContext& ctx) const
       -> decltype(ctx.out()) {
-    return write_padded(ctx, writer{bs});
+    return this->write_padded(ctx, writer{bs});
   }
 };

Now it runs into a segfault, which appears to be caused by the set_fill call in nested_formatter::write_padded:

    specs.set_fill(
        basic_string_view<Char>(specs_.fill<Char>(), specs_.fill_size()));

in combination with the implementation of fill() for non-char types returning a nullpointer:

  template <typename Char, FMT_ENABLE_IF(!std::is_same<Char, char>::value)>
  constexpr auto fill() const -> const Char* {
    return nullptr;
  }

How is this supposed to work (or rather, can it be made to work)?

@Boddlnagg Boddlnagg changed the title format_bitset (nested_formatter) does not work with wchar_t std::bitset formatting (nested_formatter) does not work with wchar_t Jan 2, 2025
@phprus
Copy link
Contributor

phprus commented Jan 2, 2025

@Boddlnagg
Please test PR #4286

@Boddlnagg
Copy link
Author

Yes, this seems to work 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants