core/string: Refactor sec2str_detailed()
I only need one function to perform the entire conversion using g_strdup_printf(). This helps to simplify the code before switching over to C. Signed-off-by: Anna Schumaker <Anna@OcarinaProject.net>
This commit is contained in:
parent
a314ee03ca
commit
18b83f5c26
|
@ -3,48 +3,42 @@
|
|||
*/
|
||||
#include <core/string.h>
|
||||
|
||||
#define O_SECONDS (1)
|
||||
#define O_MINUTES (60)
|
||||
#define O_HOURS (60 * O_MINUTES)
|
||||
#define O_DAYS (24 * O_HOURS)
|
||||
|
||||
static unsigned int factor[4] = { O_DAYS, O_HOURS, O_MINUTES, O_SECONDS };
|
||||
static const char *field[4] = { "day", "hour", "minute", "second" };
|
||||
|
||||
|
||||
gchar *string_sec2str(unsigned int sec)
|
||||
{
|
||||
return g_strdup_printf("%u:%02u", sec / 60, sec % 60);
|
||||
}
|
||||
|
||||
static const std::string _time_detail(unsigned int value,
|
||||
unsigned int remaining,
|
||||
const std::string &field)
|
||||
{
|
||||
std::string res;
|
||||
gchar *g_res;
|
||||
|
||||
if (value > 0) {
|
||||
g_res = g_strdup_printf("%u %s%s%s", value, field.c_str(),
|
||||
(value > 1) ? "s" : "",
|
||||
(remaining > 0) ? ", " : "");
|
||||
res = g_res;
|
||||
g_free(g_res);
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
const std::string string :: sec2str_detailed(unsigned int sec)
|
||||
{
|
||||
std::string res;
|
||||
unsigned int factor[3] = { O_DAYS, O_HOURS, O_MINUTES };
|
||||
std::string field[3] = { "day", "hour", "minute" };
|
||||
gchar *tmp;
|
||||
unsigned int val;
|
||||
std::string res;
|
||||
gchar *g_res = g_strdup("");
|
||||
|
||||
for (unsigned int i = 0; i < 3; i++) {
|
||||
for (unsigned int i = 0; i < 4; i++) {
|
||||
val = sec / factor[i];
|
||||
sec %= factor[i];
|
||||
res += _time_detail(val, sec, field[i]);
|
||||
if (val == 0)
|
||||
continue;
|
||||
|
||||
tmp = g_strdup_printf("%s%u %s%s%s", g_res, val, field[i],
|
||||
(val > 1) ? "s" : "",
|
||||
(sec > 0) ? ", " : "");
|
||||
g_free(g_res);
|
||||
g_res = tmp;
|
||||
}
|
||||
|
||||
res += _time_detail(sec, 0, "second");
|
||||
res = g_res;
|
||||
g_free(g_res);
|
||||
return res;
|
||||
}
|
||||
|
||||
|
|
|
@ -49,6 +49,7 @@ void test_sec2str_detailed()
|
|||
test_equal(string :: sec2str_detailed(2 * minute), "2 minutes");
|
||||
|
||||
test_equal(string :: sec2str_detailed(minute + 1), "1 minute, 1 second");
|
||||
test_equal(string :: sec2str_detailed(0), "");
|
||||
test_equal(string :: sec2str_detailed(1), "1 second");
|
||||
test_equal(string :: sec2str_detailed(2), "2 seconds");
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue