80 lines
1.8 KiB
C++
80 lines
1.8 KiB
C++
/*
|
|
* 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_ */
|