sandbox
Loading...
Searching...
No Matches
ring_buffer.hpp
1#ifndef LIBSBX_MEMORY_RING_BUFFER_HPP_
2#define LIBSBX_MEMORY_RING_BUFFER_HPP_
3
4#include <memory>
5#include <utility>
6
7namespace sbx::memory {
8
9template<typename Type, std::size_t Capacity>
11
12public:
13
14 using value_type = Type;
15
16 ring_buffer() noexcept
17 : _head{0},
18 _tail{0} { }
19
20 ~ring_buffer() noexcept {
21 for (auto i = _head; i != _tail; i = (i + 1) % Capacity) {
22 auto* ptr = _ptr_at(i);
23 std::destroy_at(ptr);
24 ptr = nullptr;
25 }
26 }
27
28 auto push(Type&& value) noexcept -> void {
29 auto* ptr = _ptr_at(_head);
30
31 if (ptr != nullptr) {
32 std::destroy_at(ptr);
33 ptr = nullptr;
34 }
35
36 std::construct_at(_ptr_at(_head), std::move(value));
37
38 _head = (_head + 1) % Capacity;
39 }
40
41 auto capacity() const noexcept -> std::size_t {
42 return Capacity;
43 }
44
45private:
46
47 auto _ptr_at(std::size_t) -> Type* {
48 return reinterpret_cast<Type*>(_buffer + i);
49 }
50
51 alignas(alignof(Type)) std::byte _buffer[sizeof(Type) * Capacity];
52 std::size_t _head;
53 std::size_t _tail;
54
55}; // class ring_buffer
56
57} // namespace sbx::memory
58
59#endif // LIBSBX_MEMORY_RING_BUFFER_HPP_
Definition: ring_buffer.hpp:10