-
Notifications
You must be signed in to change notification settings - Fork 0
/
roundbuffer.h
67 lines (47 loc) · 1.1 KB
/
roundbuffer.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
#ifndef __COMM_ROUNDBUFFER_H__
#define __COMM_ROUNDBUFFER_H__
#include "namespace.h"
#include "commtypes.h"
#include "dynarray.h"
// ONE reader ONE writer
COID_NAMESPACE_BEGIN
template<class T,uint SIZE>
class roundbuffer
: protected coid::dynarray<T>
{
private:
volatile uint _head;
volatile uint _tail;
static const uint SIZE_MASK=SIZE-1;
public:
/// size MUST be 2^n
roundbuffer()
: dynarray()
{
resize(SIZE);
}
bool push( const T& i )
{
const uint tmphead=(_head+1)&SIZE_MASK;
if( tmphead!=_tail ) {
ptr()[tmphead]=i;
_head=tmphead;
return true;
}
else {
DASSERT(false && "roundbuffer overflow!");
return false;
}
}
bool pop( T& i )
{
if( _tail==_head )
return false;
const uint tmptail=(_tail+1)&SIZE_MASK;
i=ptr()[tmptail];
_tail=tmptail;
return true;
}
};
COID_NAMESPACE_END
#endif // __COMM_ROUNDBUFFER_H__