summaryrefslogtreecommitdiff
path: root/toxcore
diff options
context:
space:
mode:
Diffstat (limited to 'toxcore')
-rw-r--r--toxcore/util.c73
-rw-r--r--toxcore/util.h10
2 files changed, 83 insertions, 0 deletions
diff --git a/toxcore/util.c b/toxcore/util.c
index 5a72c4a4..d6db946d 100644
--- a/toxcore/util.c
+++ b/toxcore/util.c
@@ -185,3 +185,76 @@ int create_recursive_mutex(pthread_mutex_t *mutex)
185 185
186 return 0; 186 return 0;
187} 187}
188
189
190struct RingBuffer {
191 uint16_t size; /* Max size */
192 uint16_t start;
193 uint16_t end;
194 void **data;
195};
196
197bool rb_full(const RingBuffer *b)
198{
199 return (b->end + 1) % b->size == b->start;
200}
201bool rb_empty(const RingBuffer *b)
202{
203 return b->end == b->start;
204}
205void* rb_write(RingBuffer *b, void *p)
206{
207 void* rc = NULL;
208 if ((b->end + 1) % b->size == b->start) /* full */
209 rc = b->data[b->start];
210
211 b->data[b->end] = p;
212 b->end = (b->end + 1) % b->size;
213
214 if (b->end == b->start)
215 b->start = (b->start + 1) % b->size;
216
217 return rc;
218}
219bool rb_read(RingBuffer *b, void **p)
220{
221 if (b->end == b->start) { /* Empty */
222 *p = NULL;
223 return false;
224 }
225
226 *p = b->data[b->start];
227 b->start = (b->start + 1) % b->size;
228 return true;
229}
230void rb_clear(RingBuffer *b)
231{
232 while (!rb_empty(b)) {
233 void *p;
234 rb_read(b, &p);
235 free(p);
236 }
237}
238RingBuffer *rb_new(int size)
239{
240 RingBuffer *buf = calloc(sizeof(RingBuffer), 1);
241
242 if (!buf) return NULL;
243
244 buf->size = size + 1; /* include empty elem */
245
246 if (!(buf->data = calloc(buf->size, sizeof(void *)))) {
247 free(buf);
248 return NULL;
249 }
250
251 return buf;
252}
253void rb_free(RingBuffer *b)
254{
255 if (b) {
256 rb_clear(b);
257 free(b->data);
258 free(b);
259 }
260} \ No newline at end of file
diff --git a/toxcore/util.h b/toxcore/util.h
index fab26e29..6c3d3b38 100644
--- a/toxcore/util.h
+++ b/toxcore/util.h
@@ -30,6 +30,7 @@
30#include <pthread.h> 30#include <pthread.h>
31 31
32#define MIN(a,b) (((a)<(b))?(a):(b)) 32#define MIN(a,b) (((a)<(b))?(a):(b))
33#define PAIR(TYPE1__, TYPE2__) struct { TYPE1__ first; TYPE2__ second; }
33 34
34void unix_time_update(); 35void unix_time_update();
35uint64_t unix_time(); 36uint64_t unix_time();
@@ -56,4 +57,13 @@ int load_state(load_state_callback_func load_state_callback, void *outer,
56/* Returns -1 if failed or 0 if success */ 57/* Returns -1 if failed or 0 if success */
57int create_recursive_mutex(pthread_mutex_t *mutex); 58int create_recursive_mutex(pthread_mutex_t *mutex);
58 59
60/* Ring buffer */
61typedef struct RingBuffer RingBuffer;
62bool rb_full(const RingBuffer *b);
63bool rb_empty(const RingBuffer *b);
64void* rb_write(RingBuffer* b, void* p);
65bool rb_read(RingBuffer* b, void** p);
66void rb_clear(RingBuffer *b);
67RingBuffer *rb_new(int size);
68void rb_free(RingBuffer *b);
59#endif /* __UTIL_H__ */ 69#endif /* __UTIL_H__ */