test: Add a way to printf() into a membuf

Add a membuf_printf() function which supports writing a formatted string
into a membuf.

Co-developed-by: Claude <noreply@anthropic.com>
Signed-off-by: Simon Glass <sjg@chromium.org>
This commit is contained in:
Simon Glass
2025-10-08 15:41:19 -06:00
parent dd4b6ad746
commit d387a08ee2
3 changed files with 67 additions and 0 deletions

View File

@@ -268,4 +268,17 @@ int membuf_new(struct membuf *mb, int size);
*/
void membuf_dispose(struct membuf *mb);
/**
* membuf_printf() - write a formatted string to a membuff
*
* Formats a string and writes it to the membuff. Returns the number of bytes
* written (not including the terminating nul).
*
* @mb: membuff to write to
* @fmt: format string
* @...: arguments for format string
* Return: number of bytes written, or negative error
*/
int membuf_printf(struct membuf *mb, const char *fmt, ...);
#endif

View File

@@ -9,6 +9,7 @@
#include <errno.h>
#include <log.h>
#include <malloc.h>
#include <vsprintf.h>
#include "membuf.h"
static inline bool is_full(const struct membuf *mb)
@@ -435,3 +436,16 @@ void membuf_dispose(struct membuf *mb)
free(mb->start);
membuf_uninit(mb);
}
int membuf_printf(struct membuf *mb, const char *fmt, ...)
{
char buf[256];
va_list args;
int len;
va_start(args, fmt);
len = vsnprintf(buf, sizeof(buf), fmt, args);
va_end(args);
return membuf_put(mb, buf, len);
}

View File

@@ -261,3 +261,43 @@ static int lib_test_membuf_init(struct unit_test_state *uts)
return 0;
}
LIB_TEST(lib_test_membuf_init, 0);
/* test membuf_printf() */
static int lib_test_membuf_printf(struct unit_test_state *uts)
{
struct membuf mb;
int ret, exp_len;
char buf[100];
char out[100];
/* Initialize membuf with a buffer */
membuf_init(&mb, buf, sizeof(buf));
/* Test simple string */
ret = membuf_printf(&mb, "Hello");
ut_asserteq(5, ret);
ut_asserteq(5, membuf_get(&mb, out, sizeof(out)));
out[5] = '\0';
ut_asserteq_str("Hello", out);
/* Test formatted string with integers */
exp_len = 9;
membuf_purge(&mb);
ret = membuf_printf(&mb, "Value: %d", 42);
ut_asserteq(exp_len, ret);
ut_asserteq(exp_len, membuf_get(&mb, out, sizeof(out)));
out[exp_len] = '\0';
ut_asserteq_str("Value: 42", out);
/* Test formatted string with multiple arguments */
membuf_purge(&mb);
exp_len = 10;
ret = membuf_printf(&mb, "x=%d y=%d", 10, 200);
ut_asserteq(exp_len, ret);
ut_asserteq(exp_len, membuf_get(&mb, out, sizeof(out)));
out[exp_len] = '\0';
ut_asserteq_str("x=10 y=200", out);
return 0;
}
LIB_TEST(lib_test_membuf_printf, 0);