diff options
| author | Simon Glass <[email protected]> | 2025-05-02 08:46:04 -0600 |
|---|---|---|
| committer | Simon Glass <[email protected]> | 2025-05-30 09:49:31 +0100 |
| commit | 4f4b9477f4476cd86ffd4219111065d610c5237a (patch) | |
| tree | 3daecd9ea2c917e972afba0969d30d79f0bbd35d /test/lib | |
| parent | d58cebbbc7617fbc45e604c883e8501a58d25e62 (diff) | |
abuf: Add a way to printf() into a buffer
It is useful to format a string into a buffer, with the sizing handled
automatically. Add a function for this.
Signed-off-by: Simon Glass <[email protected]>
Diffstat (limited to 'test/lib')
| -rw-r--r-- | test/lib/abuf.c | 61 |
1 files changed, 61 insertions, 0 deletions
diff --git a/test/lib/abuf.c b/test/lib/abuf.c index 96c77ed2379..97b128c01c0 100644 --- a/test/lib/abuf.c +++ b/test/lib/abuf.c @@ -463,3 +463,64 @@ static int lib_test_abuf_init_size(struct unit_test_state *uts) return 0; } LIB_TEST(lib_test_abuf_init_size, 0); + +/* Test abuf_printf() */ +static int lib_test_abuf_printf(struct unit_test_state *uts) +{ + struct abuf buf, fmt; + ulong start; + char *ptr; + + start = ut_check_free(); + + /* start with a fresh buffer */ + abuf_init(&buf); + + /* check handling of out-of-memory condition */ + malloc_enable_testing(0); + ut_asserteq(-ENOMEM, abuf_printf(&buf, "%s", "")); + malloc_enable_testing(1); + + ut_asserteq(0, abuf_printf(&buf, "%s", "")); + ut_asserteq(1, buf.size); + ut_asserteq(true, buf.alloced); + ut_asserteq_str("", buf.data); + + /* check expanding it, initially failing */ + ut_asserteq(-ENOMEM, abuf_printf(&buf, "%s", "testing")); + malloc_disable_testing(); + + ut_asserteq(7, abuf_printf(&buf, "%s", "testing")); + ut_asserteq(8, buf.size); + ut_asserteq_str("testing", buf.data); + + ut_asserteq(11, abuf_printf(&buf, "testing %d", 123)); + ut_asserteq(12, buf.size); + ut_asserteq_str("testing 123", buf.data); + + /* make it smaller; buffer should not shrink */ + ut_asserteq(9, abuf_printf(&buf, "test %d", 456)); + ut_asserteq(12, buf.size); + ut_asserteq_str("test 456", buf.data); + + /* test the maximum size */ + abuf_init(&fmt); + ut_assert(abuf_realloc(&fmt, 4100)); + memset(fmt.data, 'x', 4100); + ptr = fmt.data; + ptr[4096] = '\0'; + + /* we are allowed up to 4K including the terminator */ + ut_asserteq(-E2BIG, abuf_printf(&buf, "%s", ptr)); + ptr[4095] = '\0'; + ut_asserteq(4095, abuf_printf(&buf, "%s", ptr)); + + abuf_uninit(&fmt); + abuf_uninit(&buf); + + /* Check for memory leaks */ + ut_assertok(ut_check_delta(start)); + + return 0; +} +LIB_TEST(lib_test_abuf_printf, 0); |
