Added more security to EventHook.
continuous-integration/drone/push Build is passing
Details
continuous-integration/drone/push Build is passing
Details
This commit is contained in:
parent
301f9b9656
commit
1b9da9a721
|
@ -15,7 +15,7 @@ namespace CreatureLib::Battling {
|
|||
|
||||
private:
|
||||
std::vector<EventHookFunc> _listeners;
|
||||
size_t _position;
|
||||
size_t _offset;
|
||||
size_t _capacity;
|
||||
uint8_t* _memory = nullptr;
|
||||
|
||||
|
@ -23,34 +23,37 @@ namespace CreatureLib::Battling {
|
|||
static const size_t defaultSize = 1024;
|
||||
|
||||
public:
|
||||
EventHook() : _position(0), _capacity(defaultSize), _memory(static_cast<uint8_t*>(malloc(defaultSize))) {
|
||||
if (_memory == nullptr) {
|
||||
EventHook() : _offset(0), _capacity(defaultSize) {
|
||||
auto ptr = calloc(defaultSize, 1);
|
||||
if (ptr == nullptr) {
|
||||
THROW_CREATURE("Out of memory.");
|
||||
}
|
||||
_memory = static_cast<uint8_t*>(ptr);
|
||||
}
|
||||
EventHook(const EventHook&) = delete;
|
||||
EventHook& operator=(const EventHook&) = delete;
|
||||
|
||||
~EventHook() { free(_memory); }
|
||||
|
||||
size_t GetPosition() const noexcept { return _position; }
|
||||
size_t GetPosition() const noexcept { return _offset; }
|
||||
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) {
|
||||
if (_offset + sizeof(T) >= _capacity) {
|
||||
_capacity += defaultSize;
|
||||
_memory = static_cast<uint8_t*>(realloc(_memory, _capacity));
|
||||
if (_memory == nullptr) {
|
||||
auto newPtr = realloc(_memory, _capacity);
|
||||
if (newPtr == nullptr) {
|
||||
THROW_CREATURE("Out of memory.");
|
||||
}
|
||||
_memory = static_cast<uint8_t*>(newPtr);
|
||||
}
|
||||
uint8_t* ptr = _memory + _position;
|
||||
uint8_t* ptr = _memory + _offset;
|
||||
T* event = new (ptr) T(args...);
|
||||
_position += sizeof(T);
|
||||
_offset += sizeof(T);
|
||||
for (auto listener : _listeners) {
|
||||
listener(event);
|
||||
try_creature(listener(event), "Exception in event listener");
|
||||
}
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue