-
Notifications
You must be signed in to change notification settings - Fork 6
/
RingBuffer.h
145 lines (119 loc) · 1.91 KB
/
RingBuffer.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#ifndef RINGBUFFER_H
#define RINGBUFFER_H
#include <memory.h>
template<typename T>
class RingBuffer
{
public:
RingBuffer(int size) : Buffer(NULL), Size(0), Start(0), End(0) { Resize(size); }
~RingBuffer() { delete[] Buffer; }
int Capacity();
int Used();
int Available();
void Resize(int newSize);
void Write(T* src, int count);
void Read(T* dst, int count);
protected:
T* Buffer;
int Size;
int Start;
int End;
int used;
};
template<typename T>
void RingBuffer<T>::Resize(int newSize)
{
if (Buffer)
{
delete[] Buffer;
}
Size = newSize + 1;
Buffer = new T[Size];
Start = 0;
End = 0;
used = 0;
}
template<typename T>
int RingBuffer<T>::Capacity()
{
return Size - 1;
}
template<typename T>
int RingBuffer<T>::Available()
{
return Size - 1 - used;
}
template<typename T>
int RingBuffer<T>::Used()
{
return used;
}
template<typename T>
void RingBuffer<T>::Write(T* src, int count)
{
int startAvail = Available();
int startUsed = Used();
int bufferSize = Available();
if (bufferSize == 0)
{
return;
}
if (count > bufferSize)
{
count = bufferSize;
}
if (End == Capacity())
{
End = 0;
}
if (End + count > Size - 1)
{
int num = Size - End - 1;
memcpy(Buffer + End, src, num * sizeof(T));
End = 0;
count -= num;
src += num;
used += num;
}
memcpy(Buffer + End, src, count * sizeof(T));
End += count;
used += count;
if (End == Size)
{
End = 0;
}
}
template<typename T>
void RingBuffer<T>::Read(T* dst, int count)
{
int bufferSize = Used();
if (bufferSize == 0)
{
return;
}
if (count > bufferSize)
{
count = bufferSize;
}
if (Start == Capacity())
{
Start = 0;
}
if (Start + count > Size - 1)
{
int num = Size - Start - 1;
memcpy(dst, Buffer + Start, num * sizeof(T));
Start = 0;
count -= num;
dst += num;
used -= num;
}
memcpy(dst, Buffer + Start, count * sizeof(T));
Start += count;
used -= count;
if (Start == Size)
{
Start = 0;
}
}
#endif