Skip to main content

StateToIdMap.ixx File

Policy mapping states to IDs. More...

Included Headers

#include <vector> #include <span> #include <helios-engine-config.h> #include <cassert> #include <bit> #include <algorithm> #include <cstddef> #include <utility> #include <helios.engine.core.types> #include <helios.engine.state.types>

Namespaces Index

namespacehelios
namespaceengine
namespacestate

Classes Index

classStateToIdMap<TState, TId>

Maps state enum values to lists of IDs. More...

Description

Policy mapping states to IDs.

File Listing

The file content with the documentation metadata removed is:

1
5module;
6
7#include <vector>
8#include <span>
10#include <cassert>
11#include <bit>
12#include <algorithm>
13#include <cstddef>
14#include <utility>
15
16export module helios.engine.state.StateToIdMap;
17
18
19import helios.engine.state.types;
20
21import helios.engine.core.types;
22
23using namespace helios::engine::state::types;
24export namespace helios::engine::state {
25
37 template<typename TState, typename TId>
39
43 std::vector<std::vector<TId>> states_;
44
48 const std::vector<TId> empty_;
49
56 void update(size_t st, const TId id) {
57
58 size_t idx = 0;
59 while (st > 0) {
60
61 if ((st & 1) != 0) {
62 if (states_.size() <= idx) {
63 states_.resize(idx + 1);
64 }
65 if (std::ranges::find(states_[idx], id) == states_[idx].end()) {
66 states_[idx].push_back(id);
67 }
68 }
69
70 idx++;
71 st >>= 1;
72 }
73
74 }
75
79 bool frozen_ = false;
80
81 public:
82
87 states_.reserve(STATE_TO_IDMAP_DEFAULT_CAPACITY);
88 };
89
98 StateToIdMap& add(TState state, TId id) noexcept {
99 assert(!frozen_ && "Cannot add to a frozen map");
100
101 const auto st = static_cast<size_t>(std::to_underlying(state));
102
103 if (st == 0) {
104 return *this;
105 }
106
107 update(st, id);
108
109 return *this;
110 }
111
115 void finalize() {
116 for (auto& v : states_) {
117 std::sort(v.begin(), v.end());
118 auto [first, last] = std::ranges::unique(v);
119 v.erase(first, last);
120 }
121 }
122
129 return frozen_;
130 }
131
135 void freeze() {
136 finalize();
137 states_.shrink_to_fit();
138 frozen_ = true;
139 }
140
148 [[nodiscard]] const std::vector<TId>& ids(const TState state) const noexcept {
149
150 if (std::to_underlying(state) == 0) {
151 return empty_;
152 }
153
154 assert((std::to_underlying(state) & (std::to_underlying(state) -1)) == 0 && "State must be a power of 2");
155
156 const auto stateIdx = static_cast<size_t>(std::countr_zero(std::to_underlying(state)));
157
158 if (states_.size() <= stateIdx) {
159 return empty_;
160 }
161
162 return states_[stateIdx];
163 }
164
165
166 };
167
168
169}

Generated via doxygen2docusaurus 2.0.0 by Doxygen 1.9.8.