Skip to content

Commit bc48e16

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

1 file changed

Lines changed: 49 additions & 2 deletions

File tree

tests/Timestamp.cpp

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
#include <catch2/catch_test_macros.hpp>
1+
#include <version>
22

33
#ifdef __cpp_lib_print
44
# include <format>
@@ -12,7 +12,54 @@
1212
#endif
1313

1414

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

1764
TEST_CASE("Core::Timestamp", "Timestamp")
1865
{

0 commit comments

Comments
 (0)