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