loon
High-performance header-only C++ library for low-latency applications
Loading...
Searching...
No Matches
ring_buffer.hpp
Go to the documentation of this file.
1#pragma once
2
5
6#include <array>
7#include <cstddef>
8#include <optional>
9
10namespace loon {
11
28template <typename T, size_t N>
30 public:
32 RingBuffer() = default;
33
37 explicit RingBuffer(bool override_when_full) : override(override_when_full) {}
38
42 bool push(const T& value) {
43 if (full()) {
44 if (!override) {
45 return false;
46 }
47 // advance read pointer to discard oldest
48 read = (read + 1) % N;
49 } else {
50 ++count;
51 }
52 buffer[write] = value;
53 write = (write + 1) % N;
54
55 return true;
56 }
57
60 std::optional<T> pop() {
61 if (empty()) {
62 return std::nullopt;
63 }
64 T value = buffer[read];
65 read = (read + 1) % N;
66 --count;
67 return value;
68 }
69
72 std::optional<T> front() {
73 if (empty()) {
74 return std::nullopt;
75 }
76 return buffer[read];
77 }
78
81 std::optional<T> back() {
82 if (empty()) {
83 return std::nullopt;
84 }
85 return buffer[(write - 1 + N) % N];
86 }
87
90 bool discard() {
91 if (empty()) {
92 return false;
93 }
94 read = (read + 1) % N;
95 --count;
96 return true;
97 }
98
101 [[nodiscard]] size_t capacity() const { return N; }
102
105 [[nodiscard]] bool empty() const { return count == 0; }
106
109 [[nodiscard]] bool full() const { return count == N; }
110
113 [[nodiscard]] bool overrides() const { return override; }
114
117 [[nodiscard]] size_t size() const { return count; }
118
119 private:
120 std::array<T, N> buffer;
121 size_t write = 0;
122 size_t read = 0;
123 size_t count = 0;
124 bool override = false;
125};
126
127} // namespace loon
A fixed-size circular buffer (ring buffer) with FIFO semantics.
std::optional< T > pop()
Removes and returns the front element.
bool overrides() const
Checks if override mode is enabled.
size_t size() const
Returns the current number of elements.
bool empty() const
Checks if the buffer is empty.
RingBuffer(bool override_when_full)
Constructs an empty RingBuffer with configurable override behavior.
bool full() const
Checks if the buffer is full.
std::optional< T > back()
Returns the back element without removing it.
std::optional< T > front()
Returns the front element without removing it.
bool discard()
Discards the front element without returning it.
bool push(const T &value)
Pushes a value to the back of the buffer.
RingBuffer()=default
Constructs an empty RingBuffer with default behavior (reject when full).
size_t capacity() const
Returns the maximum capacity of the buffer.