semf
ringbuffer.h
Go to the documentation of this file.
1
10#ifndef SEMF_UTILS_CORE_BUFFER_RINGBUFFER_H_
11#define SEMF_UTILS_CORE_BUFFER_RINGBUFFER_H_
12
14
15namespace semf
16{
38template <typename T>
39class RingBuffer : public Buffer<T>
40{
41public:
42 using Buffer<T>::Buffer;
43
48 virtual void put(T data);
55 T& get();
63 virtual T& operator[](size_t pos) const;
70 bool isFull() const;
77 bool isEmpty() const;
82 size_t count() const override;
87 void reset();
88
89private:
91 size_t m_dataCounter = 0;
93 size_t m_writePos = 0;
95 size_t m_readPos = 0;
96};
97
98template <typename T>
100{
101 if (isFull())
102 {
103 return;
104 }
105
107 ++m_dataCounter;
108 m_writePos = (m_writePos + 1) % this->size();
109 this->data()[m_writePos] = data;
111}
112
113template <typename T>
115{
116#if defined(DEBUG) || defined(USE_SEMF_DEBUG)
117 if (isEmpty())
118 {
119 T* p = nullptr;
120 return *p;
121 }
122#endif
123
125 --m_dataCounter;
126 m_readPos = (m_readPos + 1) % this->size();
127 T& data = this->data()[m_readPos];
129
130 return data;
131}
132
133template <typename T>
134T& RingBuffer<T>::operator[](size_t pos) const
135{
136#if defined(DEBUG) || defined(USE_SEMF_DEBUG)
137 if (isEmpty() || pos > m_dataCounter)
138 {
139 T* p = nullptr;
140 return *p;
141 }
142#endif
143
145 size_t readPos = (m_readPos + pos) % this->size();
146 T& data = this->data()[readPos];
148
149 return data;
150}
151
152template <typename T>
154{
156 if (m_dataCounter == this->size())
157 {
159 return true;
160 }
162 return false;
163}
164
165template <typename T>
167{
169 if (m_dataCounter == 0)
170 {
172 return true;
173 }
174
176 return false;
177}
178
179template <typename T>
181{
183 size_t counter = m_dataCounter;
185
186 return counter;
187}
188
189template <typename T>
191{
193 m_readPos = 0;
194 m_writePos = 0;
195 m_dataCounter = 0;
197}
198} /* namespace semf */
199#endif /* SEMF_UTILS_CORE_BUFFER_RINGBUFFER_H_ */
Buffer is a base class for buffer implementations.
Definition: buffer.h:42
T * data() const
Returns the pointer to the first element of the data array.
Definition: buffer.h:139
Buffer()=default
The RingBuffer class implements a classic circular buffer.
Definition: ringbuffer.h:40
void reset()
Clears the buffer.
Definition: ringbuffer.h:190
virtual T & operator[](size_t pos) const
Returns the entry from a specific position in the buffer.
Definition: ringbuffer.h:134
virtual void put(T data)
Writes data in the buffer.
Definition: ringbuffer.h:99
bool isFull() const
Returns if the buffer is full.
Definition: ringbuffer.h:153
bool isEmpty() const
Returns if the buffer is empty.
Definition: ringbuffer.h:166
size_t count() const override
Returns the number of entries stored in the buffer and not read yet.
Definition: ringbuffer.h:180
T & get()
Returns the oldest value not read yet.
Definition: ringbuffer.h:114