[hackers] [slstatus] Refactor fmt_human() and fix a bug || Laslo Hunhold

From: <git_AT_suckless.org>
Date: Mon, 21 May 2018 20:29:26 +0200 (CEST)

commit ceb13206a4d9f410ab49c3824c487658c341d8c8
Author: Laslo Hunhold <dev_AT_frign.de>
AuthorDate: Mon May 21 20:08:56 2018 +0200
Commit: Aaron Marcher <me_AT_drkhsh.at>
CommitDate: Mon May 21 20:28:57 2018 +0200

    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.

diff --git a/util.c b/util.c
index fc8b72a..b412211 100644
--- a/util.c
+++ b/util.c
_AT_@ -89,21 +89,29 @@ bprintf(const char *fmt, ...)
 const char *
 fmt_human(size_t num, int base)
 {
- size_t i;
         double scaled;
- const char *siprefix[] = { "", "k", "M", "G", "T", "P", "E", "Z", "Y" };
- const char *iecprefix[] = { "", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei",
- "Zi", "Yi" };
- char *prefix[9];
-
- if (base == 1000) {
- memcpy(prefix, siprefix, sizeof(prefix));
- } else if (base == 1024) {
- memcpy(prefix, iecprefix, sizeof(prefix));
+ size_t i, prefixlen;
+ 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" };
+
+ switch (base) {
+ case 1000:
+ prefix = prefix_1000;
+ 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;
- for (i = 0; i < LEN(prefix) && scaled >= 1024; i++) {
+ for (i = 0; i < prefixlen && scaled >= base; i++) {
                 scaled /= base;
         }
 
diff --git a/util.h b/util.h
index faa1472..b474f88 100644
--- a/util.h
+++ b/util.h
_AT_@ -10,5 +10,5 @@ void die(const char *, ...);
 
 int esnprintf(char *str, size_t size, 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, ...);
Received on Mon May 21 2018 - 20:29:26 CEST

This archive was generated by hypermail 2.3.0 : Mon May 21 2018 - 20:36:36 CEST