Debian Codegraph @

lib/json_print_math.c

raw
1 // SPDX-License-Identifier: GPL-2.0+
2
3 #include <stdarg.h>
4 #include <stdio.h>
5 #include <math.h>
6
7 #include "utils.h"
8 #include "json_print.h"
9
10 char *sprint_size(__u64 sz, char *buf)
11 {
12 long kilo = 1024;
13 long mega = kilo * kilo;
14 long giga = mega * kilo;
15 size_t len = SPRINT_BSIZE - 1;
16 double tmp = sz;
17
18 if (sz >= giga && fabs(giga * rint(tmp / giga) - sz) < 1024)
19 snprintf(buf, len, "%gGb", rint(tmp / giga));
20 else if (sz >= mega && fabs(mega * rint(tmp / mega) - sz) < 1024)
21 snprintf(buf, len, "%gMb", rint(tmp / mega));
22 else if (sz >= kilo && fabs(kilo * rint(tmp / kilo) - sz) < 16)
23 snprintf(buf, len, "%gKb", rint(tmp / kilo));
24 else
25 snprintf(buf, len, "%llub", sz);
26
27 return buf;
28 }
29
30 int print_color_size(enum output_type type, enum color_attr color,
31 const char *key, const char *fmt, __u64 sz)
32 {
33 SPRINT_BUF(buf);
34
35 if (_IS_JSON_CONTEXT(type))
36 return print_color_uint(type, color, key, "%u", sz);
37
38 sprint_size(sz, buf);
39 return print_color_string(type, color, key, fmt, buf);
40 }