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