Refactor fmt_human() and fix a bug

It is not necessary to copy memory or anything. Just keep a pointer to
the active prefix-array and assign the length of the arrays to a
variable.

Make the code more readable by using a switch, be more strict when an
invalid base is passed to it and fix a small oversight in the bottom of
the code where the base 1024 was forgotten to generalized.
This commit is contained in:
Laslo Hunhold 2018-05-21 20:08:56 +02:00 committed by Aaron Marcher
parent 10dbc9543e
commit ceb13206a4
2 changed files with 19 additions and 11 deletions

26
util.c
View File

@ -89,21 +89,29 @@ bprintf(const char *fmt, ...)
const char * const char *
fmt_human(size_t num, int base) fmt_human(size_t num, int base)
{ {
size_t i;
double scaled; double scaled;
const char *siprefix[] = { "", "k", "M", "G", "T", "P", "E", "Z", "Y" }; size_t i, prefixlen;
const char *iecprefix[] = { "", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", const char **prefix;
const char *prefix_1000[] = { "", "k", "M", "G", "T", "P", "E", "Z", "Y" };
const char *prefix_1024[] = { "", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei",
"Zi", "Yi" }; "Zi", "Yi" };
char *prefix[9];
if (base == 1000) { switch (base) {
memcpy(prefix, siprefix, sizeof(prefix)); case 1000:
} else if (base == 1024) { prefix = prefix_1000;
memcpy(prefix, iecprefix, sizeof(prefix)); prefixlen = LEN(prefix_1000);
break;
case 1024:
prefix = prefix_1024;
prefixlen = LEN(prefix_1024);
break;
default:
warn("fmt_human: Invalid base");
return NULL;
} }
scaled = num; scaled = num;
for (i = 0; i < LEN(prefix) && scaled >= 1024; i++) { for (i = 0; i < prefixlen && scaled >= base; i++) {
scaled /= base; scaled /= base;
} }

2
util.h
View File

@ -10,5 +10,5 @@ void die(const char *, ...);
int esnprintf(char *str, size_t size, const char *fmt, ...); int esnprintf(char *str, size_t size, const char *fmt, ...);
const char *bprintf(const char *fmt, ...); const char *bprintf(const char *fmt, ...);
const char *fmt_human(size_t num, int iec); const char *fmt_human(size_t num, int base);
int pscanf(const char *path, const char *fmt, ...); int pscanf(const char *path, const char *fmt, ...);