lib: Add format_size() to format sizes as strings

Refactor print_size() to use a new format_size() helper that formats
a size into a buffer. This allows callers to get the formatted string
without printing it directly.

The format_size() function is only exported in U-Boot proper (controlled
by CONFIG_LIB_FORMAT_SIZE) to avoid code-size impact in SPL/TPL where it
remains static.

Co-developed-by: Claude <noreply@anthropic.com>
Signed-off-by: Simon Glass <simon.glass@canonical.com>
This commit is contained in:
Simon Glass
2025-11-28 09:22:20 -07:00
parent 69d2f4ab58
commit bf72ede55e
4 changed files with 59 additions and 10 deletions

View File

@@ -68,3 +68,17 @@ static int lib_test_print_size(struct unit_test_state *uts)
return 0;
}
LIB_TEST(lib_test_print_size, UTF_CONSOLE);
static int lib_test_format_size(struct unit_test_state *uts)
{
char buf[12];
ut_asserteq_str("321 Bytes", format_size(buf, 321));
ut_asserteq_str("4.2 KiB", format_size(buf, 4321));
ut_asserteq_str("53 KiB", format_size(buf, 54321));
ut_asserteq_str("1 GiB", format_size(buf, 1073741824));
ut_asserteq_str("49.4 TiB", format_size(buf, 54321987654321));
return 0;
}
LIB_TEST(lib_test_format_size, 0);