-
Notifications
You must be signed in to change notification settings - Fork 0
/
circular_buffer.c
90 lines (77 loc) · 2.64 KB
/
circular_buffer.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include "circular_buffer.h"
enum circularBufferStatus circularBuffer_status(struct circularBuffer* cb) {
if(cb->head == cb->tail)
return circularBuffer_EMPTY;
if( (cb->head + 1) % cb->size == cb->tail)
return circularBuffer_FULL;
return circularBuffer_OK;
}
void circularBuffer_init(struct circularBuffer* cb, uint8_t* p_data, size_t size) {
cb->data = p_data;
cb->size = size;
cb->head = 0;
cb->tail = 0;
}
// return number of elements currently contained in circularBuffer
size_t circularBuffer_fill(struct circularBuffer* cb) {
if(cb->head >= cb->tail) {
return cb->head - cb->tail;
}
return cb->size - cb->tail + cb->head;
}
// return number of unused uint8_ts in the buffer
size_t circularBuffer_capacity(struct circularBuffer* cb) {
return cb->size - 1 - circularBuffer_fill(cb);
}
int circularBuffer_write(struct circularBuffer* cb, uint8_t* Buf, size_t l) {
for(size_t i = 0; i < l; ++i) {
circularBuffer_write_element(cb, Buf[i]);
}
return 1;
}
int circularBuffer_write_element( struct circularBuffer* cb, uint8_t c ) {
cb->data[cb->head] = c;
if(circularBuffer_status(cb) == circularBuffer_FULL)
cb->tail = (cb->tail + 1) % cb->size;
cb->head = (cb->head + 1) % cb->size;
return 1;
}
uint8_t circularBuffer_read_element( struct circularBuffer* cb ) {
if(circularBuffer_status(cb) == circularBuffer_EMPTY)
return 0;
uint8_t value = cb->data[cb->tail];
cb->tail = (cb->tail + 1) % cb->size;
return value;
}
int circularBuffer_read(struct circularBuffer* cb, uint8_t* Buf, size_t l) {
if(circularBuffer_fill(cb) < l) {
return 0;
}
for(size_t i = 0; i<l; i++) {
Buf[i] = circularBuffer_read_element(cb);
}
return 1;
}
// return an element in front of the tail (read pointer) without moving it
// if index>fill undefined values will be reported (fill needs to be checked)
uint8_t circularBuffer_peek(struct circularBuffer* cb, size_t index) {
return cb->data[(index + cb->tail) % cb->size];
}
void circularBuffer_delete_all( struct circularBuffer* cb) {
cb->tail = cb->head;
}
void circularBuffer_delete(struct circularBuffer* cb, size_t n){
if(n > circularBuffer_fill(cb)){
circularBuffer_delete_all(cb);
return;
}
cb->tail = (cb->tail + n) % cb->size;
}
uint8_t* circularBuffer_getHead( struct circularBuffer *cb ) {
return (uint8_t*)cb->data + cb->head;
}
void circularBuffer_incrementHead( struct circularBuffer *cb ) {
if(circularBuffer_status(cb) == circularBuffer_FULL)
cb->tail = (cb->tail + 1) % cb->size;
cb->head = (cb->head + 1) % cb->size;
}