-
Notifications
You must be signed in to change notification settings - Fork 0
/
ringbuffer.c
136 lines (106 loc) · 2.64 KB
/
ringbuffer.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
/*
* ringbuffer.c
*
* Created on: Jul 19, 2018
* Author: fkyburz
*
* data in rbuf[head] is not valid (post imcrement)
* data in rbuf[tail] is valid
*
*/
//#include "ringbuffer.h"
#include "ringbuffer.h"
//#include "device.h"
int32_t ringbuffer_reset(ringbuffer_t * rbuf);
int32_t ringbuffer_put(ringbuffer_t * rbuf, uint16_t data);
int32_t ringbuffer_get(ringbuffer_t * rbuf, uint16_t * data);
int32_t ringbuffer_empty(ringbuffer_t * rbuf);
int32_t ringbuffer_full(ringbuffer_t * rbuf);
int32_t ringbuffer_reset(ringbuffer_t * rbuf)
{
int32_t status = -1;
if(rbuf)
{
rbuf->head = 0;
rbuf->tail = 0;
status = 0;
}
return status;
}
int32_t ringbuffer_empty(ringbuffer_t * rbuf)
{
// define empty as head == tail
return (rbuf->head == rbuf->tail);
}
int32_t ringbuffer_length(ringbuffer_t * rbuf)
{
int32_t status;
if (rbuf->head >= rbuf->tail)
{
status = ((int16_t)(rbuf->head) - (int16_t)(rbuf->tail));
}
else
{
status = (((int16_t)rbuf->size - (int16_t)rbuf->tail) +
(int16_t)rbuf->head);
}
return status;
}
int32_t ringbuffer_full(ringbuffer_t * rbuf)
{
// We determine "full" case by head being one position behind the tail
// Note that this means we are wasting one space in the buffer!
// Instead, you could have an "empty" flag and determine buffer full that way
return ((rbuf->head + 1) % rbuf->size) == rbuf->tail;
}
int32_t ringbuffer_put(ringbuffer_t * rbuf, uint16_t data)
{
int32_t status = -1;
if(rbuf)
{
rbuf->buffer[rbuf->head] = data;
rbuf->head = (rbuf->head + 1) % rbuf->size;
if(rbuf->head == rbuf->tail)
{
rbuf->tail = (rbuf->tail + 1) % rbuf->size;
}
status = 0;
}
return status;
}
int32_t ringbuffer_put_array(ringbuffer_t * rbuf, uint16_t * data, uint16_t size)
{
int32_t status = -1;
if (rbuf)
{
int i;
for(i = 0; i < size; i++)
{
ringbuffer_put(rbuf, data[i]);
}
status = 0;
}
return status;
}
// get one character
int32_t ringbuffer_get(ringbuffer_t * rbuf, uint16_t * data)
{
int32_t status = -1;
if(rbuf && data && !ringbuffer_empty(rbuf))
{
*data = rbuf->buffer[rbuf->tail];
rbuf->tail = (rbuf->tail + 1) % rbuf->size;
status = 0;
}
return status;
}
int32_t ringbuffer_data(ringbuffer_t * rbuf, uint16_t * data, uint16_t pos)
{
int32_t status = -1;
if (rbuf && data && !ringbuffer_empty(rbuf))
{
*data = rbuf->buffer[pos];
status = 0;
}
return status;
}