forked from AsahiLinux/m1n1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ringbuffer.c
81 lines (62 loc) · 1.41 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
#include "ringbuffer.h"
#include "malloc.h"
#include "types.h"
ringbuffer_t *ringbuffer_alloc(size_t len)
{
ringbuffer_t *bfr = calloc(1, sizeof(*bfr));
if (!bfr)
return NULL;
bfr->buffer = calloc(len, 1);
if (!bfr->buffer) {
free(bfr);
return NULL;
}
bfr->read = 0;
bfr->write = 0;
bfr->len = len;
return bfr;
}
void ringbuffer_free(ringbuffer_t *bfr)
{
if (bfr)
free(bfr->buffer);
free(bfr);
}
size_t ringbuffer_read(u8 *target, size_t len, ringbuffer_t *bfr)
{
size_t read;
for (read = 0; read < len; ++read) {
if (bfr->read == bfr->write)
break;
*target = bfr->buffer[bfr->read];
target++;
bfr->read++;
bfr->read %= bfr->len;
}
return read;
}
size_t ringbuffer_write(const u8 *src, size_t len, ringbuffer_t *bfr)
{
size_t written;
for (written = 0; written < len; ++written) {
if (((bfr->write + 1) % bfr->len) == bfr->read)
break;
bfr->buffer[bfr->write] = *src;
src++;
bfr->write++;
bfr->write %= bfr->len;
}
return written;
}
size_t ringbuffer_get_used(ringbuffer_t *bfr)
{
size_t read = bfr->read;
size_t write = bfr->write;
if (write < read)
write += bfr->len;
return write - read;
}
size_t ringbuffer_get_free(ringbuffer_t *bfr)
{
return bfr->len - ringbuffer_get_used(bfr);
}