view src/ring_buffer.c @ 10:68f85ffc6029

Finished rbtree. Reworked the iterators in list. Minor tweaks to others.
author Eris Caffee <discordia@eldalin.com>
date Fri, 28 Sep 2012 18:24:53 -0500
parents abdba37f67a2
children
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 *
16 ring_buffer_new(size_t const max)
17 {
18 if (max < 1)
19 return NULL;
21 struct ring_buffer * rb = malloc(sizeof(struct ring_buffer));
22 if (NULL == rb)
23 return NULL;
25 rb->start = rb->count = 0;
26 rb->max = max;
28 rb->data = calloc(rb->max, sizeof(void *));
29 if (NULL == rb->data)
30 {
31 free(rb);
32 return NULL;
33 }
35 return rb;
36 }
38 ////////////////////////////////////////////////////////////////////////////////
39 // Returns:
40 // NULL on error
41 // elem on success and the buffer is not full
42 // the overwritten element on success if the buffer was full
43 void *
44 ring_buffer_write(struct ring_buffer * rb, void * elem)
45 {
46 if ((NULL == rb) || (NULL == elem))
47 return NULL;
49 size_t end = rb->start + rb->count;
50 void * ret = rb->data[end % rb->max];
51 rb->data[end % rb->max] = elem;
52 if (rb->count == rb->max)
53 rb->start = (rb->start + 1) % rb->max;
54 else
55 {
56 rb->count++;
57 ret = elem;
58 }
60 return ret;
61 }
63 ////////////////////////////////////////////////////////////////////////////////
64 void *
65 ring_buffer_read(struct ring_buffer * rb)
66 {
67 if (NULL == rb)
68 return NULL;
70 if (0 == rb->count)
71 return NULL;
73 void * t = rb->data[rb->start];
74 rb->count--;
75 rb->start = (rb->start + 1) % rb->max;
77 return t;
78 }
80 ////////////////////////////////////////////////////////////////////////////////
81 size_t
82 ring_buffer_size(struct ring_buffer * rb)
83 {
84 if (NULL == rb)
85 return 0;
87 return rb->count;
88 }
90 ////////////////////////////////////////////////////////////////////////////////
91 void
92 ring_buffer_delete(struct ring_buffer * rb)
93 {
94 if (NULL != rb) free(rb->data);
95 free(rb);
96 }