changeset 276:1807059fb8f2

Move ringbuffer implementation.
author Matti Hamalainen <ccr@tnsp.org>
date Thu, 09 Jun 2011 11:37:34 +0300
parents 66b90d71548b
children 2cff949abbc5
files th_util.c th_util.h
diffstat 2 files changed, 62 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/th_util.c	Fri Jun 03 15:16:52 2011 +0300
+++ b/th_util.c	Thu Jun 09 11:37:34 2011 +0300
@@ -394,3 +394,51 @@
 
     return NULL;
 }
+
+
+qringbuf_t * th_ringbuf_new(const size_t size, void (*mdeallocator)(void *data))
+{
+    qringbuf_t *res = th_calloc(1, sizeof(qringbuf_t));
+    
+    res->data = (void **) th_malloc(size * sizeof(void *));
+    res->size = size;
+    res->n = 0;
+    res->deallocator = mdeallocator;
+    
+    return res;
+}
+
+
+BOOL th_ringbuf_grow(qringbuf_t *buf, const size_t n)
+{
+    buf->size += n;
+    buf->data = (void **) th_realloc(buf->data, buf->size * sizeof(void *));
+    return (buf->data != NULL);
+}
+
+
+void th_ringbuf_free(qringbuf_t *buf)
+{
+    int i;
+    
+    for (i = 0; i < buf->n; i++)
+        buf->deallocator(buf->data[i]);
+    
+    th_free(buf->data);
+    th_free(buf);
+}
+
+
+void th_ringbuf_add(qringbuf_t *buf, void *ptr)
+{
+    if (buf->n < buf->size) {
+        buf->data[buf->n] = ptr;
+        buf->n++;
+    } else {
+        th_free(buf->data[0]);
+        memmove(&(buf->data[0]), &(buf->data[1]), buf->size - 1);
+        buf->data[buf->size - 1] = ptr;
+    }
+}
+
+
--- a/th_util.h	Fri Jun 03 15:16:52 2011 +0300
+++ b/th_util.h	Thu Jun 09 11:37:34 2011 +0300
@@ -111,6 +111,20 @@
 qlist_t * th_llist_find_func(qlist_t *list, const void *userdata, int (compare)(const void *, const void *));
 
 
+/* Ringbuffer implementation
+ */
+typedef struct {
+    void **data;
+    int n, size;
+    void (*deallocator)(void *);
+} qringbuf_t;
+
+qringbuf_t * th_ringbuf_new(const size_t size, void (*mdeallocator)(void *));
+BOOL        th_ringbuf_grow(qringbuf_t *buf, const size_t n);
+void        th_ringbuf_free(qringbuf_t *buf);
+void        th_ringbuf_add(qringbuf_t *buf, void *ptr);
+
+
 #ifdef __cplusplus
 }
 #endif