6 #include "../compiler/compiler.h"
7 #include "../oslib/asprintf.h"
11 * num2str() - Cheesy number->string conversion, complete with carry rounding error.
12 * @num: quantity (e.g., number of blocks, bytes or bits)
13 * @maxlen: max number of digits in the output string (not counting prefix and units, but counting .)
14 * @base: multiplier for num (e.g., if num represents Ki, use 1024)
15 * @pow2: select unit prefix - 0=power-of-10 decimal SI, nonzero=power-of-2 binary IEC
16 * @units: select units - N2S_* constants defined in num2str.h
17 * @returns a malloc'd buffer containing "number[<unit prefix>][<units>]"
19 char *num2str(uint64_t num, int maxlen, int base, int pow2, enum n2s_unit units)
21 const char *sistr[] = { "", "k", "M", "G", "T", "P", "E" };
22 const char *iecstr[] = { "", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei" };
23 const char **unitprefix;
24 static const char *const unitstr[] = {
29 [N2S_BYTEPERSEC]= "B/s",
30 [N2S_BITPERSEC] = "bit/s"
32 const unsigned int thousand = pow2 ? 1024 : 1000;
34 int post_index, carry = 0;
38 compiletime_assert(sizeof(sistr) == sizeof(iecstr), "unit prefix arrays must be identical sizes");
39 assert(units < FIO_ARRAY_SIZE(unitstr));
46 for (post_index = 0; base > 1; post_index++)
67 * Divide by K/Ki until string length of num <= maxlen.
70 while (post_index < FIO_ARRAY_SIZE(sistr)) {
71 sprintf(tmp, "%llu", (unsigned long long) num);
72 if (strlen(tmp) <= maxlen)
75 modulo = num % thousand;
77 carry = modulo >= thousand / 2;
81 if (post_index >= FIO_ARRAY_SIZE(sistr))
85 * If no modulo, then we're done.
89 if (asprintf(&buf, "%llu%s%s", (unsigned long long) num,
90 unitprefix[post_index], unitstr[units]) < 0)
96 * If no room for decimals, then we're done.
98 sprintf(tmp, "%llu", (unsigned long long) num);
99 if ((int)(maxlen - strlen(tmp)) <= 1) {
106 * Fill in everything and return the result.
108 assert(maxlen - strlen(tmp) - 1 > 0);
109 assert(modulo < thousand);
110 sprintf(tmp, "%.*f", (int)(maxlen - strlen(tmp) - 1),
111 (double)modulo / (double)thousand);
116 if (asprintf(&buf, "%llu.%s%s%s", (unsigned long long) num, &tmp[2],
117 unitprefix[post_index], unitstr[units]) < 0)