string_get_size() rounds the fractional part before formatting the
result. If that carry pushes the integer part to the unit divisor, the
value is still printed in the old unit.
This yields outputs like "1000 kB" for 999500 bytes and "1024 KiB" for
1048064 bytes instead of promoting them to the next unit.
Renormalize the value after the carry so it is promoted before
formatting. Add KUnit coverage for the decimal and binary boundary
cases.
Fixes: 3c9f3681d0b4 ("[SCSI] lib: add generic helper to print sizes rounded to
the correct SI range")
Signed-off-by: Shuvam Pandey <[email protected]>
---
lib/string_helpers.c | 7 +++++++
lib/tests/string_helpers_kunit.c | 4 ++++
2 files changed, 11 insertions(+)
diff --git a/lib/string_helpers.c b/lib/string_helpers.c
index 169eaf583494..aa1ba47e28bd 100644
--- a/lib/string_helpers.c
+++ b/lib/string_helpers.c
@@ -121,6 +121,13 @@ int string_get_size(u64 size, u64 blk_size, const enum
string_size_units units,
size += 1;
}
+ if (size >= divisor[units_base]) {
+ size = 1;
+ remainder = 0;
+ i++;
+ j = 2;
+ }
+
if (j) {
snprintf(tmp, sizeof(tmp), ".%03u", remainder);
tmp[j+1] = '\0';
diff --git a/lib/tests/string_helpers_kunit.c b/lib/tests/string_helpers_kunit.c
index c853046183d2..16118fb16c9a 100644
--- a/lib/tests/string_helpers_kunit.c
+++ b/lib/tests/string_helpers_kunit.c
@@ -558,6 +558,10 @@ static void test_get_size(struct kunit *test)
/* weird block sizes */
test_string_get_size_one(3000, 1900, "5.70 MB", "5.44 MiB");
+ /* rounding carry into the next unit */
+ test_string_get_size_one(999500, 1, "1.00 MB", "976 KiB");
+ test_string_get_size_one(1048064, 1, "1.05 MB", "1.00 MiB");
+
/* huge values */
test_string_get_size_one(U64_MAX, 4096, "75.6 ZB", "64.0 ZiB");
test_string_get_size_one(4096, U64_MAX, "75.6 ZB", "64.0 ZiB");
--
2.50.0