ustream: add function ustream_read().
authorYousong Zhou <yszhou4tech@gmail.com>
Wed, 21 Jan 2015 13:21:25 +0000 (21:21 +0800)
committerFelix Fietkau <nbd@openwrt.org>
Wed, 21 Jan 2015 19:00:39 +0000 (20:00 +0100)
It can be used to fill caller-specified buffer with data already in
ustream read buffer.  Useful in the following use pattern.

int available = ustream_pending_data(s, false);
if (available >= sizeof(struct msghdr)) {
struct msghdr h;
ustream_read(s, &h, sizeof(h));
}

Signed-off-by: Yousong Zhou <yszhou4tech@gmail.com>
ustream.c
ustream.h

index 828a025..fc93bc2 100644 (file)
--- a/ustream.c
+++ b/ustream.c
@@ -333,6 +333,26 @@ char *ustream_get_read_buf(struct ustream *s, int *buflen)
        return data;
 }
 
        return data;
 }
 
+int ustream_read(struct ustream *s, char *buf, int buflen)
+{
+       char *chunk;
+       int chunk_len;
+       int len = 0;
+
+       do {
+               chunk = ustream_get_read_buf(s, &chunk_len);
+               if (!chunk)
+                       break;
+               if (chunk_len > buflen - len)
+                       chunk_len = buflen - len;
+               memcpy(buf + len, chunk, chunk_len);
+               ustream_consume(s, chunk_len);
+               len += chunk_len;
+       } while (len < buflen);
+
+       return len;
+}
+
 static void ustream_write_error(struct ustream *s)
 {
        if (!s->write_error)
 static void ustream_write_error(struct ustream *s)
 {
        if (!s->write_error)
index 6431744..53e0828 100644 (file)
--- a/ustream.h
+++ b/ustream.h
@@ -143,6 +143,11 @@ void ustream_free(struct ustream *s);
 /* ustream_consume: remove data from the head of the read buffer */
 void ustream_consume(struct ustream *s, int len);
 
 /* ustream_consume: remove data from the head of the read buffer */
 void ustream_consume(struct ustream *s, int len);
 
+/*
+ * ustream_read: read and consume data in read buffer into caller-specified
+ * area.  Return length of data read.
+ */
+int ustream_read(struct ustream *s, char *buf, int buflen);
 /* ustream_write: add data to the write buffer */
 int ustream_write(struct ustream *s, const char *buf, int len, bool more);
 int ustream_printf(struct ustream *s, const char *format, ...);
 /* ustream_write: add data to the write buffer */
 int ustream_write(struct ustream *s, const char *buf, int len, bool more);
 int ustream_printf(struct ustream *s, const char *format, ...);