From e8ab09ac246806106a77a333246f42f3ce9ce835 Mon Sep 17 00:00:00 2001 From: Florian Pritz Date: Mon, 12 Sep 2011 16:32:43 +0200 Subject: rewrite format_bytes() This removes the dependency on math.h/libm and is easier to understand. Signed-off-by: Florian Pritz --- Makefile | 2 +- fb-helper.c.in | 30 ++++++++++++++++-------------- 2 files changed, 17 insertions(+), 15 deletions(-) diff --git a/Makefile b/Makefile index 5717ec8..b976361 100644 --- a/Makefile +++ b/Makefile @@ -17,7 +17,7 @@ fb: fb.in sed 's|@VERSION@|$(VERSION)|; s|@LIBDIR@|$(LIBDIR)|' $< > $@ fb-helper: fb-helper.c - $(CC) $(CFLAGS) -lcurl -lm -o $@ $< + $(CC) $(CFLAGS) -lcurl -o $@ $< fb.1: fb.pod pod2man -c "" $< $@ diff --git a/fb-helper.c.in b/fb-helper.c.in index d77b0b2..4a6ff28 100644 --- a/fb-helper.c.in +++ b/fb-helper.c.in @@ -16,11 +16,9 @@ #include #include #include -#include #include #include #include -#include #include #include @@ -66,23 +64,27 @@ int load_file(const char *fn, char **data, size_t *data_size) void format_bytes(double bytes, char *buf) { - double base = 0; + double size = bytes; int suffix_pos = 0; - char suffix[FORMAT_ARRAY_SIZE][4] = {"B", "KiB", "MiB", "GiB", "TiB"}; + static const char *suffix[] = {"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"}; + static const int suffix_count = sizeof(suffix) / sizeof(suffix[0]); + static const double boundary = 2048.0; - base = log(bytes) / log(1024); - suffix_pos = (int)floor(base); - - if (suffix_pos >= FORMAT_ARRAY_SIZE) - suffix_pos = FORMAT_ARRAY_SIZE-1; - - if (suffix_pos > 0) { - snprintf(buf, 64, "%.2f%s", pow(1024, base - suffix_pos), suffix[suffix_pos]); - } else { - snprintf(buf, 64, "%.2fB", bytes); + for(suffix_pos = 0; suffix_pos + 1 < suffix_count; suffix_pos++) { + if(size <= boundary && size >= -boundary) { + break; + } + size /= 1024.0; } + + // don't print decimals for bytes + if (suffix_pos != 0) + snprintf(buf, 64, "%.2f%s", size, suffix[suffix_pos]); + else + snprintf(buf, 64, "%.0f%s", size, suffix[suffix_pos]); } + int progress_callback(void *cb_data, double dltotal, double dlnow, double ultotal, double ulnow) -- cgit v1.2.3-24-g4f1b