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(-)
@@ -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
*
@@ -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);
@@ -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);