Blame lib/json_print_math.c

Packit Bot 867fae
// SPDX-License-Identifier: GPL-2.0+
Packit Bot 867fae
Packit Bot 867fae
#include <stdarg.h>
Packit Bot 867fae
#include <stdio.h>
Packit Bot 867fae
#include <math.h>
Packit Bot 867fae
Packit Bot 867fae
#include "utils.h"
Packit Bot 867fae
#include "json_print.h"
Packit Bot 867fae
Packit Bot 867fae
char *sprint_size(__u32 sz, char *buf)
Packit Bot 867fae
{
Packit Bot 867fae
	long kilo = 1024;
Packit Bot 867fae
	long mega = kilo * kilo;
Packit Bot 867fae
	size_t len = SPRINT_BSIZE - 1;
Packit Bot 867fae
	double tmp = sz;
Packit Bot 867fae
Packit Bot 867fae
	if (sz >= mega && fabs(mega * rint(tmp / mega) - sz) < 1024)
Packit Bot 867fae
		snprintf(buf, len, "%gMb", rint(tmp / mega));
Packit Bot 867fae
	else if (sz >= kilo && fabs(kilo * rint(tmp / kilo) - sz) < 16)
Packit Bot 867fae
		snprintf(buf, len, "%gKb", rint(tmp / kilo));
Packit Bot 867fae
	else
Packit Bot 867fae
		snprintf(buf, len, "%ub", sz);
Packit Bot 867fae
Packit Bot 867fae
	return buf;
Packit Bot 867fae
}
Packit Bot 867fae
Packit Bot 867fae
int print_color_size(enum output_type type, enum color_attr color,
Packit Bot 867fae
		     const char *key, const char *fmt, __u32 sz)
Packit Bot 867fae
{
Packit Bot 867fae
	SPRINT_BUF(buf);
Packit Bot 867fae
Packit Bot 867fae
	if (_IS_JSON_CONTEXT(type))
Packit Bot 867fae
		return print_color_uint(type, color, key, "%u", sz);
Packit Bot 867fae
Packit Bot 867fae
	sprint_size(sz, buf);
Packit Bot 867fae
	return print_color_string(type, color, key, fmt, buf);
Packit Bot 867fae
}