Fix handling of null strings with the s specifier

This commit is contained in:
Victor Zverovich 2023-11-14 07:48:10 -10:00
parent 45e124ee43
commit 649fe0fc8b
2 changed files with 9 additions and 4 deletions

View File

@ -2342,9 +2342,10 @@ template <typename Char, typename OutputIt>
FMT_CONSTEXPR auto write(OutputIt out, const Char* s,
const format_specs<Char>& specs, locale_ref)
-> OutputIt {
return specs.type != presentation_type::pointer
? write(out, basic_string_view<Char>(s), specs, {})
: write_ptr<Char>(out, bit_cast<uintptr_t>(s), &specs);
if (specs.type == presentation_type::pointer)
return write_ptr<Char>(out, bit_cast<uintptr_t>(s), &specs);
if (!s) throw_format_error("string pointer is null");
return write(out, basic_string_view<Char>(s), specs, {});
}
template <typename Char, typename OutputIt, typename T,

View File

@ -1531,8 +1531,12 @@ TEST(format_test, format_cstring) {
EXPECT_EQ("test", fmt::format("{0:s}", "test"));
char nonconst[] = "nonconst";
EXPECT_EQ("nonconst", fmt::format("{0}", nonconst));
auto nullstr = static_cast<const char*>(nullptr);
EXPECT_THROW_MSG(
(void)fmt::format(runtime("{0}"), static_cast<const char*>(nullptr)),
(void)fmt::format("{}", nullstr),
format_error, "string pointer is null");
EXPECT_THROW_MSG(
(void)fmt::format("{:s}", nullstr),
format_error, "string pointer is null");
}