openMSX
CircularBuffer.hh
Go to the documentation of this file.
1#ifndef CIRCULARBUFFER_HH
2#define CIRCULARBUFFER_HH
3
4#include <array>
5#include <cassert>
6#include <cstddef>
7#include <utility>
8
9namespace openmsx {
10
11template<typename T, size_t MAXSIZE>
13{
14public:
15 constexpr CircularBuffer() = default;
16
17 constexpr void addFront(const T& element) {
18 assert(!isFull());
19 first = prev(first);
20 buffer[first] = element;
21 }
22 constexpr void addFront(T&& element) {
23 assert(!isFull());
24 first = prev(first);
25 buffer[first] = std::move(element);
26 }
27 constexpr void addBack(const T& element) {
28 assert(!isFull());
29 buffer[last] = element;
30 last = next(last);
31 }
32 constexpr void addBack(T&& element) {
33 assert(!isFull());
34 buffer[last] = std::move(element);
35 last = next(last);
36 }
37 constexpr T& removeFront() {
38 assert(!isEmpty());
39 auto tmp = first;
40 first = next(first);
41 return buffer[tmp];
42 }
43 constexpr T& removeBack() {
44 assert(!isEmpty());
45 last = prev(last);
46 return buffer[last];
47 }
48 [[nodiscard]] constexpr T& operator[](size_t pos) {
49 assert(pos < MAXSIZE);
50 auto tmp = first + pos;
51 if (tmp > MAXSIZE) {
52 tmp -= (MAXSIZE + 1);
53 }
54 return buffer[tmp];
55 }
56 [[nodiscard]] constexpr const T& operator[](size_t pos) const {
57 return const_cast<CircularBuffer&>(*this)[pos];
58 }
59 [[nodiscard]] constexpr bool isEmpty() const {
60 return (first == last);
61 }
62 [[nodiscard]] constexpr bool isFull() const {
63 return (first == next(last));
64 }
65 [[nodiscard]] constexpr size_t size() const {
66 if (first > last) {
67 return MAXSIZE + 1 - first + last;
68 } else {
69 return last - first;
70 }
71 }
72
73 void clear() {
74 first = last = 0;
75 }
76
77private:
78 [[nodiscard]] constexpr size_t next(size_t a) const {
79 return (a != MAXSIZE) ? a + 1 : 0;
80 }
81 [[nodiscard]] constexpr size_t prev(size_t a) const {
82 return (a != 0) ? a - 1 : MAXSIZE;
83 }
84
85 size_t first = 0;
86 size_t last = 0;
87 // one extra to be able to distinguish full and empty
88 std::array<T, MAXSIZE + 1> buffer;
89};
90
91} // namespace openmsx
92
93#endif
constexpr void addBack(const T &element)
constexpr bool isFull() const
constexpr void addBack(T &&element)
constexpr T & operator[](size_t pos)
constexpr T & removeFront()
constexpr CircularBuffer()=default
constexpr T & removeBack()
constexpr size_t size() const
constexpr void addFront(T &&element)
constexpr bool isEmpty() const
constexpr void addFront(const T &element)
constexpr const T & operator[](size_t pos) const
This file implemented 3 utility functions:
Definition Autofire.cc:9