Fix signs in floating-point duration formatting (#4981)

This commit is contained in:
Mohith 2026-10-24 22:58:23 +05:30 committed by GitHub
parent a8293b774e
commit 434e30f81f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 32 additions and 5 deletions

View File

@ -1687,10 +1687,8 @@ struct duration_formatter {
return true;
}
// must be +-inf
if (val > 0)
std::copy_n("inf", 3, out);
else
std::copy_n("-inf", 4, out);
write_sign();
std::copy_n("inf", 3, out);
return true;
}
@ -1815,7 +1813,7 @@ struct duration_formatter {
auto buf = memory_buffer();
write_floating_seconds(buf, std::chrono::duration<rep, Period>(val),
precision);
if (negative) *out++ = '-';
write_sign();
if (buf.size() < 2 || buf[1] == '.')
out = detail::write_padding(out, pad);
out = copy<Char>(buf.begin(), buf.end(), out);

View File

@ -755,6 +755,35 @@ TEST(chrono_test, special_durations) {
"01.234");
}
TEST(chrono_test, negative_floating_duration_sign) {
auto d = std::chrono::duration<double>(-61.25);
EXPECT_EQ(fmt::format("{:%S %M}", d), "-01.250000 01");
EXPECT_EQ(fmt::format("{:%S %S}", d), "-01.250000 01.250000");
EXPECT_EQ(fmt::format("{:%S %Q}", d), "-01.250000 61.25");
EXPECT_EQ(fmt::format("{:%Q %S}", d), "-61.25 01.250000");
EXPECT_EQ(fmt::format("{:%S %Q}", -d), "01.250000 61.25");
EXPECT_EQ(fmt::format("{:%S %Q}", std::chrono::duration<float>(-1)), "-01 1");
EXPECT_EQ(fmt::format("{:%S %Q}", std::chrono::duration<long double>(-1)),
"-01 1");
}
TEST(chrono_test, negative_infinite_duration_sign) {
auto inf = std::numeric_limits<double>::infinity();
auto d = std::chrono::duration<double>(-inf);
EXPECT_EQ(fmt::format("{:%Q}", d), "-inf");
EXPECT_EQ(fmt::format("{:%S}", d), "-inf");
EXPECT_EQ(fmt::format("{:%H}", d), "-inf");
EXPECT_EQ(fmt::format("{:%j}", d), "-inf");
EXPECT_EQ(fmt::format("{:%R}", d), "-inf:inf");
EXPECT_EQ(fmt::format("{:%T}", d), "-inf:inf:inf");
EXPECT_EQ(fmt::format("{:%S %Q}", d), "-inf inf");
EXPECT_EQ(fmt::format("{:>6%Q}", d), " -inf");
EXPECT_EQ(fmt::format("{:%Q %S}", -d), "inf inf");
EXPECT_EQ(fmt::format("{:%Q}", std::chrono::duration<float>(-inf)), "-inf");
EXPECT_EQ(fmt::format("{:%Q}", std::chrono::duration<long double>(-inf)),
"-inf");
}
TEST(chrono_test, unsigned_duration) {
EXPECT_EQ(fmt::format("{}", std::chrono::duration<unsigned>(42)), "42s");
}