2 * Copyright (c) 2021 Arm Limited.
4 * SPDX-License-Identifier: MIT
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to
8 * deal in the Software without restriction, including without limitation the
9 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10 * sell copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 #include "optional.hpp"
33 template <typename T, std::size_t N>
38 * @brief Return maximum capacity of the ring buffer.
40 constexpr std::size_t capacity()
46 * @brief Return current size of the ring buffer.
48 std::size_t size() const
54 * @brief Places item into next slot of the ring buffer.
55 * @return Boolean to indicate success or failure.
58 bool push_back(U &&item)
60 if (size() == capacity())
65 m_data[(m_begin + m_size) % N].set(std::forward<U>(item));
72 * @brief Gets a pointer to the item at the starting index of the ring buffer.
80 * @brief Gets a pointer to the item that was last placed into the ring buffer.
84 return get((m_begin + m_size + N - 1) % N);
88 * @brief Pop the front of the ring buffer.
90 * Item at the starting index of the ring buffer is returned. The slot is subsequently emptied. The starting index of
91 * the ring buffer increments by 1.
93 * @return Item wrapped in an optional.
95 util::optional<T> pop_front()
99 return util::optional<T>{};
102 util::optional<T> value = std::move(m_data[m_begin]);
104 m_begin = (m_begin + 1) % N;
111 T *get(std::size_t index)
113 if (m_data[index].has_value())
115 return std::addressof(m_data[index].value());
123 std::array<util::optional<T>, N> m_data{};
125 // Marks the start index of the ring buffer.
126 std::size_t m_begin{};
128 // The number of entries in the ring buffer from the start index.
129 std::size_t m_size{};
132 } /* namespace util */