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