]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/format-util.c
9fea2e0690e5f4e344695212398dbd778ea78fc0
[thirdparty/systemd.git] / src / basic / format-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <stdio.h>
4
5 #include "format-util.h"
6 #include "memory-util.h"
7 #include "stdio-util.h"
8
9 assert_cc(DECIMAL_STR_MAX(int) + 1 <= IF_NAMESIZE + 1);
10 char *format_ifname_full(int ifindex, char buf[static IF_NAMESIZE + 1], FormatIfnameFlag flag) {
11 /* Buffer is always cleared */
12 memzero(buf, IF_NAMESIZE + 1);
13 if (if_indextoname(ifindex, buf))
14 return buf;
15
16 if (!FLAGS_SET(flag, FORMAT_IFNAME_IFINDEX))
17 return NULL;
18
19 if (FLAGS_SET(flag, FORMAT_IFNAME_IFINDEX_WITH_PERCENT))
20 snprintf(buf, IF_NAMESIZE + 1, "%%%d", ifindex);
21 else
22 snprintf(buf, IF_NAMESIZE + 1, "%d", ifindex);
23
24 return buf;
25 }
26
27 char *format_bytes_full(char *buf, size_t l, uint64_t t, FormatBytesFlag flag) {
28 typedef struct {
29 const char *suffix;
30 uint64_t factor;
31 } suffix_table;
32 static const suffix_table table_iec[] = {
33 { "E", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
34 { "P", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
35 { "T", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
36 { "G", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
37 { "M", UINT64_C(1024)*UINT64_C(1024) },
38 { "K", UINT64_C(1024) },
39 }, table_si[] = {
40 { "E", UINT64_C(1000)*UINT64_C(1000)*UINT64_C(1000)*UINT64_C(1000)*UINT64_C(1000)*UINT64_C(1000) },
41 { "P", UINT64_C(1000)*UINT64_C(1000)*UINT64_C(1000)*UINT64_C(1000)*UINT64_C(1000) },
42 { "T", UINT64_C(1000)*UINT64_C(1000)*UINT64_C(1000)*UINT64_C(1000) },
43 { "G", UINT64_C(1000)*UINT64_C(1000)*UINT64_C(1000) },
44 { "M", UINT64_C(1000)*UINT64_C(1000) },
45 { "K", UINT64_C(1000) },
46 };
47 const suffix_table *table;
48 size_t n, i;
49
50 assert_cc(ELEMENTSOF(table_iec) == ELEMENTSOF(table_si));
51
52 if (t == (uint64_t) -1)
53 return NULL;
54
55 table = flag & FORMAT_BYTES_USE_IEC ? table_iec : table_si;
56 n = ELEMENTSOF(table_iec);
57
58 for (i = 0; i < n; i++)
59 if (t >= table[i].factor) {
60 if (flag & FORMAT_BYTES_BELOW_POINT) {
61 snprintf(buf, l,
62 "%" PRIu64 ".%" PRIu64 "%s",
63 t / table[i].factor,
64 i != n - 1 ?
65 (t / table[i + 1].factor * UINT64_C(10) / table[n - 1].factor) % UINT64_C(10):
66 (t * UINT64_C(10) / table[i].factor) % UINT64_C(10),
67 table[i].suffix);
68 } else
69 snprintf(buf, l,
70 "%" PRIu64 "%s",
71 t / table[i].factor,
72 table[i].suffix);
73
74 goto finish;
75 }
76
77 snprintf(buf, l, "%" PRIu64 "%s", t, flag & FORMAT_BYTES_TRAILING_B ? "B" : "");
78
79 finish:
80 buf[l-1] = 0;
81 return buf;
82
83 }