Reworked event hook to a system with pre-allocated memory, owned by the battle. This deals with cleaning up event data memory.
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
2020-07-31 16:19:39 +02:00
parent 3e8f9340f3
commit 0eaae43444
5 changed files with 33 additions and 13 deletions

View File

@@ -11,16 +11,36 @@ namespace CreatureLib::Battling {
/// for it.
class EventHook {
std::vector<EVENT_HOOK_FUNC()> _listeners;
size_t _position;
size_t _capacity;
uint64_t* _memory;
// Consider tweaking this size to be in line with the normal amount of events we use.
static const size_t defaultSize = 1024;
public:
void RegisterListener(EVENT_HOOK_FUNC(func)) { _listeners.push_back(func); }
EventHook() : _position(0), _capacity(defaultSize), _memory(static_cast<uint64_t*>(malloc(defaultSize))) {}
~EventHook() { free(_memory); }
void TriggerEvent(EventData* eventData) const {
AssertNotNull(eventData)
size_t GetPosition() const noexcept { return _position; }
size_t GetCapacity() const noexcept { return _capacity; }
template <class T, class... parameters> void Trigger(parameters... args) {
if (_listeners.size() == 0)
return;
if (_position + sizeof(T) > _capacity) {
_capacity += defaultSize;
_memory = static_cast<uint64_t*>(realloc(_memory, _capacity));
}
auto ptr = _memory + _position;
T* event = new (ptr) T(args...);
_position += sizeof(T);
for (auto listener : _listeners) {
listener(eventData);
listener(event);
}
}
void RegisterListener(EVENT_HOOK_FUNC(func)) { _listeners.push_back(func); }
};
}
#endif // CREATURELIB_EVENTHOOK_HPP