-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathring_buff.c
61 lines (52 loc) · 1.25 KB
/
ring_buff.c
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
/*
Ring buffer with atomic operations
*/
#include "ring_buff.h"
void RingBuffer_Init(RingBuffer_t *buffer, uint8_t *buffer_ptr, uint16_t sz)
{
buffer->size = sz;
buffer->buffer = buffer_ptr;
buffer->head = buffer->buffer;
buffer->tail = buffer->buffer;
}
uint8_t RingBuffer_Push(RingBuffer_t *buffer, uint8_t data)
{
*buffer->head = data;
uint8_t *head = buffer->head + 1;
if (head >= buffer->buffer + buffer->size) {
head -= buffer->size;
}
buffer->head = head;
return *buffer->head;
}
uint8_t RingBuffer_Pop(RingBuffer_t *buffer)
{
uint8_t byte = *buffer->tail;
uint8_t *tail = buffer->tail + 1;
if (tail >= buffer->buffer + buffer->size) {
tail -= buffer->size;
}
buffer->tail = tail;
return byte;
}
uint16_t RingBuffer_Available(RingBuffer_t *buffer)
{
uint8_t *tail = buffer->tail;
uint8_t *head = buffer->head;
uint16_t size = buffer->size;
if (tail == head) {
return 0;
} else if (tail < head) {
return head - tail;
} else {
return size - (tail - head);
}
}
uint8_t RingBuffer_Peek(RingBuffer_t *buffer)
{
return *buffer->tail;
}
void RingBuffer_Clear(RingBuffer_t *buffer)
{
buffer->head = buffer->tail = buffer->buffer;
}