-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathring_buffer.c
More file actions
39 lines (30 loc) · 719 Bytes
/
ring_buffer.c
File metadata and controls
39 lines (30 loc) · 719 Bytes
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
#define BUF_SIZE 8
typedef struct {
int buffer[BUF_SIZE];
int head; // write index
int tail; // read index
} RingBuffer;
void init_buffer(RingBuffer *rb){
rb->head = 0;
rb->tail = 0;
}
int is_empty(RingBuffer *rb){
return rb->head == rb->tail;
}
int is_full(RingBuffer *rb){
return (((rb->head + 1) % BUF_SIZE) == rb->tail);
}
int enqueue(RingBuffer *rb, int data){
if(is_full(rb))
return 0;
rb->buffer[rb->head] = data;
rb->head = (rb->head + 1) % BUF_SIZE;
return 1;
}
int dequeue(RingBuffer *rb, int *data){
if(is_empty(rb))
return 0;
*data = rb->buffer[rb->tail];
rb->tail = (rb->tail + 1) % BUF_SIZE;
return 1;
}