-
-
Notifications
You must be signed in to change notification settings - Fork 67
/
Copy pathCircularByteBuffer.h
126 lines (107 loc) · 1.94 KB
/
CircularByteBuffer.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#ifndef __CIRCULARBYTEBUFFER_H_
#define __CIRCULARBYTEBUFFER_H_
//#define DEBUG_CBB(...) os_printf( __VA_ARGS__ )
#ifndef DEBUG_CBB
#define DEBUG_CBB(...)
#define NODEBUG_CBB
#endif
class CircularByteBuffer {
public:
CircularByteBuffer () {
data = NULL;
size = 0;
capacity = 0;
}
~CircularByteBuffer(){
if (data!=NULL)
free (data);
}
void clear ()
{
memset(data,0,capacity);
size = 0;
begin = 0;
end = 0;
}
void deallocate () {
if (data!=NULL) {
free (data);
data = NULL;
}
}
void init (long capacity) {
if (data!=NULL)
free (data);
data = (byte*) malloc (capacity);
size = 0;
begin = 0;
end = 0;
this->capacity = capacity;
}
long getSize () {
return size;
}
byte peek () {
return data[begin];
}
void push (byte b) {
if (size+1 == capacity) {
DEBUG_CBB ("buffer full");
return;
}
data[end] = b;
end = (end+1) % capacity;
size += 1;
}
byte pop () {
if (size == 0){
DEBUG_CBB ("buffer empty");
return 0;
}
byte ret = data[begin];
begin = (begin+1) % capacity;
size -= 1;
return ret;
}
void push (byte* b, long len){
if (size+len >= capacity) {
DEBUG_CBB ("buffer full");
return;
}
if ( (end + len) <= capacity ) {
memcpy ((void*)&data[end],b,len);
end += len;
} else {
long endSide = capacity - end;
memcpy ((void*)&data[end],b,endSide);
end = 0;
memcpy ((void*)&data[end],b+endSide,len-endSide);
end += len-endSide;
}
size += len;
}
byte* pop (byte* b, long len){
if ( (size - len) < 0 ) {
DEBUG_CBB ("buffer empty");
return NULL;
}
if ( (begin + len) <= capacity ) {
memcpy (b,(void*)&data[begin],len);
begin += len;
} else {
long endSide = capacity - begin;
memcpy (b,(void*)&data[begin],endSide);
begin = 0;
memcpy (b+endSide,(void*)&data[begin],len-endSide);
begin += len-endSide;
}
size -= len;
}
private:
byte* data;
long capacity;
long size;
long begin;
long end;
};
#endif