lib/string_helpers: string_get_size() now returns characters wrote
authorKent Overstreet <kent.overstreet@gmail.com>
Mon, 25 Apr 2022 19:26:28 +0000 (15:26 -0400)
committerKent Overstreet <kent.overstreet@linux.dev>
Tue, 12 Sep 2023 03:59:47 +0000 (23:59 -0400)
printbuf now needs to know the number of characters that would have been
written if the buffer was too small, like snprintf(); this changes
string_get_size() to return the the return value of snprintf().

Signed-off-by: Kent Overstreet <kent.overstreet@linux.dev>
include/linux/string_helpers.h
lib/string_helpers.c

index 9d1f5bb74dd5002ce26d36d42d4fb147c0e6719e..58fb1f90eda519cf42b0ae8bc761e6c1611f4a96 100644 (file)
@@ -24,8 +24,8 @@ enum string_size_units {
        STRING_UNITS_2,         /* use binary powers of 2^10 */
 };
 
-void string_get_size(u64 size, u64 blk_size, enum string_size_units units,
-                    char *buf, int len);
+int string_get_size(u64 size, u64 blk_size, enum string_size_units units,
+                   char *buf, int len);
 
 int parse_int_array_user(const char __user *from, size_t count, int **array);
 
index 9982344cca34d6be6c0f3b7eeb4f1f08aa50fcdb..7713f73e66b0f35ba40966f78694f7d4d6326b42 100644 (file)
  * giving the size in the required units.  @buf should have room for
  * at least 9 bytes and will always be zero terminated.
  *
+ * Return value: number of characters of output that would have been written
+ * (which may be greater than len, if output was truncated).
  */
-void string_get_size(u64 size, u64 blk_size, const enum string_size_units units,
-                    char *buf, int len)
+int string_get_size(u64 size, u64 blk_size, const enum string_size_units units,
+                   char *buf, int len)
 {
        static const char *const units_10[] = {
                "B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"
@@ -126,8 +128,8 @@ void string_get_size(u64 size, u64 blk_size, const enum string_size_units units,
        else
                unit = units_str[units][i];
 
-       snprintf(buf, len, "%u%s %s", (u32)size,
-                tmp, unit);
+       return snprintf(buf, len, "%u%s %s", (u32)size,
+                       tmp, unit);
 }
 EXPORT_SYMBOL(string_get_size);