-
Notifications
You must be signed in to change notification settings - Fork 4
/
CircularBuffer.c
68 lines (56 loc) · 1.45 KB
/
CircularBuffer.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
/*
* CircularBuffer.c
*
* Created on: Dec 15, 2012
* Author: jon
*/
#include "CircularBuffer.h"
int CircularBufferWrite(CircularBuffer *c, unsigned char *dataIn, unsigned int length){
if (c->size >= (c->length + length)){
// buffer won't overflow
if ((c->head + length >= c->size)){
// rollover
int bytesToLast = c->size - c->head;
int bytesRemainder = length - bytesToLast;
memcpy(c->buffer+c->head, dataIn, bytesToLast);
memcpy(c->buffer, dataIn+bytesToLast, bytesRemainder);
c->head = bytesRemainder;
c->length += length;
}
else {
// no rollover
memcpy(c->buffer+c->head, dataIn, length);
c->head += length;
c->length += length;
}
return length;
}
else {
// buffer would overflow
return 0; // TODO: could just write whatever is left of the buffer and return that
}
}
int CircularBufferRead(CircularBuffer *c, unsigned char *dataOut, unsigned int length){
if (c->length >= length){
if ((c->tail + length >= c->size)){
// rollover
int bytesToLast = c->size - c->tail;
int bytesRemainder = length - bytesToLast;
memcpy(dataOut, c->buffer+c->tail, bytesToLast);
memcpy(dataOut+bytesToLast, c->buffer, bytesRemainder);
c->tail = bytesRemainder;
c->length -= length;
}
else {
// no rollover
memcpy(dataOut, c->buffer+c->tail, length);
c->tail += length;
c->length -= length;
}
return length;
}
else {
// want to read more bytes than there are
return 0;
}
}