diff options
author | Peter Xu <peterx@redhat.com> | 2017-05-12 12:17:40 +0800 |
---|---|---|
committer | Dr. David Alan Gilbert <dgilbert@redhat.com> | 2017-05-17 17:30:45 +0100 |
commit | 22951aaaebb6c4c314c58ad576960a9c57695bbc (patch) | |
tree | f1071715f4dbec35fdeca1703eaf6fb5815ebb74 /util | |
parent | 99e15582dea30d4a7c6fa5be9196d0f4d759231c (diff) |
utils: provide size_to_str()
Moving the algorithm from print_type_size() into size_to_str() so that
other component can also leverage it. With that, refactor
print_type_size().
The assert() in that logic is removed though, since even UINT64_MAX
would not overflow.
Signed-off-by: Peter Xu <peterx@redhat.com>
Message-Id: <1494562661-9063-3-git-send-email-peterx@redhat.com>
Reviewed-by: Markus Armbruster <armbru@redhat.com>
Signed-off-by: Dr. David Alan Gilbert <dgilbert@redhat.com>
Diffstat (limited to 'util')
-rw-r--r-- | util/cutils.c | 25 |
1 files changed, 25 insertions, 0 deletions
diff --git a/util/cutils.c b/util/cutils.c index 50ad179dc5..1534682083 100644 --- a/util/cutils.c +++ b/util/cutils.c @@ -619,3 +619,28 @@ const char *qemu_ether_ntoa(const MACAddr *mac) return ret; } + +/* + * Return human readable string for size @val. + * @val can be anything that uint64_t allows (no more than "16 EiB"). + * Use IEC binary units like KiB, MiB, and so forth. + * Caller is responsible for passing it to g_free(). + */ +char *size_to_str(uint64_t val) +{ + static const char *suffixes[] = { "", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei" }; + unsigned long div; + int i; + + /* + * The exponent (returned in i) minus one gives us + * floor(log2(val * 1024 / 1000). The correction makes us + * switch to the higher power when the integer part is >= 1000. + * (see e41b509d68afb1f for more info) + */ + frexp(val / (1000.0 / 1024.0), &i); + i = (i - 1) / 10; + div = 1ULL << (i * 10); + + return g_strdup_printf("%0.3g %sB", (double)val / div, suffixes[i]); +} |