]> git.proxmox.com Git - mirror_iproute2.git/blame - lib/json_print_math.c
build: Fix link errors on some systems
[mirror_iproute2.git] / lib / json_print_math.c
CommitLineData
1a22ad27
RD
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
10char *sprint_size(__u32 sz, char *buf)
11{
12 long kilo = 1024;
13 long mega = kilo * kilo;
14 size_t len = SPRINT_BSIZE - 1;
15 double tmp = sz;
16
17 if (sz >= mega && fabs(mega * rint(tmp / mega) - sz) < 1024)
18 snprintf(buf, len, "%gMb", rint(tmp / mega));
19 else if (sz >= kilo && fabs(kilo * rint(tmp / kilo) - sz) < 16)
20 snprintf(buf, len, "%gKb", rint(tmp / kilo));
21 else
22 snprintf(buf, len, "%ub", sz);
23
24 return buf;
25}
26
27int print_color_size(enum output_type type, enum color_attr color,
28 const char *key, const char *fmt, __u32 sz)
29{
30 SPRINT_BUF(buf);
31
32 if (_IS_JSON_CONTEXT(type))
33 return print_color_uint(type, color, key, "%u", sz);
34
35 sprint_size(sz, buf);
36 return print_color_string(type, color, key, fmt, buf);
37}