-
Notifications
You must be signed in to change notification settings - Fork 0
/
circ.c
70 lines (56 loc) · 1011 Bytes
/
circ.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
#include "circ.h"
#include <stdlib.h>
#include <string.h>
int circ_init(circ_buf_t *b, unsigned int len, unsigned int size)
{
b->buf = malloc((len + 1) * size);
if (!b->buf) {
return -1;
}
b->len = (len + 1);
b->size = size;
b->head = 0;
b->tail = 0;
b->count = 0;
return 0;
}
int circ_enq(circ_buf_t *b, const void *elm)
{
int head = (b->head + 1) % b->len;
if (head == b->tail) {
return -1;
}
memcpy(b->buf + b->head * b->size, elm, b->size);
b->head = head;
b->count++;
return 0;
}
int circ_deq(circ_buf_t *b, void *elm)
{
if (b->head == b->tail) {
return -1;
}
if (elm) {
memcpy(elm, &b->buf[b->tail * b->size], b->size);
}
b->tail = (b->tail + 1) % b->len;
b->count--;
return 0;
}
const void *circ_peek(circ_buf_t *b, int index)
{
if (index >= b->count)
return NULL;
int i = (b->head + index) % b->len;
return &b->buf[i * b->size];
}
unsigned int circ_cnt(circ_buf_t *b)
{
return b->count;
}
void circ_free(circ_buf_t *b)
{
if (b) {
free(b->buf);
}
}