-
Notifications
You must be signed in to change notification settings - Fork 9
/
tiny_ring_buffer.h
73 lines (62 loc) · 1.87 KB
/
tiny_ring_buffer.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*!
* @file
* @brief Ring/circular buffer. Usable as a FIFO queue for fixed-size elements.
*
* Can be used to pass data from the interrupt context to the non-interrupt
* context if the follow constraints hold:
* - `unsigned` is an atomic type
* - The interrupt context only calls `insert` and `count`
* - The non-interrupt context only calls `remove`, `at`, and `count`
* - The ring buffer is never allowed to get full
*/
#ifndef tiny_ring_buffer_h
#define tiny_ring_buffer_h
#include <stdbool.h>
typedef struct {
void* buffer;
unsigned element_size;
volatile unsigned head;
volatile unsigned tail;
unsigned capacity;
bool full;
} tiny_ring_buffer_t;
/*!
* Initializes the ring buffer.
*/
void tiny_ring_buffer_init(
tiny_ring_buffer_t* self,
void* buffer,
unsigned element_size,
unsigned element_count);
/*!
* The number of elements the ring buffer can hold.
*/
inline unsigned tiny_ring_buffer_capacity(tiny_ring_buffer_t* self)
{
return self->capacity;
}
/*!
* The number of elements currently stored in the ring buffer.
*/
unsigned tiny_ring_buffer_count(tiny_ring_buffer_t* self);
/*!
* Gets the element at the specified index. If the index is larger than
* the size then the element buffer will not be written.
*/
void tiny_ring_buffer_at(tiny_ring_buffer_t* self, unsigned index, void* element);
/*!
* Insert an element into the ring buffer. If the ring buffer is full,
* the oldest element will be overwritten.
*/
void tiny_ring_buffer_insert(tiny_ring_buffer_t* self, const void* element);
/*!
* Removes the oldest element from the ring buffer and writes it into the
* provided buffer. If the ring buffer is empty then the element will not
* be written.
*/
void tiny_ring_buffer_remove(tiny_ring_buffer_t* self, void* element);
/*!
* Removes all elements from the ring buffer.
*/
void tiny_ring_buffer_clear(tiny_ring_buffer_t* self);
#endif