view src/ring_buffer.c @ 9:abdba37f67a2

Red-black tree in progress. Linked list needs iterators redone, also in progress. Sleepy.
author Eris Caffee <discordia@eldalin.com>
date Fri, 28 Sep 2012 03:08:25 -0500
parents 5af32066927f
children 68f85ffc6029
line source
1 #include <stdlib.h>
2 #include <errno.h>
4 #include "ring_buffer.h"
6 struct ring_buffer
7 {
8 void ** data;
9 size_t max;
10 size_t start;
11 size_t count;
12 };
14 ////////////////////////////////////////////////////////////////////////////////
15 struct ring_buffer * ring_buffer_new(size_t const max)
16 {
17 if (max < 1)
18 {
19 errno = EINVAL;
20 return NULL;
21 }
23 struct ring_buffer * rb = malloc(sizeof(struct ring_buffer));
24 if (NULL == rb)
25 return NULL;
27 rb->start = rb->count = 0;
28 rb->max = max;
30 rb->data = calloc(rb->max, sizeof(void *));
31 if (NULL == rb->data)
32 {
33 free(rb);
34 return NULL;
35 }
37 return rb;
38 }
40 ////////////////////////////////////////////////////////////////////////////////
41 // Returns:
42 // NULL on error
43 // elem on success and the buffer is not full
44 // the overwritten element on success if the buffer was full
45 void * ring_buffer_write(struct ring_buffer * rb, void * elem)
46 {
47 if ((NULL == rb) || (NULL == elem))
48 {
49 errno = EINVAL;
50 return NULL;
51 }
53 size_t end = rb->start + rb->count;
54 void * ret = rb->data[end % rb->max];
55 rb->data[end % rb->max] = elem;
56 if (rb->count == rb->max)
57 rb->start = (rb->start + 1) % rb->max;
58 else
59 {
60 rb->count++;
61 ret = elem;
62 }
64 return ret;
65 }
67 ////////////////////////////////////////////////////////////////////////////////
68 void * ring_buffer_read(struct ring_buffer * rb)
69 {
70 if (NULL == rb)
71 {
72 errno = EINVAL;
73 return NULL;
74 }
76 if (0 == rb->count)
77 return NULL;
79 void * t = rb->data[rb->start];
80 rb->count--;
81 rb->start = (rb->start + 1) % rb->max;
83 return t;
84 }
86 ////////////////////////////////////////////////////////////////////////////////
87 size_t ring_buffer_size(struct ring_buffer * rb)
88 {
89 if (NULL == rb)
90 {
91 errno = EINVAL;
92 return -1;
93 }
95 return rb->count;
96 }
98 ////////////////////////////////////////////////////////////////////////////////
99 void ring_buffer_delete(struct ring_buffer * rb)
100 {
101 if (NULL != rb) free(rb->data);
102 free(rb);
103 }