add new type for ring buffer

This commit is contained in:
chatlanin
2025-01-04 11:41:10 +03:00
parent bb94945fa7
commit bc04dc09e9
4 changed files with 25 additions and 16 deletions

View File

@@ -5,6 +5,8 @@
#include "hack/utils/color.hpp"
#include "hack/exception/title.hpp"
// NOTE
// вмесо nlohman::json можно поробовать прикрутить https://jqlang.github.io/jq
namespace hack
{
class exception

View File

@@ -1,19 +1,23 @@
#pragma once
#include <array>
#include <vector>
#include <mutex>
#include <optional>
#include <vector>
namespace hack::patterns
{
template<typename T, std::size_t BUFFER_SIZE>
template<typename T>
class ring_buffer
{
using MUTEX = std::lock_guard<std::recursive_mutex>;
public:
explicit ring_buffer() = default;
explicit ring_buffer(int s)
{
m_size = s;
m_data.resize(m_size);
};
public:
void put(T item) noexcept
@@ -52,13 +56,13 @@ namespace hack::patterns
if(empty()) return std::nullopt;
auto val = m_data[m_tail];
m_tail = (m_tail + 1) % BUFFER_SIZE;
m_tail = (m_tail + 1) % m_size;
m_full = false;
return val;
}
std::array<T, BUFFER_SIZE>& get_src() const noexcept
std::vector<T>& get_src() const noexcept
{
return m_data;
}
@@ -73,13 +77,13 @@ namespace hack::patterns
{
MUTEX lock(m_mutex);
std::size_t size;
if(!m_full)
size = (m_head >= m_tail) ? m_head - m_tail : BUFFER_SIZE - (m_tail - m_head);
std::size_t s;
if (!m_full)
s = (m_head >= m_tail) ? m_head - m_tail : m_size - (m_tail - m_head);
else
size = BUFFER_SIZE;
s = m_size;
return size;
return s;
}
void reset() noexcept
@@ -96,14 +100,14 @@ namespace hack::patterns
std::size_t capacity() const noexcept
{
return BUFFER_SIZE;
return m_size;
}
private:
void head_refresh()
{
if (m_full) m_tail = (m_tail + 1) % BUFFER_SIZE;
m_head = (m_head + 1) % BUFFER_SIZE;
if (m_full) m_tail = (m_tail + 1) % m_size;
m_head = (m_head + 1) % m_size;
m_full = m_head == m_tail;
}
@@ -113,7 +117,8 @@ namespace hack::patterns
std::size_t m_tail{ 0 };
private:
int m_size;
mutable std::recursive_mutex m_mutex;
mutable std::array<T, BUFFER_SIZE> m_data;
mutable std::vector<T> m_data;
};
}