-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathring_buffer.c
123 lines (97 loc) · 2.04 KB
/
ring_buffer.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
#include "ring_buffer.h"
// The definition of our circular buffer structure is hidden from the user
struct circular_buf_t {
char *buffer;
size_t head;
size_t tail;
size_t max; //of the buffer
bool full;
};
static void advance_pointer(cbuf_handle_t cbuf)
{
if(cbuf->full)
{
cbuf->tail = (cbuf->tail + 1) % cbuf->max;
}
cbuf->head = (cbuf->head + 1) % cbuf->max;
// We mark full because we will advance tail on the next time around
cbuf->full = (cbuf->head == cbuf->tail);
}
static void retreat_pointer(cbuf_handle_t cbuf)
{
cbuf->full = false;
cbuf->tail = (cbuf->tail + 1) % cbuf->max;
}
cbuf_handle_t circular_buf_init(char *buffer, size_t size)
{
cbuf_handle_t cbuf = kmalloc(sizeof(circular_buf_t), GFP_KERNEL);
cbuf->buffer = buffer;
cbuf->max = size;
circular_buf_reset(cbuf);
return cbuf;
}
void circular_buf_free(cbuf_handle_t cbuf)
{
kfree(cbuf);
}
void circular_buf_reset(cbuf_handle_t cbuf)
{
cbuf->head = 0;
cbuf->tail = 0;
cbuf->full = false;
}
size_t circular_buf_size(cbuf_handle_t cbuf)
{
size_t size = cbuf->max;
if(!cbuf->full)
{
if(cbuf->head >= cbuf->tail)
{
size = (cbuf->head - cbuf->tail);
}
else
{
size = (cbuf->max + cbuf->head - cbuf->tail);
}
}
return size;
}
size_t circular_buf_capacity(cbuf_handle_t cbuf)
{
return cbuf->max;
}
void circular_buf_put(cbuf_handle_t cbuf, char data)
{
cbuf->buffer[cbuf->head] = data;
advance_pointer(cbuf);
}
int circular_buf_put2(cbuf_handle_t cbuf, char data)
{
int r = -1;
if(!circular_buf_full(cbuf))
{
cbuf->buffer[cbuf->head] = data;
advance_pointer(cbuf);
r = 0;
}
return r;
}
int circular_buf_get(cbuf_handle_t cbuf, char *data)
{
int r = -1;
if(!circular_buf_empty(cbuf))
{
*data = cbuf->buffer[cbuf->tail];
retreat_pointer(cbuf);
r = 0;
}
return r;
}
bool circular_buf_empty(cbuf_handle_t cbuf)
{
return (!cbuf->full && (cbuf->head == cbuf->tail));
}
bool circular_buf_full(cbuf_handle_t cbuf)
{
return cbuf->full;
}