# HG changeset patch # User Matti Hamalainen # Date 1307608654 -10800 # Node ID 1807059fb8f29b793126f13c8b2abadafddd0dc6 # Parent 66b90d71548b31129da86627fe0d007da847d5a6 Move ringbuffer implementation. diff -r 66b90d71548b -r 1807059fb8f2 th_util.c --- 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; + } +} + + diff -r 66b90d71548b -r 1807059fb8f2 th_util.h --- 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