Sequoia
Loading...
Searching...
No Matches
StaticQueue.hpp
Go to the documentation of this file.
1
2// Copyright Oliver J. Rosten 2018. //
3// Distributed under the GNU GENERAL PUBLIC LICENSE, Version 3.0. //
4// (See accompanying file LICENSE.md or copy at //
5// https://www.gnu.org/licenses/gpl-3.0.en.html) //
7
8#pragma once
9
17
18namespace sequoia::data_structures
19{
25 template<class T, std::size_t MaxDepth>
27 {
28 public:
29 constexpr static_queue(std::initializer_list<T> l)
30 : m_Queue{utilities::to_array<T, MaxDepth>(l)}
31 , m_Front{l.size() ? 0 : MaxDepth}
32 , m_Back{l.size() ? l.size() - 1 : MaxDepth}
33 {
34 }
35
36 constexpr static_queue(const static_queue&) = default;
37 constexpr static_queue(static_queue&) noexcept = default;
38 ~static_queue() = default;
39
40 constexpr static_queue& operator=(const static_queue&) = default;
41 constexpr static_queue& operator=(static_queue&) noexcept = default;
42
43 constexpr void push(const T& val)
44 {
45 if constexpr(MaxDepth > 0)
46 {
47 if(size() == MaxDepth)
48 {
49 throw std::logic_error("Attempting to exceed maximum queue depth");
50 }
51 else if(m_Front == MaxDepth)
52 {
53 m_Front = 0;
54 m_Back = 0;
55 }
56 else
57 {
58 m_Back = (m_Back + 1) % MaxDepth;
59 }
60
61 m_Queue[m_Back] = val;
62 }
63 else
64 {
65 throw std::logic_error("Attempting to exceed maximum queue depth");
66 }
67 }
68
69 [[nodiscard]]
70 constexpr const T& back() const noexcept
71 {
72 return m_Queue[m_Back];
73 }
74
75 [[nodiscard]]
76 constexpr const T& front() const noexcept
77 {
78 return m_Queue[m_Front];
79 }
80
81 constexpr void pop() noexcept
82 {
83 if(m_Front == m_Back)
84 {
85 m_Front = MaxDepth;
86 m_Back = MaxDepth;
87 }
88 else
89 {
90 m_Front = (m_Front + 1) % MaxDepth;
91 }
92 }
93
94 [[nodiscard]]
95 constexpr bool empty() const noexcept
96 {
97 return m_Front == MaxDepth;
98 }
99
100 [[nodiscard]]
101 constexpr std::size_t size() const noexcept
102 {
103 if(empty())
104 {
105 return {};
106 }
107 else if(m_Front <= m_Back)
108 {
109 return m_Back + 1 - m_Front;
110 }
111 else
112 {
113 return MaxDepth + 1 - (m_Front - m_Back);
114 }
115 }
116
117 [[nodiscard]]
118 friend constexpr bool operator==(const static_queue& lhs, const static_queue& rhs) noexcept
119 {
120 if constexpr(MaxDepth > 0)
121 {
122 const auto sz{lhs.size()};
123 if(sz != rhs.size()) return false;
124
125 for(std::size_t i{}, l{lhs.m_Front}, r{rhs.m_Front}; i<sz; ++i)
126 {
127
128 if(lhs.m_Queue[l] != rhs.m_Queue[r]) return false;
129
130 l = (l+1) % MaxDepth;
131 r = (r+1) % MaxDepth;
132 }
133
134 return true;
135 }
136 else
137 {
138 return true;
139 }
140 }
141 private:
142 std::array<T, MaxDepth> m_Queue{};
143
144 std::size_t m_Front{MaxDepth}, m_Back{MaxDepth};
145 };
146}
A collection of constexpr algorithms.
Utility to convert an initializer_list into an array, potentially transforming the initializer_list i...
A queue suitable for constexpr contexts.
Definition: StaticQueue.hpp:27