From: Joel Rosdahl Date: Mon, 18 Jul 2011 10:22:08 +0000 (+0200) Subject: Add utility function format_parsable_size_with_suffix X-Git-Tag: v3.2~206 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=f080f3cc68146bacdad1ce7cb446de5fd529f5e1;p=thirdparty%2Fccache.git Add utility function format_parsable_size_with_suffix --- diff --git a/ccache.h b/ccache.h index d0f083387..3d72b38a9 100644 --- a/ccache.h +++ b/ccache.h @@ -128,7 +128,8 @@ const char *get_extension(const char *path); char *remove_extension(const char *path); size_t file_size(struct stat *st); int safe_create_wronly(const char *fname); -char *format_human_readable_size(size_t v); +char *format_human_readable_size(size_t size); +char *format_parsable_size_with_suffix(size_t size); bool parse_size_with_suffix(const char *str, size_t *size); char *x_realpath(const char *path); char *gnu_getcwd(void); diff --git a/test/test_util.c b/test/test_util.c index 3a73bf876..3e1c86af3 100644 --- a/test/test_util.c +++ b/test/test_util.c @@ -106,4 +106,18 @@ TEST(format_human_readable_size) format_human_readable_size(17.11 * 1024 * 1024)); } +TEST(format_parsable_size_with_suffix) +{ + CHECK_STR_EQ_FREE2("0", format_parsable_size_with_suffix(0)); + CHECK_STR_EQ_FREE2("42K", format_parsable_size_with_suffix(42)); + CHECK_STR_EQ_FREE2("1.0M", format_parsable_size_with_suffix(1024)); + CHECK_STR_EQ_FREE2("1.2M", format_parsable_size_with_suffix(1234)); + CHECK_STR_EQ_FREE2("438.5M", + format_parsable_size_with_suffix(438.5 * 1024)); + CHECK_STR_EQ_FREE2("1.0G", + format_parsable_size_with_suffix(1024 * 1024)); + CHECK_STR_EQ_FREE2("17.1G", + format_parsable_size_with_suffix(17.11 * 1024 * 1024)); +} + TEST_SUITE_END diff --git a/util.c b/util.c index 313bd6ac1..e91e86124 100644 --- a/util.c +++ b/util.c @@ -830,6 +830,23 @@ format_human_readable_size(size_t v) return s; } +/* Format a size (in KiB) as a human-readable string. Caller frees. */ +char * +format_parsable_size_with_suffix(size_t size) +{ + char *s; + if (size >= 1024*1024) { + s = format("%.1fG", size / ((double)(1024*1024))); + } else if (size >= 1024) { + s = format("%.1fM", size / ((double)(1024))); + } else if (size > 0) { + s = format("%.0fK", (double)size); + } else { + s = x_strdup("0"); + } + return s; +} + /* * Parse a value in multiples of 1024 given a string that can end in K, M or G. * Default suffix: G.