Skip to content

Commit 29ddd6f

Browse files
committed
Timestamp test: add chrono duration formatter
1 parent 00e29ea commit 29ddd6f

1 file changed

Lines changed: 47 additions & 0 deletions

File tree

tests/Timestamp.cpp

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,53 @@
1414

1515
using namespace std;
1616

17+
#if AVCPP_CXX_STANDARD < 20 || __cpp_lib_chrono < 201907L
18+
#include <sstream>
19+
#include <iostream>
20+
#include <type_traits>
21+
#include <chrono>
22+
23+
template<typename Rep, typename Period>
24+
std::ostream& operator<<(std::ostream& ost, const std::chrono::duration<Rep, Period>& dur)
25+
{
26+
using namespace std::literals;
27+
28+
std::ostringstream s;
29+
s.flags(ost.flags());
30+
s.imbue(ost.getloc());
31+
s.precision(ost.precision());
32+
33+
s << +dur.count();
34+
35+
// Ref: https://en.cppreference.com/w/cpp/chrono/duration/operator_ltlt.html
36+
if constexpr (std::is_same_v<Period, std::atto>) s << "as"sv;
37+
else if constexpr (std::is_same_v<Period, std::femto>) s << "fs"sv;
38+
else if constexpr (std::is_same_v<Period, std::pico>) s << "fs"sv;
39+
else if constexpr (std::is_same_v<Period, std::nano>) s << "ns"sv;
40+
else if constexpr (std::is_same_v<Period, std::micro>) s << "us"sv;
41+
else if constexpr (std::is_same_v<Period, std::milli>) s << "ms"sv;
42+
else if constexpr (std::is_same_v<Period, std::centi>) s << "cs"sv;
43+
else if constexpr (std::is_same_v<Period, std::deci>) s << "ds"sv;
44+
else if constexpr (std::is_same_v<Period, std::ratio<1>>) s << "s"sv;
45+
else if constexpr (std::is_same_v<Period, std::deca>) s << "das"sv;
46+
else if constexpr (std::is_same_v<Period, std::hecto>) s << "hs"sv;
47+
else if constexpr (std::is_same_v<Period, std::kilo>) s << "ks"sv;
48+
else if constexpr (std::is_same_v<Period, std::mega>) s << "Ms"sv;
49+
else if constexpr (std::is_same_v<Period, std::giga>) s << "Gs"sv;
50+
else if constexpr (std::is_same_v<Period, std::tera>) s << "Ts"sv;
51+
else if constexpr (std::is_same_v<Period, std::peta>) s << "Ps"sv;
52+
else if constexpr (std::is_same_v<Period, std::exa>) s << "Es"sv;
53+
else if constexpr (std::is_same_v<Period, std::ratio<60>>) s << "min"sv;
54+
else if constexpr (std::is_same_v<Period, std::ratio<3600>>) s << "h"sv;
55+
else if constexpr (std::is_same_v<Period, std::ratio<86400>>) s << "d"sv;
56+
else if constexpr (Period::den == 1) s << '[' << Period::num << "]s"sv;
57+
else
58+
s << '[' << Period::num << '/' << Period::num << "]s"sv;
59+
ost << std::move(s).str();
60+
return ost;
61+
}
62+
#endif
63+
1764
TEST_CASE("Core::Timestamp", "Timestamp")
1865
{
1966
SECTION("Overflow operator+(a,b)")

0 commit comments

Comments
 (0)