Browse Source

lib/stream: Add stream_discard, to discard read data from a stream

* stream.c: (stream_discard) Discard the already data from a stream, as
  indicated by the getp. Move remaining, unread data, to the beginning of
  the stream. get and end stream pointers are updated as appropriate.

  If all data has been consumed, then this behaves identically to
  stream_reset.
Paul Jakma 2 years ago
parent
commit
dc633bd183
2 changed files with 27 additions and 0 deletions
  1. 25 0
      lib/stream.c
  2. 2 0
      lib/stream.h

+ 25 - 0
lib/stream.c

@@ -960,6 +960,31 @@ stream_reset (struct stream *s)
   s->getp = s->endp = 0;
 }
 
+/* Discard read data (prior to the getp), and move the unread data
+ * to the beginning of the stream.
+ *
+ * See also stream_fifo_* functions, for another approach to managing
+ * streams.
+ */
+void
+stream_discard (struct stream *s)
+{
+  STREAM_VERIFY_SANE (s);
+  
+  if (s->getp == 0)
+    return;
+  
+  if (s->getp == s->endp)
+    {
+      stream_reset (s);
+      return;
+    }
+  
+  s->data = memmove (s->data, s->data + s->getp, s->endp - s->getp);
+  s->endp -= s->getp;
+  s->getp = 0;
+}
+
 /* Write stream contens to the file discriptor. */
 int
 stream_flush (struct stream *s, int fd)

+ 2 - 0
lib/stream.h

@@ -218,6 +218,8 @@ extern size_t stream_write (struct stream *, const void *, size_t);
 
 /* reset the stream. See Note above */
 extern void stream_reset (struct stream *);
+/* move unread data to start of stream, discarding read data */
+extern void stream_discard (struct stream *);
 extern int stream_flush (struct stream *, int);
 extern int stream_empty (struct stream *); /* is the stream empty? */