File: json_print_math.c

package info (click to toggle)
iproute2 6.18.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 7,272 kB
  • sloc: ansic: 125,480; sh: 1,363; cpp: 946; makefile: 697; yacc: 421; lex: 145; python: 43
file content (40 lines) | stat: -rw-r--r-- 1,004 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// 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(__u64 sz, char *buf)
{
	long kilo = 1024;
	long mega = kilo * kilo;
	long giga = mega * kilo;
	size_t len = SPRINT_BSIZE - 1;
	double tmp = sz;

	if (sz >= giga && fabs(giga * rint(tmp / giga) - sz) < 1024)
		snprintf(buf, len, "%gGb", rint(tmp / giga));
	else 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, "%llub", sz);

	return buf;
}

int print_color_size(enum output_type type, enum color_attr color,
		     const char *key, const char *fmt, __u64 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);
}