Skip to content

Commit 1e53c17

Browse files
author
Pavel Siska
committed
fieldHandlersEnum
1 parent 6108697 commit 1e53c17

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
#pragma once
2+
3+
#include <boost/container/static_vector.hpp>
4+
5+
namespace ipxp {
6+
7+
/**
8+
* @brief Helper to determine the number of enum values.
9+
*
10+
* Requires that the enum defines a final enumerator named `FIELDS_SIZE`.
11+
*
12+
* @tparam E The enum type.
13+
* @return Number of elements.
14+
*/
15+
template<typename E>
16+
constexpr uint8_t enum_size()
17+
{
18+
return static_cast<uint8_t>(E::FIELDS_SIZE);
19+
}
20+
21+
/**
22+
* @brief Fixed-size array indexed by enum class.
23+
*
24+
* Simplifies code by allowing strongly typed enum indexing.
25+
*
26+
* @tparam Enum Enum class type (must be contiguous, starting at 0).
27+
* @tparam T Stored type.
28+
* @tparam Size Size of the enum (should match number of fields).
29+
*/
30+
31+
template<typename Enum, typename T, uint8_t Size>
32+
class EnumArray {
33+
public:
34+
static_assert(std::is_enum_v<Enum>, "EnumArray requires an enum type");
35+
36+
/**
37+
* @brief Access element by enum index.
38+
*/
39+
T& operator[](Enum index) { return m_data[static_cast<uint8_t>(index)]; }
40+
const T& operator[](Enum index) const { return m_data[static_cast<uint8_t>(index)]; }
41+
42+
void insert(Enum index, const T& value)
43+
{
44+
uint8_t idx = static_cast<uint8_t>(index);
45+
if (idx != m_data.size()) {
46+
throw std::out_of_range("EnumArray: insertion index must be equal to current size");
47+
}
48+
m_data.push_back(value);
49+
}
50+
51+
void insert(Enum index, T&& value)
52+
{
53+
uint8_t idx = static_cast<uint8_t>(index);
54+
if (idx != m_data.size()) {
55+
throw std::out_of_range("EnumArray: insertion index must be equal to current size");
56+
}
57+
m_data.push_back(std::move(value));
58+
}
59+
60+
/**
61+
* @brief Returns the number of elements in the array.
62+
*/
63+
std::size_t size() const noexcept { return m_data.size(); }
64+
65+
/**
66+
* @brief Returns iterator to the beginning.
67+
*/
68+
auto begin() noexcept { return m_data.begin(); }
69+
auto end() noexcept { return m_data.end(); }
70+
auto begin() const noexcept { return m_data.begin(); }
71+
auto end() const noexcept { return m_data.end(); }
72+
73+
private:
74+
boost::container::static_vector<T, Size> m_data;
75+
};
76+
77+
/**
78+
* @brief Storage for field handlers indexed by enum.
79+
*
80+
* Designed to hold field accessors for a plugin schema.
81+
*
82+
* @tparam Enum Enum type used to represent individual fields.
83+
*/
84+
85+
template<typename Enum>
86+
using FieldHandlers = EnumArray<Enum, FieldHandler, enum_size<Enum>()>;
87+
88+
} // namespace ipxp

0 commit comments

Comments
 (0)