MotorControlModuleSDFM_TMS3.../Projects/EFC_Communication/UMLibrary/common/CircularBuffer.hpp

80 lines
2.0 KiB
C++
Raw Normal View History

2024-06-07 11:12:56 +03:00
/*
* CircularBuffer.hpp
*
* Created on: 21 дек. 2017 г.
* Author: titov
*/
#ifndef SOURCE_COMMON_CIRCULARBUFFER_HPP_
#define SOURCE_COMMON_CIRCULARBUFFER_HPP_
//!Кольцевой буфер.
/*!Кольцевой буфер.
* Класс не осуществляет защиту данных от переполнения и вычитывания.
* \param size Размер кольцевого буфера, должен быть степенью 2.
* \param T Тип данных хранящихся в буфуре.
*
*/
template<unsigned int size, typename T = char>
class CircularBuffer {
private:
static const unsigned int sizemask = size - 1;
T buff[size];
unsigned int head;
unsigned int tail;
public:
CircularBuffer();
void clear();
void put(T val);
T push();
bool empty() const;
bool full() const;
unsigned int load() const;
unsigned int avalaible() const;
};
template<unsigned int size, typename T>
inline CircularBuffer<size, T>::CircularBuffer() :
head(0), tail(0) {}
template<unsigned int size, typename T>
inline void CircularBuffer<size, T>::clear() {
head = 0;
tail = 0;
}
template<unsigned int size, typename T>
inline void CircularBuffer<size, T>::put(T val) {
buff[++head & sizemask] = val;
}
template<unsigned int size, typename T>
inline T CircularBuffer<size, T>::push() {
return buff[++tail & sizemask];
}
template<unsigned int size, typename T>
inline bool CircularBuffer<size, T>::empty() const {
return tail == head;
}
template<unsigned int size, typename T>
inline bool CircularBuffer<size, T>::full() const {
return ((head - tail) & sizemask) == sizemask;
}
template<unsigned int size, typename T>
inline unsigned int CircularBuffer<size, T>::load() const {
return (head - tail) & sizemask;
}
template<unsigned int size, typename T>
inline unsigned int CircularBuffer<size, T>::avalaible() const {
return (tail - head - 1u) & sizemask;
}
#endif /* SOURCE_COMMON_CIRCULARBUFFER_HPP_ */