Mercurial > hg > th-libs
changeset 23:a4f894105953
Add ringbuffer implementation.
author | Matti Hamalainen <ccr@tnsp.org> |
---|---|
date | Thu, 09 Jun 2011 17:33:18 +0300 |
parents | 1ac2449c4df7 |
children | f7a509f96a5d |
files | th_util.c th_util.h |
diffstat | 2 files changed, 62 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
--- a/th_util.c Sun May 22 02:11:05 2011 +0300 +++ b/th_util.c Thu Jun 09 17:33:18 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 Sun May 22 02:11:05 2011 +0300 +++ b/th_util.h Thu Jun 09 17:33:18 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