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