Fumofumotris/source/game/event.c

51 lines
1,010 B
C
Raw Normal View History

2024-04-03 23:31:47 +00:00
#include <iso646.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include "fumotris.h"
struct Delegate {
size_t len;
size_t capacity;
void (**events)(void *args);
};
2024-04-09 07:00:48 +00:00
size_t delegate_size(size_t capacity)
2024-04-03 23:31:47 +00:00
{
return sizeof(void(*)(void *)) * capacity;
}
2024-04-09 22:10:30 +00:00
bool NewDelegate(struct Delegate *d, size_t capacity)
2024-04-03 23:31:47 +00:00
{
2024-04-09 22:10:30 +00:00
void (**events)(void *args) = malloc(delegate_size(capacity));
if (events == nullptr)
return false;
*d = (struct Delegate) {
2024-04-03 23:31:47 +00:00
.len = 0,
.capacity = capacity,
.events = malloc(delegate_size(capacity))
};
2024-04-09 22:10:30 +00:00
return true;
2024-04-03 23:31:47 +00:00
}
void Subscribe(struct Delegate *d, void (*event)(void *args))
{
if (d->len == d->capacity) {
d->capacity *= 2;
d->events = realloc(d->events, delegate_size(d->capacity));
}
d->events[d->len] = event;
d->len += 1;
}
2024-04-04 19:43:45 +00:00
void Invoke(struct Delegate *d, void *args)
2024-04-03 23:31:47 +00:00
{
for (size_t i = 0; i < d->len; i++) {
d->events[i](args);
}
}