0
0
Fork 0
mirror of https://github.com/matrix-construct/construct synced 2024-11-25 16:22:35 +01:00

ircd: Add pretty() human readable time utils.

This commit is contained in:
Jason Volk 2018-10-18 17:31:43 -07:00
parent 7eb091cad0
commit 0d6b49a0b6
2 changed files with 107 additions and 1 deletions

View file

@ -45,6 +45,11 @@ namespace ircd
std::string pretty(const human_readable_size &);
string_view pretty_only(const mutable_buffer &out, const human_readable_size &);
std::string pretty_only(const human_readable_size &);
// Human readable time suite (for timers and counts; otherwise see date.h)
string_view pretty_nanoseconds(const mutable_buffer &out, const long double &);
template<class r, class p> string_view pretty(const mutable_buffer &out, const duration<r, p> &);
template<class r, class p> std::string pretty(const duration<r, p> &);
}
namespace ircd
@ -266,3 +271,25 @@ ircd::try_lex_cast<std::string>(const string_view &s)
{
return true;
}
template<class rep,
class period>
std::string
ircd::pretty(const duration<rep, period> &d)
{
return util::string(32, [&d]
(const mutable_buffer &out)
{
return pretty(out, d);
});
}
template<class rep,
class period>
ircd::string_view
ircd::pretty(const mutable_buffer &out,
const duration<rep, period> &d)
{
const auto &ns(duration_cast<nanoseconds>(d));
return pretty_nanoseconds(out, ns.count());
}

View file

@ -23,7 +23,86 @@
//
//
// Human readable unit suite
// Human readable time suite
//
ircd::string_view
ircd::pretty_nanoseconds(const mutable_buffer &out,
const long double &ns)
{
static const std::array<string_view, 7> unit
{
"nanoseconds",
"microseconds",
"milliseconds",
"seconds",
"minutes",
"hours",
"days",
};
auto pos(0);
long double val(ns);
// nanoseconds -> microseconds
if(val > 1000.0)
{
val /= 1000;
++pos;
}
else goto done;
// microseconds -> milliseconds
if(val > 1000.0)
{
val /= 1000;
++pos;
}
else goto done;
// milliseconds -> seconds
if(val > 1000.0)
{
val /= 1000;
++pos;
}
else goto done;
// seconds -> minutes
if(val > 60.0)
{
val /= 60;
++pos;
}
else goto done;
// minutes -> hours
if(val > 60.0)
{
val /= 60;
++pos;
}
else goto done;
// hours -> days
if(val > 12.0)
{
val /= 12;
++pos;
}
else goto done;
done:
return fmt::sprintf
{
out, "%.2lf %s",
val,
unit.at(pos)
};
}
//
// Human readable space suite
//
std::string