| 1 |
/* SPDX-License-Identifier: LGPL-2.1-or-later */ |
| 2 |
|
| 3 |
#include "format-util.h" |
| 4 |
|
| 5 |
char* format_bytes_full(char *buf, size_t l, uint64_t t, FormatBytesFlag flag) { |
| 6 |
typedef struct { |
| 7 |
const char *suffix; |
| 8 |
uint64_t factor; |
| 9 |
} suffix_table; |
| 10 |
static const suffix_table table_iec[] = { |
| 11 |
{ "E", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) }, |
| 12 |
{ "P", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) }, |
| 13 |
{ "T", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) }, |
| 14 |
{ "G", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) }, |
| 15 |
{ "M", UINT64_C(1024)*UINT64_C(1024) }, |
| 16 |
{ "K", UINT64_C(1024) }, |
| 17 |
}, table_si[] = { |
| 18 |
{ "E", UINT64_C(1000)*UINT64_C(1000)*UINT64_C(1000)*UINT64_C(1000)*UINT64_C(1000)*UINT64_C(1000) }, |
| 19 |
{ "P", UINT64_C(1000)*UINT64_C(1000)*UINT64_C(1000)*UINT64_C(1000)*UINT64_C(1000) }, |
| 20 |
{ "T", UINT64_C(1000)*UINT64_C(1000)*UINT64_C(1000)*UINT64_C(1000) }, |
| 21 |
{ "G", UINT64_C(1000)*UINT64_C(1000)*UINT64_C(1000) }, |
| 22 |
{ "M", UINT64_C(1000)*UINT64_C(1000) }, |
| 23 |
{ "K", UINT64_C(1000) }, |
| 24 |
}; |
| 25 |
const suffix_table *table; |
| 26 |
size_t n; |
| 27 |
|
| 28 |
assert_cc(ELEMENTSOF(table_iec) == ELEMENTSOF(table_si)); |
| 29 |
|
| 30 |
if (t == UINT64_MAX) |
| 31 |
return NULL; |
| 32 |
|
| 33 |
table = flag & FORMAT_BYTES_USE_IEC ? table_iec : table_si; |
| 34 |
n = ELEMENTSOF(table_iec); |
| 35 |
|
| 36 |
for (size_t i = 0; i < n; i++) |
| 37 |
if (t >= table[i].factor) { |
| 38 |
uint64_t remainder = i != n - 1 ? |
| 39 |
(t / table[i + 1].factor * 10 / table[n - 1].factor) % 10 : |
| 40 |
(t * 10 / table[i].factor) % 10; |
| 41 |
|
| 42 |
if (FLAGS_SET(flag, FORMAT_BYTES_ALWAYS_POINT) || |
| 43 |
(FLAGS_SET(flag, FORMAT_BYTES_BELOW_POINT) && remainder > 0)) |
| 44 |
(void) snprintf(buf, l, |
| 45 |
"%" PRIu64 ".%" PRIu64 "%s", |
| 46 |
t / table[i].factor, |
| 47 |
remainder, |
| 48 |
table[i].suffix); |
| 49 |
else |
| 50 |
(void) snprintf(buf, l, |
| 51 |
"%" PRIu64 "%s", |
| 52 |
t / table[i].factor, |
| 53 |
table[i].suffix); |
| 54 |
|
| 55 |
goto finish; |
| 56 |
} |
| 57 |
|
| 58 |
(void) snprintf(buf, l, "%" PRIu64 "%s", t, flag & FORMAT_BYTES_TRAILING_B ? "B" : ""); |
| 59 |
|
| 60 |
finish: |
| 61 |
buf[l-1] = 0; |
| 62 |
return buf; |
| 63 |
} |