diff options
author | Florian Pritz <bluewind@xinu.at> | 2011-09-12 16:32:43 +0200 |
---|---|---|
committer | Florian Pritz <bluewind@xinu.at> | 2011-09-12 16:45:51 +0200 |
commit | e8ab09ac246806106a77a333246f42f3ce9ce835 (patch) | |
tree | c7aed3ed72480bcde139c3167d3db6296741f554 | |
parent | 4d14c5c1e28b5f0f99eb31a28a01976da7787c30 (diff) |
rewrite format_bytes()
This removes the dependency on math.h/libm and is easier to understand.
Signed-off-by: Florian Pritz <bluewind@xinu.at>
-rw-r--r-- | Makefile | 2 | ||||
-rw-r--r-- | fb-helper.c.in | 30 |
2 files changed, 17 insertions, 15 deletions
@@ -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 <stdio.h> #include <sys/time.h> #include <sys/stat.h> -#include <sys/mman.h> #include <libgen.h> #include <string.h> #include <stdlib.h> -#include <math.h> #include <curl/curl.h> #include <curl/easy.h> @@ -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) |