print_size() formats a size with a binary unit, but can only write
it to the console. Move the formatting into a new snprint_size()
helper which writes to a buffer and let print_size() use it, so that
callers which build up a string, e.g. a boot menu entry, can present
sizes the same way as the console output does.

Signed-off-by: Padmarao Begari <[email protected]>
---
Changes in v2:
- New patch, replaces the open-coded unit selection of the v1 patch.
---
 include/display_options.h | 18 ++++++++++++++++++
 lib/display_options.c     | 22 ++++++++++++++--------
 2 files changed, 32 insertions(+), 8 deletions(-)

diff --git a/include/display_options.h b/include/display_options.h
index 66e59607737..2baf6859917 100644
--- a/include/display_options.h
+++ b/include/display_options.h
@@ -11,6 +11,24 @@
 
 #include <linux/types.h>
 
+/* Maximum length of a string produced by snprint_size(), including the NUL */
+#define SIZE_STR_LEN   32
+
+/**
+ * snprint_size() - Write a size with a unit to a buffer
+ *
+ * Format sizes as "xxx KiB", "xxx.y KiB", "xxx MiB", "xxx.y MiB",
+ * xxx GiB, xxx.y GiB, etc as needed. Sizes below 1 KiB are formatted as
+ * "xxx Bytes".
+ *
+ * @buf:       Buffer to write to
+ * @bufsize:   Size of @buf in bytes
+ * @size:      Size to format
+ * Return:     number of characters which would be written if @buf were large
+ *             enough, not counting the terminating NUL (as with snprintf())
+ */
+int snprint_size(char *buf, size_t bufsize, uint64_t size);
+
 /**
  * print_size() - Print a size with a suffix
  *
diff --git a/lib/display_options.c b/lib/display_options.c
index 2c15cc5b5c4..287eb247061 100644
--- a/lib/display_options.c
+++ b/lib/display_options.c
@@ -93,7 +93,7 @@ void print_freq(uint64_t freq, const char *s)
        printf(" %cHz%s", c, s);
 }
 
-void print_size(uint64_t size, const char *s)
+int snprint_size(char *buf, size_t bufsize, uint64_t size)
 {
        unsigned long m = 0, n;
        uint64_t f;
@@ -115,8 +115,7 @@ void print_size(uint64_t size, const char *s)
                 * We have just checked that the size is small enought to fit
                 * unsigned int safely.
                 */
-               printf("%u Bytes%s", (unsigned int)size, s);
-               return;
+               return snprintf(buf, bufsize, "%u Bytes", (unsigned int)size);
        }
 
        n = size >> d;
@@ -138,11 +137,18 @@ void print_size(uint64_t size, const char *s)
                }
        }
 
-       printf ("%lu", n);
-       if (m) {
-               printf (".%ld", m);
-       }
-       printf (" %ciB%s", c, s);
+       if (m)
+               return snprintf(buf, bufsize, "%lu.%ld %ciB", n, m, c);
+
+       return snprintf(buf, bufsize, "%lu %ciB", n, c);
+}
+
+void print_size(uint64_t size, const char *s)
+{
+       char buf[SIZE_STR_LEN];
+
+       snprint_size(buf, sizeof(buf), size);
+       printf("%s%s", buf, s);
 }
 
 #define MAX_LINE_LENGTH_BYTES          64
-- 
2.34.1

Reply via email to