A template for ring buffer implementation
Dependents: AwsomeStation LoRaBaseStation LoRaTerminal
Diff: RingBuffer.cpp
- Revision:
- 1:5f641cf190da
- Parent:
- 0:36b372831d9e
- Child:
- 3:21ee07b29eb7
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/RingBuffer.cpp Sat Jul 23 07:39:05 2016 +0000 @@ -0,0 +1,130 @@ +#include "RingBuffer.h" + +template <typename T> +CircularBuffer<T>::CircularBuffer(const uint32_t size) + :buffer_size(size) +{ + read_ptr = 0; + write_ptr = 0; + count = 0; + + // mutex lock + mux = false; + + // overflow + is_over_flow = false; + + // container + data = new T[buffer_size]; +} + +template <typename T> +CircularBuffer<T>::~CircularBuffer() +{ + delete[] data; +} + +template <typename T> +bool CircularBuffer<T>::isLocked() +{ + return mux; +} + +template <typename T> +void CircularBuffer<T>::lock() +{ + mux = true; +} + +template <typename T> +void CircularBuffer<T>::unlock() +{ + mux = false; +} + +template <typename T> +void CircularBuffer<T>::enqueue(T in) +{ + data[write_ptr++] = in; + write_ptr %= buffer_size; + + count++; +} + +template <typename T> +T CircularBuffer<T>::dequeue() +{ + T temp = data[read_ptr++]; + read_ptr %= buffer_size; + + count--; + return temp; +} + +template <typename T> +uint32_t CircularBuffer<T>::getReadPtr() +{ + return read_ptr; +} + +template <typename T> +uint32_t CircularBuffer<T>::getWritePtr() +{ + return write_ptr; +} + +template <typename T> +uint32_t CircularBuffer<T>::getCounter() +{ + return count; +} + +template <typename T> +bool CircularBuffer<T>::getOverFlow() +{ + return is_over_flow; +} + +template <typename T> +void CircularBuffer<T>::clearOverFlow() +{ + is_over_flow = false; +} + +template <typename T> +T CircularBuffer<T>::first() +{ + if (read_ptr > 0) + { + return data[read_ptr - 1]; + } + else + { + return data[read_ptr]; + } +} + +template <typename T> +T CircularBuffer<T>::last() +{ + if (write_ptr > 0) + { + return data[write_ptr - 1]; + } + else + { + return data[write_ptr]; + } +} + +template <typename T> +T CircularBuffer<T>::operator[](uint32_t idx) +{ + return data[idx]; +} + +// force compiler to create code for template +template class CircularBuffer<int>; +template class CircularBuffer<uint8_t>; +template class CircularBuffer<uint16_t>; +template class CircularBuffer<uint32_t>; \ No newline at end of file