6 #include "../compiler/compiler.h"
7 #include "../oslib/asprintf.h"
10 #define ARRAY_SIZE(x) (sizeof((x)) / (sizeof((x)[0])))
13 * num2str() - Cheesy number->string conversion, complete with carry rounding error.
14 * @num: quantity (e.g., number of blocks, bytes or bits)
15 * @maxlen: max number of digits in the output string (not counting prefix and units, but counting .)
16 * @base: multiplier for num (e.g., if num represents Ki, use 1024)
17 * @pow2: select unit prefix - 0=power-of-10 decimal SI, nonzero=power-of-2 binary IEC
18 * @units: select units - N2S_* constants defined in num2str.h
19 * @returns a malloc'd buffer containing "number[<unit prefix>][<units>]"
21 char *num2str(uint64_t num, int maxlen, int base, int pow2, enum n2s_unit units)
23 const char *sistr[] = { "", "k", "M", "G", "T", "P", "E" };
24 const char *iecstr[] = { "", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei" };
25 const char **unitprefix;
26 static const char *const unitstr[] = {
31 [N2S_BYTEPERSEC]= "B/s",
32 [N2S_BITPERSEC] = "bit/s"
34 const unsigned int thousand = pow2 ? 1024 : 1000;
36 int post_index, carry = 0;
40 compiletime_assert(sizeof(sistr) == sizeof(iecstr), "unit prefix arrays must be identical sizes");
41 assert(units < ARRAY_SIZE(unitstr));
48 for (post_index = 0; base > 1; post_index++)
69 * Divide by K/Ki until string length of num <= maxlen.
72 while (post_index < ARRAY_SIZE(sistr)) {
73 sprintf(tmp, "%llu", (unsigned long long) num);
74 if (strlen(tmp) <= maxlen)
77 modulo = num % thousand;
79 carry = modulo >= thousand / 2;
83 if (post_index >= ARRAY_SIZE(sistr))
87 * If no modulo, then we're done.
91 if (asprintf(&buf, "%llu%s%s", (unsigned long long) num,
92 unitprefix[post_index], unitstr[units]) < 0)
98 * If no room for decimals, then we're done.
100 sprintf(tmp, "%llu", (unsigned long long) num);
101 if ((int)(maxlen - strlen(tmp)) <= 1) {
108 * Fill in everything and return the result.
110 assert(maxlen - strlen(tmp) - 1 > 0);
111 assert(modulo < thousand);
112 sprintf(tmp, "%.*f", (int)(maxlen - strlen(tmp) - 1),
113 (double)modulo / (double)thousand);
115 if (asprintf(&buf, "%llu.%s%s%s", (unsigned long long) num, &tmp[2],
116 unitprefix[post_index], unitstr[units]) < 0)