Fix fmt function to handle null pointers and return empty string

This commit is contained in:
mutouyun 2025-01-11 18:39:07 +08:00 committed by 木头云
parent d0bd85a2c0
commit 6fcb40d117
2 changed files with 7 additions and 5 deletions

View File

@ -221,9 +221,12 @@ bool to_string(fmt_context &ctx, std::string const &a) noexcept {
}
bool to_string(fmt_context &ctx, char const *a, span<char const> fstr) noexcept {
if (a == nullptr) return false;
if (a == nullptr) {
return ipc::sprintf(ctx, fmt_of, fstr, "s", "");
} else {
return ipc::sprintf(ctx, fmt_of, fstr, "s", a);
}
}
bool to_string(fmt_context &ctx, char a) noexcept {
return ipc::sprintf(ctx, fmt_of, {}, "c", a);

View File

@ -112,11 +112,10 @@ TEST(fmt, fmt) {
EXPECT_EQ(s, test);
EXPECT_EQ(ipc::fmt("", 1, "", '2', "", 3.0), "123.000000");
char const * nc = nullptr;
EXPECT_EQ(ipc::fmt(nc, 1, "", '2', "", 3.0), "123.000000");
std::string empty;
EXPECT_EQ(ipc::fmt(empty, 1, "", '2', "", 3.0), "123.000000");
EXPECT_EQ(ipc::fmt(empty, 1, empty, '2', "", 3.0), "123.000000");
EXPECT_EQ(ipc::fmt("", 1, empty, '2', empty, 3.0), "123.000000");
EXPECT_EQ(ipc::fmt("", 1, "", '2', empty), "12");
}
namespace {