aboutsummaryrefslogtreecommitdiff
path: root/src/ringbuffer.h
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--src/ringbuffer.h100
1 files changed, 100 insertions, 0 deletions
diff --git a/src/ringbuffer.h b/src/ringbuffer.h
new file mode 100644
index 0000000..9480043
--- /dev/null
+++ b/src/ringbuffer.h
@@ -0,0 +1,100 @@
1#ifndef RING_BUFFER_H
2#define RING_BUFFER_H
3
4#include <memory>
5#include "bu/exceptionbase.h"
6
7namespace Bu
8{
9 template<typename value, typename valuealloc=std::allocator<value> >
10 class RingBuffer
11 {
12 public:
13 RingBuffer( int nCapacity ) :
14 nCapacity( nCapacity ),
15 nStart( -1 ),
16 nEnd( -2 )
17 {
18 aData = va.allocate( nCapacity );
19 for( int j = 0; j < nCapacity; j++ )
20 {
21 va.construct( &aData[j], value() );
22 }
23 }
24
25 virtual ~RingBuffer()
26 {
27 for( int j = 0; j < nCapacity; j++ )
28 {
29 va.destroy( &aData[j] );
30 }
31 va.deallocate( aData, nCapacity );
32 }
33
34 int getCapacity()
35 {
36 return nCapacity;
37 }
38
39 bool isFilled()
40 {
41 return (nStart == nEnd);
42 }
43
44 bool isEmpty()
45 {
46 return (nStart == -1);
47 }
48
49 void enqueue( const value &v )
50 {
51 if( nStart == -1 )
52 {
53 nStart = 0;
54 nEnd = 1;
55 aData[0] = v;
56 }
57 else if( nStart == nEnd )
58 {
59 throw ExceptionBase("Hey, it's full!");
60 }
61 else
62 {
63 aData[nEnd] = v;
64 nEnd = (nEnd+1)%nCapacity;
65 }
66 }
67
68 value dequeue()
69 {
70 if( nStart == -1 )
71 {
72 throw ExceptionBase("No data");
73 }
74 else
75 {
76 value &v = aData[nStart];
77 nStart = (nStart+1)%nCapacity;
78 if( nStart == nEnd )
79 {
80 nStart = -1;
81 nEnd = -2;
82 }
83 return v;
84 }
85 }
86
87 value &operator[]( int nIndex )
88 {
89 return aData[(nIndex+nStart)%nCapacity];
90 }
91
92 private:
93 int nCapacity;
94 value *aData;
95 valuealloc va;
96 int nStart, nEnd;
97 };
98}
99
100#endif