|
| 1 | +/* SPDX-License-Identifier: LGPL-2.1+ */ |
| 2 | + |
| 3 | +#include "util.h" |
| 4 | +#include "time-util.h" |
| 5 | + |
| 6 | +char *format_timespan(char *buf, size_t l, usec_t t, usec_t accuracy) { |
| 7 | + static const struct { |
| 8 | + const char *suffix; |
| 9 | + usec_t usec; |
| 10 | + } table[] = { |
| 11 | + { "y", USEC_PER_YEAR }, |
| 12 | + { "month", USEC_PER_MONTH }, |
| 13 | + { "w", USEC_PER_WEEK }, |
| 14 | + { "d", USEC_PER_DAY }, |
| 15 | + { "h", USEC_PER_HOUR }, |
| 16 | + { "min", USEC_PER_MINUTE }, |
| 17 | + { "s", USEC_PER_SEC }, |
| 18 | + { "ms", USEC_PER_MSEC }, |
| 19 | + { "us", 1 }, |
| 20 | + }; |
| 21 | + |
| 22 | + size_t i; |
| 23 | + char *p = buf; |
| 24 | + bool something = false; |
| 25 | + |
| 26 | + assert(buf); |
| 27 | + assert(l > 0); |
| 28 | + |
| 29 | + if (t == USEC_INFINITY) { |
| 30 | + strncpy(p, "infinity", l-1); |
| 31 | + p[l-1] = 0; |
| 32 | + return p; |
| 33 | + } |
| 34 | + |
| 35 | + if (t <= 0) { |
| 36 | + strncpy(p, "0", l-1); |
| 37 | + p[l-1] = 0; |
| 38 | + return p; |
| 39 | + } |
| 40 | + |
| 41 | + /* The result of this function can be parsed with parse_sec */ |
| 42 | + |
| 43 | + for (i = 0; i < ELEMENTSOF(table); i++) { |
| 44 | + int k = 0; |
| 45 | + size_t n; |
| 46 | + bool done = false; |
| 47 | + usec_t a, b; |
| 48 | + |
| 49 | + if (t <= 0) |
| 50 | + break; |
| 51 | + |
| 52 | + if (t < accuracy && something) |
| 53 | + break; |
| 54 | + |
| 55 | + if (t < table[i].usec) |
| 56 | + continue; |
| 57 | + |
| 58 | + if (l <= 1) |
| 59 | + break; |
| 60 | + |
| 61 | + a = t / table[i].usec; |
| 62 | + b = t % table[i].usec; |
| 63 | + |
| 64 | + /* Let's see if we should shows this in dot notation */ |
| 65 | + if (t < USEC_PER_MINUTE && b > 0) { |
| 66 | + usec_t cc; |
| 67 | + signed char j; |
| 68 | + |
| 69 | + j = 0; |
| 70 | + for (cc = table[i].usec; cc > 1; cc /= 10) |
| 71 | + j++; |
| 72 | + |
| 73 | + for (cc = accuracy; cc > 1; cc /= 10) { |
| 74 | + b /= 10; |
| 75 | + j--; |
| 76 | + } |
| 77 | + |
| 78 | + if (j > 0) { |
| 79 | + k = snprintf(p, l, |
| 80 | + "%s"USEC_FMT".%0*"PRI_USEC"%s", |
| 81 | + p > buf ? " " : "", |
| 82 | + a, |
| 83 | + j, |
| 84 | + b, |
| 85 | + table[i].suffix); |
| 86 | + |
| 87 | + t = 0; |
| 88 | + done = true; |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + /* No? Then let's show it normally */ |
| 93 | + if (!done) { |
| 94 | + k = snprintf(p, l, |
| 95 | + "%s"USEC_FMT"%s", |
| 96 | + p > buf ? " " : "", |
| 97 | + a, |
| 98 | + table[i].suffix); |
| 99 | + |
| 100 | + t = b; |
| 101 | + } |
| 102 | + |
| 103 | + n = MIN((size_t) k, l); |
| 104 | + |
| 105 | + l -= n; |
| 106 | + p += n; |
| 107 | + |
| 108 | + something = true; |
| 109 | + } |
| 110 | + |
| 111 | + *p = 0; |
| 112 | + |
| 113 | + return buf; |
| 114 | +} |
0 commit comments