-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcb.h
More file actions
63 lines (53 loc) · 1.01 KB
/
cb.h
File metadata and controls
63 lines (53 loc) · 1.01 KB
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
#include <stdlib.h>
#include <stdbool.h>
#define ERROR_SIGNAL 1
#define OK_SIGNAL 0
typedef unsigned uint;
typedef unsigned char byte;
typedef struct
{
byte* buffer;
uint read;
uint write;
size_t size;
} circular_buffer;
int init_circular_buffer(size_t size, circular_buffer* cb)
{
cb->read = 0;
cb->write = 0;
cb->buffer = (byte*) malloc(size);
cb->size = size;
if(cb->buffer == NULL)
return ERROR_SIGNAL;
return OK_SIGNAL;
}
int destroy_circular_buffer(circular_buffer* cb)
{
free(cb->buffer);
return 0;
}
int read_buffer(circular_buffer* cb, byte* out)
{
if(cb->read == cb->write)
return ERROR_SIGNAL;
*out = cb->buffer[cb->read];
cb->read++;
if(cb->read == cb->size)
cb->read = 0;
return OK_SIGNAL;
}
int write_buffer(circular_buffer* cb, char* word, size_t size)
{
for(size_t i = 0; i < size; i++)
{
cb->buffer[cb->write] = word[i];
cb->write++;
if(cb->write == cb->size)
cb->write = 0;
}
return OK_SIGNAL;
}
bool is_buffer_empty(circular_buffer* cb)
{
return cb->read==cb->write;
}