summaryrefslogtreecommitdiffstats
path: root/lib/json_print_math.c
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-05-04 14:18:53 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-05-04 14:18:53 +0000
commita0e0018c9a7ef5ce7f6d2c3ae16aecbbd16a8f67 (patch)
tree8feaf1a1932871b139b3b30be4c09c66489918be /lib/json_print_math.c
parentInitial commit. (diff)
downloadiproute2-upstream/6.1.0.tar.xz
iproute2-upstream/6.1.0.zip
Adding upstream version 6.1.0.upstream/6.1.0upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'lib/json_print_math.c')
-rw-r--r--lib/json_print_math.c37
1 files changed, 37 insertions, 0 deletions
diff --git a/lib/json_print_math.c b/lib/json_print_math.c
new file mode 100644
index 0000000..f4d5049
--- /dev/null
+++ b/lib/json_print_math.c
@@ -0,0 +1,37 @@
+// SPDX-License-Identifier: GPL-2.0+
+
+#include <stdarg.h>
+#include <stdio.h>
+#include <math.h>
+
+#include "utils.h"
+#include "json_print.h"
+
+char *sprint_size(__u32 sz, char *buf)
+{
+ long kilo = 1024;
+ long mega = kilo * kilo;
+ size_t len = SPRINT_BSIZE - 1;
+ double tmp = sz;
+
+ if (sz >= mega && fabs(mega * rint(tmp / mega) - sz) < 1024)
+ snprintf(buf, len, "%gMb", rint(tmp / mega));
+ else if (sz >= kilo && fabs(kilo * rint(tmp / kilo) - sz) < 16)
+ snprintf(buf, len, "%gKb", rint(tmp / kilo));
+ else
+ snprintf(buf, len, "%ub", sz);
+
+ return buf;
+}
+
+int print_color_size(enum output_type type, enum color_attr color,
+ const char *key, const char *fmt, __u32 sz)
+{
+ SPRINT_BUF(buf);
+
+ if (_IS_JSON_CONTEXT(type))
+ return print_color_uint(type, color, key, "%u", sz);
+
+ sprint_size(sz, buf);
+ return print_color_string(type, color, key, fmt, buf);
+}