# HG changeset patch # User Matti Hamalainen # Date 1225241511 -7200 # Node ID 0bcc38910a773fc4ce7922ae452e27ba78aacca7 # Parent 4e3616709752b9c0e73a9910da1595d92ab67a27 Simple ringbuffer implementation. diff -r 4e3616709752 -r 0bcc38910a77 nnchat.c --- a/nnchat.c Wed Oct 29 02:51:35 2008 +0200 +++ b/nnchat.c Wed Oct 29 02:51:51 2008 +0200 @@ -19,12 +19,15 @@ #include #include + +#define SET_MAX_BACKBUF (1024) #define SET_MAX_HISTORY (16) #define SET_BUFSIZE (4096) #define SET_ALLOC_SIZE (128) #define SET_DELAY (15) #define SET_DELAY_USEC (SET_DELAY * 1000) + /* Options */ int optPort = 8005; @@ -152,6 +155,50 @@ return TRUE; } + +typedef struct { + char **data; + size_t n, size; +} ringbuf_t; + + +ringbuf_t * newRingBuf(const size_t size) +{ + ringbuf_t *res = th_calloc(1, sizeof(ringbuf_t)); + + res->data = (char **) th_malloc(size * sizeof(char *)); + res->size = size; + res->n = 0; + + return res; +} + + +void freeRingBuf(ringbuf_t *buf) +{ + size_t i; + + for (i = 0; i < buf->n; i++) + th_free(buf->data[i]); + + th_free(buf->data); + th_free(buf); +} + + +void addRingBuf(ringbuf_t *buf, const char *str) +{ + if (buf->n < buf->size) { + buf->data[buf->n] = th_strdup(str); + buf->n++; + } else { + th_free(buf->data[0]); + memmove(&(buf->data[0]), &(buf->data[1]), buf->size - 1); + buf->data[buf->size - 1] = th_strdup(str); + } +} + + typedef struct { ssize_t pos, len, size; char *data;