54 lines
1.5 KiB
C++
54 lines
1.5 KiB
C++
|
|
#pragma once
|
|
|
|
#if !defined(BAD_APPLE_OS_OS_TOOLS_RINGBUFFER_HPP_INCLUDED)
|
|
#define BAD_APPLE_OS_OS_TOOLS_RINGBUFFER_HPP_INCLUDED
|
|
|
|
#include <array>
|
|
#include <cstddef>
|
|
|
|
namespace baos
|
|
{
|
|
template<typename T, std::size_t SIZE>
|
|
class RingBuffer
|
|
{
|
|
private:
|
|
std::array<T, SIZE> mElements;
|
|
std::size_t mBufferedElements = 0;
|
|
std::size_t mPosition = 0;
|
|
public:
|
|
[[nodiscard]] bool full() const noexcept { return mBufferedElements == SIZE; }
|
|
[[nodiscard]] bool empty() const noexcept { return mBufferedElements == 0; }
|
|
[[nodiscard]] std::size_t size() const noexcept { return mBufferedElements; }
|
|
|
|
[[nodiscard]] T& operator[](std::size_t index) noexcept { return at(index); }
|
|
[[nodiscard]] const T& operator[](std::size_t index) const noexcept { return at(index); }
|
|
|
|
[[nodiscard]] T& at(std::size_t index) noexcept { return mElements[(index + mPosition) % SIZE]; }
|
|
[[nodiscard]] const T& at(std::size_t index) const noexcept { return mElements[(index + mPosition) % SIZE]; }
|
|
|
|
bool append(T element) noexcept
|
|
{
|
|
if (full()) {
|
|
return false;
|
|
}
|
|
mElements[mPosition] = std::move(element);
|
|
++mBufferedElements;
|
|
mPosition = (mPosition + 1) % SIZE;
|
|
return true;
|
|
}
|
|
|
|
bool next(T& outElement) noexcept
|
|
{
|
|
if (empty()) {
|
|
return false;
|
|
}
|
|
outElement = std::move(mElements[(mPosition + SIZE - mBufferedElements) % SIZE]);
|
|
--mBufferedElements;
|
|
return true;
|
|
}
|
|
};
|
|
}
|
|
|
|
#endif // !defined(BAD_APPLE_OS_OS_TOOLS_RINGBUFFER_HPP_INCLUDED)
|