Line data Source code
1 : /* SPDX-License-Identifier: LGPL-2.1+ */
2 :
3 : #include <stdio.h>
4 :
5 : #include "format-util.h"
6 : #include "memory-util.h"
7 :
8 0 : char *format_ifname(int ifindex, char buf[static IF_NAMESIZE + 1]) {
9 : /* Buffer is always cleared */
10 0 : memzero(buf, IF_NAMESIZE + 1);
11 0 : return if_indextoname(ifindex, buf);
12 : }
13 :
14 109 : 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_si[] = {
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 n, i;
36 :
37 : assert_cc(ELEMENTSOF(table_iec) == ELEMENTSOF(table_si));
38 :
39 109 : if (t == (uint64_t) -1)
40 8 : return NULL;
41 :
42 101 : table = flag & FORMAT_BYTES_USE_IEC ? table_iec : table_si;
43 101 : n = ELEMENTSOF(table_iec);
44 :
45 566 : for (i = 0; i < n; i++)
46 525 : if (t >= table[i].factor) {
47 60 : if (flag & FORMAT_BYTES_BELOW_POINT) {
48 160 : snprintf(buf, l,
49 : "%" PRIu64 ".%" PRIu64 "%s",
50 40 : t / table[i].factor,
51 40 : i != n - 1 ?
52 29 : (t / table[i + 1].factor * UINT64_C(10) / table[n - 1].factor) % UINT64_C(10):
53 11 : (t * UINT64_C(10) / table[i].factor) % UINT64_C(10),
54 40 : table[i].suffix);
55 : } else
56 40 : snprintf(buf, l,
57 : "%" PRIu64 "%s",
58 20 : t / table[i].factor,
59 20 : table[i].suffix);
60 :
61 60 : goto finish;
62 : }
63 :
64 41 : snprintf(buf, l, "%" PRIu64 "%s", t, flag & FORMAT_BYTES_TRAILING_B ? "B" : "");
65 :
66 101 : finish:
67 101 : buf[l-1] = 0;
68 101 : return buf;
69 :
70 : }
|