Mercurial > hg > nnchat
diff th_util.c @ 276:1807059fb8f2
Move ringbuffer implementation.
author | Matti Hamalainen <ccr@tnsp.org> |
---|---|
date | Thu, 09 Jun 2011 11:37:34 +0300 |
parents | 4ec36204d34e |
children | 8ae649a4b738 |
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; + } +} + +