Skip to content

Commit

Permalink
Report out-of-range errors in chrono
Browse files Browse the repository at this point in the history
  • Loading branch information
vitaut authored and happymonkey1 committed Apr 6, 2024
1 parent f7ba249 commit 3e3712d
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 10 deletions.
8 changes: 4 additions & 4 deletions include/fmt/chrono.h
Original file line number Diff line number Diff line change
Expand Up @@ -1049,10 +1049,10 @@ inline void tzset_once() {
// Converts value to Int and checks that it's in the range [0, upper).
template <typename T, typename Int, FMT_ENABLE_IF(std::is_integral<T>::value)>
inline Int to_nonnegative_int(T value, Int upper) {
FMT_ASSERT(std::is_unsigned<Int>::value ||
(value >= 0 && to_unsigned(value) <= to_unsigned(upper)),
"invalid value");
(void)upper;
if (!std::is_unsigned<Int>::value &&
(value < 0 || to_unsigned(value) > to_unsigned(upper))) {
FMT_THROW(fmt::format_error("chrono value is out of range"));
}
return static_cast<Int>(value);
}
template <typename T, typename Int, FMT_ENABLE_IF(!std::is_integral<T>::value)>
Expand Down
17 changes: 11 additions & 6 deletions test/chrono-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -740,8 +740,8 @@ TEST(chrono_test, special_durations) {
EXPECT_EQ(fmt::format("{:%T}", std::chrono::duration<char, std::mega>{2}),
"03:33:20");
EXPECT_EQ("01.234",
fmt::format("{:.3%S}", std::chrono::duration<float, std::pico>(
1.234e12)));
fmt::format("{:.3%S}",
std::chrono::duration<float, std::pico>(1.234e12)));
}

TEST(chrono_test, unsigned_duration) {
Expand Down Expand Up @@ -864,18 +864,18 @@ TEST(chrono_test, timestamps_ratios) {

EXPECT_EQ(fmt::format("{:%M:%S}", t1), "01:07.890");

std::chrono::time_point<std::chrono::system_clock, std::chrono::minutes>
t2(std::chrono::minutes(7));
std::chrono::time_point<std::chrono::system_clock, std::chrono::minutes> t2(
std::chrono::minutes(7));

EXPECT_EQ(fmt::format("{:%M:%S}", t2), "07:00");

std::chrono::time_point<std::chrono::system_clock,
std::chrono::time_point<std::chrono::system_clock,
std::chrono::duration<int, std::ratio<9>>>
t3(std::chrono::duration<int, std::ratio<9>>(7));

EXPECT_EQ(fmt::format("{:%M:%S}", t3), "01:03");

std::chrono::time_point<std::chrono::system_clock,
std::chrono::time_point<std::chrono::system_clock,
std::chrono::duration<int, std::ratio<63>>>
t4(std::chrono::duration<int, std::ratio<63>>(1));

Expand Down Expand Up @@ -1023,3 +1023,8 @@ TEST(chrono_test, glibc_extensions) {
EXPECT_EQ(fmt::format("{:%-S}", d), "3.140000");
}
}

TEST(chrono_test, out_of_range) {
auto d = std::chrono::duration<unsigned long, std::giga>(538976288);
EXPECT_THROW((void)fmt::format("{:%j}", d), fmt::format_error);
}

0 comments on commit 3e3712d

Please sign in to comment.