libsaria: Format a duration (in seconds)
I turn it into a string "W days, X hours, Y minutes, Z seconds" Signed-off-by: Bryan Schumaker <bjschuma@gmail.com>
This commit is contained in:
parent
fcc48dbccb
commit
c5fe4546e2
|
@ -10,6 +10,7 @@ namespace libsaria
|
|||
|
||||
set<string> *format_text(const string &);
|
||||
string *lowercase(const string &);
|
||||
string length_string(unsigned int);
|
||||
void print_format_stats();
|
||||
|
||||
}
|
||||
|
|
|
@ -4,6 +4,7 @@
|
|||
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <sstream>
|
||||
using namespace std;
|
||||
|
||||
static map<string, set<string> > format_cache;
|
||||
|
@ -11,6 +12,11 @@ static map<string, string> lc_cache;
|
|||
static unsigned int format_hits;
|
||||
static unsigned int lc_hits;
|
||||
|
||||
static const unsigned int TM_SECOND = 1;
|
||||
static const unsigned int TM_MINUTE = 60;
|
||||
static const unsigned int TM_HOUR = TM_MINUTE * 60;
|
||||
static const unsigned int TM_DAY = TM_HOUR * 24;
|
||||
|
||||
void do_format(const string &text,
|
||||
map<string, set<string> >::iterator &words,
|
||||
map<string, string>::iterator &lc)
|
||||
|
@ -91,6 +97,22 @@ void find_lowercase(const string &text,
|
|||
do_format(text, words, lc);
|
||||
}
|
||||
|
||||
unsigned int add_to_stream(stringstream &stream, const unsigned int factor,
|
||||
string field, unsigned int length, unsigned int total)
|
||||
{
|
||||
unsigned int res = length / factor;
|
||||
if (res == 0)
|
||||
return 0;
|
||||
|
||||
if (total != 0)
|
||||
stream << ", ";
|
||||
stream << res << " " << field;
|
||||
if (res > 1)
|
||||
stream << "s";
|
||||
|
||||
return res * factor;;
|
||||
}
|
||||
|
||||
namespace libsaria
|
||||
{
|
||||
|
||||
|
@ -120,6 +142,22 @@ namespace libsaria
|
|||
return &(it->second);
|
||||
}
|
||||
|
||||
string length_string(unsigned int len)
|
||||
{
|
||||
unsigned int tot;
|
||||
stringstream stream;
|
||||
|
||||
if (len == 0)
|
||||
return "";
|
||||
|
||||
tot = add_to_stream(stream, TM_DAY, "day", len, 0);
|
||||
tot += add_to_stream(stream, TM_HOUR, "hour", len - tot, tot);
|
||||
tot += add_to_stream(stream, TM_MINUTE, "minute", len - tot, tot);
|
||||
|
||||
add_to_stream(stream, TM_SECOND, "second", len - tot, tot);
|
||||
return stream.str();
|
||||
}
|
||||
|
||||
void print_format_stats()
|
||||
{
|
||||
println("Format cache hits: %u size: %u", format_hits, format_cache.size());
|
||||
|
|
Loading…
Reference in New Issue