-
Notifications
You must be signed in to change notification settings - Fork 1
/
ring.h
78 lines (70 loc) · 1.8 KB
/
ring.h
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
/* Anthony Korzan
* October 4, 2012 */
#define BUFFER_LENGTH 256
struct ring {
int head;
int tail;
int data[BUFFER_LENGTH];
};
/* Allocates and returns a pointer to a ring buffer. If unable
to allocate returns NULL. */
struct ring* rb_create(void)
{
struct ring* rb = malloc(sizeof(struct ring));
/* Check malloc */
if (rb) {
/* Initialize */
rb->head = 0;
rb->tail = 1;
}
return rb;
}
/* Deallocates an entire ring buffer. */
void rb_delete(struct ring *rb)
{
free(rb);
}
/* Returns 0 if not empty and -1 if empty. */
int rb_isempty(struct ring *rb)
{
if (rb->tail == (rb->head + 1) % BUFFER_LENGTH)
return -1;
else
return 0;
}
/* Returns 0 if not full and -1 if full. */
int rb_isfull(struct ring *rb)
{
if (rb->tail == rb->head)
return -1;
else
return 0;
}
/* If the ring buer is non-full, this function inserts a value at tail-1, and advances the tail.
Returns -1 (logical true) if successful.
Returns 0 if NOT successful.
*/
int rb_enqueue(struct ring *rb, int value)
{
/* Check if full. */
if(rb_isfull(rb)) {
return 0;
} else {
rb->data[(rb->tail - 1 + BUFFER_LENGTH) % BUFFER_LENGTH] = value;
rb->tail = (rb->tail + 1) % BUFFER_LENGTH;
return -1;
}
}
/* Removes a value and advances a head. Returns a void*.
If empty, returns -1. */
int rb_dequeue(struct ring *rb)
{
/* Check if empty. */
if (rb_isempty(rb)) {
return -1;
} else {
int value = rb->data[rb->head];
rb->head = (rb->head + 1) % BUFFER_LENGTH;
return value;
}
}