membuf: Add a function to set up a static membuf

Add a way to set up a membuf with some pre-loaded data, so it is
possible to read it out using membuf_readline(), etc.

Signed-off-by: Simon Glass <sjg@chromium.org>
This commit is contained in:
Simon Glass
2025-08-28 14:22:29 -06:00
parent f3005834f6
commit 05990c1bb8
3 changed files with 43 additions and 1 deletions

View File

@@ -222,7 +222,9 @@ int membuf_readline(struct membuf *mb, char *str, int maxlen, int minch,
int membuf_extend_by(struct membuf *mb, int by, int max);
/**
* membuf_init() - set up a new membuff using an existing membuff
* membuf_init() - set up a new membuff using an existing buffer
*
* The buffer is initially empty
*
* @mb: membuff to set up
* @buff: Address of buffer
@@ -230,6 +232,19 @@ int membuf_extend_by(struct membuf *mb, int by, int max);
*/
void membuf_init(struct membuf *mb, char *buff, int size);
/**
* membuf_init_with_data() - set up a new membuff using existing data
*
* The buffer is set up to contain the provided data. with its size set to
* @size + 1 (less MEMBUF_FULL), so that there is enough space for the head/tail
* differece.
*
* @mb: membuff to set up
* @buff: Address of buffer
* @size: Number of bytes to put into the membuf
*/
void membuf_init_with_data(struct membuf *mb, char *buff, int size);
/**
* membuf_uninit() - clear a membuff so it can no longer be used
*

View File

@@ -405,6 +405,14 @@ void membuf_init(struct membuf *mb, char *buff, int size)
membuf_purge(mb);
}
void membuf_init_with_data(struct membuf *mb, char *buff, int size)
{
char *data;
membuf_init(mb, buff, size + !MEMBUF_FULL);
membuf_putraw(mb, size, true, &data);
}
int membuf_new(struct membuf *mb, int size)
{
mb->start = malloc(size);

View File

@@ -242,3 +242,22 @@ static int lib_test_membuf_readline(struct unit_test_state *uts)
return 0;
}
LIB_TEST(lib_test_membuf_readline, 0);
/* test membuf_readline() with generated data */
static int lib_test_membuf_init(struct unit_test_state *uts)
{
struct membuf mb;
char buf[10], out[10];
int len;
strcpy(buf, "hello");
len = strlen(buf);
membuf_init_with_data(&mb, buf, len);
ut_asserteq_ptr(buf, mb.start);
ut_asserteq(len, membuf_avail(&mb));
ut_asserteq(len, membuf_readline(&mb, out, sizeof(out), 0, false));
ut_asserteq_str("hello", out);
return 0;
}
LIB_TEST(lib_test_membuf_init, 0);