diff options
author | Anthony G. Basile <blueness@gentoo.org> | 2013-07-10 12:31:27 -0400 |
---|---|---|
committer | Anthony G. Basile <blueness@gentoo.org> | 2013-07-10 12:31:27 -0400 |
commit | 037a28c3d2bc5bf4a3f36b0172e83e6515b05a68 (patch) | |
tree | 7d2a3acca5cc0b14cbea84b7544e1086f57e4269 /src/libudev/util.c | |
parent | fbae3924871345cb60979dd9fb6794a091ba3ad1 (diff) |
Bring mkdir.c, label.c and util.c in better line with upstream
Signed-off-by: Anthony G. Basile <blueness@gentoo.org>
Diffstat (limited to 'src/libudev/util.c')
-rw-r--r-- | src/libudev/util.c | 107 |
1 files changed, 107 insertions, 0 deletions
diff --git a/src/libudev/util.c b/src/libudev/util.c index e447f89647..f625cfe99b 100644 --- a/src/libudev/util.c +++ b/src/libudev/util.c @@ -127,6 +127,113 @@ usec_t timespec_load(const struct timespec *ts) { (usec_t) ts->tv_nsec / NSEC_PER_USEC; } +char *format_timespan(char *buf, size_t l, usec_t t, usec_t accuracy) { + static const struct { + const char *suffix; + usec_t usec; + } table[] = { + { "y", USEC_PER_YEAR }, + { "month", USEC_PER_MONTH }, + { "w", USEC_PER_WEEK }, + { "d", USEC_PER_DAY }, + { "h", USEC_PER_HOUR }, + { "min", USEC_PER_MINUTE }, + { "s", USEC_PER_SEC }, + { "ms", USEC_PER_MSEC }, + { "us", 1 }, + }; + + unsigned i; + char *p = buf; + bool something = false; + + assert(buf); + assert(l > 0); + + if (t == (usec_t) -1) + return NULL; + + if (t <= 0) { + snprintf(p, l, "0"); + p[l-1] = 0; + return p; + } + + /* The result of this function can be parsed with parse_sec */ + + for (i = 0; i < ELEMENTSOF(table); i++) { + int k; + size_t n; + bool done = false; + usec_t a, b; + + if (t <= 0) + break; + + if (t < accuracy && something) + break; + + if (t < table[i].usec) + continue; + + if (l <= 1) + break; + + a = t / table[i].usec; + b = t % table[i].usec; + + /* Let's see if we should shows this in dot notation */ + if (t < USEC_PER_MINUTE && b > 0) { + usec_t cc; + int j; + + j = 0; + for (cc = table[i].usec; cc > 1; cc /= 10) + j++; + + for (cc = accuracy; cc > 1; cc /= 10) { + b /= 10; + j--; + } + + if (j > 0) { + k = snprintf(p, l, + "%s%llu.%0*llu%s", + p > buf ? " " : "", + (unsigned long long) a, + j, + (unsigned long long) b, + table[i].suffix); + + t = 0; + done = true; + } + } + + /* No? Then let's show it normally */ + if (!done) { + k = snprintf(p, l, + "%s%llu%s", + p > buf ? " " : "", + (unsigned long long) a, + table[i].suffix); + + t = b; + } + + n = MIN((size_t) k, l); + + l -= n; + p += n; + + something = true; + } + + *p = 0; + + return buf; +} + char* endswith(const char *s, const char *postfix) { size_t sl, pl; |