
From: Simon Glass <sjg@chromium.org> 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> --- include/membuf.h | 17 ++++++++++++++++- lib/membuf.c | 8 ++++++++ test/lib/membuf.c | 19 +++++++++++++++++++ 3 files changed, 43 insertions(+), 1 deletion(-) diff --git a/include/membuf.h b/include/membuf.h index b495a72652b..3352faa0606 100644 --- a/include/membuf.h +++ b/include/membuf.h @@ -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 * diff --git a/lib/membuf.c b/lib/membuf.c index 016430ae988..47a1b06664a 100644 --- a/lib/membuf.c +++ b/lib/membuf.c @@ -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); diff --git a/test/lib/membuf.c b/test/lib/membuf.c index f36332ff7b6..2e7de9cdc57 100644 --- a/test/lib/membuf.c +++ b/test/lib/membuf.c @@ -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); -- 2.43.0