AskSin++
RingBuffer.h
1 //- -----------------------------------------------------------------------------------------------------------------------
2 // 2020-01-19 papa Creative Commons - http://creativecommons.org/licenses/by-nc-sa/3.0/de/
3 //- -----------------------------------------------------------------------------------------------------------------------
4 
5 #ifndef RINGBUFFER_H_
6 #define RINGBUFFER_H_
7 
8 namespace as {
9 
14 template<class TYPE,int SIZE>
15 class RingStack {
16  TYPE _buffer[SIZE];
17  TYPE* _current;
18  int _count;
23  TYPE& first () {
24  return _buffer[0];
25  }
30  TYPE& last () {
31  return _buffer[SIZE-1];
32  }
33 
34 public:
38  RingStack () {
39  clear();
40  }
44  void clear () {
45  _current = &first();
46  _count = 0;
47  }
52  int size () const { return SIZE; }
57  int count () const { return _count; }
62  bool shift () {
63  if( _count < SIZE ) _count++;
64  _current--;
65  if( _current < _buffer ) _current = &last();
66  return _count == SIZE;
67  }
73  bool shift (const TYPE& data) {
74  bool result = shift();
75  *_current = data;
76  return result;
77  }
83  TYPE& operator [] (int index) {
84  index = index <_count-1 ? index : _count-1;
85  return *(_buffer + ((_current - _buffer + index) % SIZE));
86  }
92  const TYPE& operator [] (int index) const {
93  index = index <_count-1 ? index : _count-1;
94  return *(_buffer + ((_current - _buffer + index) % SIZE));
95  }
96 };
97 
98 }
99 
100 #endif /* RINGBUFFER_H_ */
as::RingStack::shift
bool shift()
Definition: RingBuffer.h:62
as::RingStack::size
int size() const
Definition: RingBuffer.h:52
as::RingStack::count
int count() const
Definition: RingBuffer.h:57
as::RingStack
Definition: RingBuffer.h:15
as::RingStack::clear
void clear()
Definition: RingBuffer.h:44
as::RingStack::shift
bool shift(const TYPE &data)
Definition: RingBuffer.h:73
as::RingStack::operator[]
TYPE & operator[](int index)
Definition: RingBuffer.h:83
as::RingStack::RingStack
RingStack()
Definition: RingBuffer.h:38