From 18b83f5c264f29f4bac3277c09eefbe36ef419df Mon Sep 17 00:00:00 2001 From: Anna Schumaker Date: Wed, 2 Sep 2015 08:13:21 -0400 Subject: [PATCH] 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 --- core/string.cpp | 42 ++++++++++++++++++------------------------ tests/core/string.cpp | 1 + 2 files changed, 19 insertions(+), 24 deletions(-) diff --git a/core/string.cpp b/core/string.cpp index ddd1fc85..f3f72d96 100644 --- a/core/string.cpp +++ b/core/string.cpp @@ -3,48 +3,42 @@ */ #include +#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; } diff --git a/tests/core/string.cpp b/tests/core/string.cpp index 30f19491..bcaeff22 100644 --- a/tests/core/string.cpp +++ b/tests/core/string.cpp @@ -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"); }