-
Notifications
You must be signed in to change notification settings - Fork 2
/
rbuff.c
52 lines (44 loc) · 858 Bytes
/
rbuff.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
/*ring buffer example*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "rbuff.h"
void rbuf_init(rbuf_t *b)
{
memset(&b->buf, 0, BUFSIZE);
b->pIn = b->pOut = b->buf;
b->pEnd = &b->buf[BUFSIZE];
b->len = 0;
}
int rbuf_is_full(rbuf_t *b)
{
return b->len == BUFSIZE;
}
int rbuf_is_empty(rbuf_t *b)
{
return b->len == 0;
}
int rbuf_put(rbuf_t *b, char c)
{
if (b->pIn == b->pOut && rbuf_is_full(b)) {
return 0;
}
*b->pIn++ = c;
b->len++;
if (b->pIn >= b->pEnd) {
b->pIn = b->buf;
}
return 1;
}
int rbuf_get(rbuf_t *b, char *pc)
{
if (b->pIn == b->pOut && rbuf_is_empty(b)) {
return 0;
}
*pc = *b->pOut++;
b->len--;
if (b->pOut >= b->pEnd) {
b->pOut = b->buf;
}
return 1;
}