Fix major incorrect usage of mrb class definitions causing segfaults

This commit is contained in:
2026-05-05 21:09:52 +01:00
parent d362bbc114
commit 0da950caf9
9 changed files with 393 additions and 152 deletions
+55 -22
View File
@@ -152,38 +152,71 @@ struct Rect {
}
};
template <typename T>
template <typename T = void *>
struct Pool {
T &operator[](int index) {
return items[index];
}
const std::vector<T> &all() {
return items;
}
int acquire(const T &item) {
if (!free_indices.empty()) {
int index = free_indices.back();
free_indices.pop_back();
items[index] = std::move(item);
return index;
} else {
items.push_back(std::move(item));
return items.size() - 1;
T *operator[](int index) {
if (!is_valid(index)) {
fprintf(stderr, "Invalid pool index: %d\n", index);
return nullptr;
}
return slots[index].ptr;
}
const std::vector<T *> &all() {
static std::vector<T *> all_items;
all_items.clear();
for (const auto &slot : slots)
if (slot.alive)
all_items.push_back(slot.ptr);
return all_items;
}
int acquire(T *item) {
int index;
if (!free_indices.empty()) {
index = free_indices.back();
free_indices.pop_back();
} else {
index = slots.size();
slots.push_back({});
}
slots[index].ptr = item;
slots[index].refcount = 1;
slots[index].alive = true;
return index;
}
void use(int index) {
if (is_valid(index))
slots[index].refcount++;
}
void release(int index) {
free_indices.push_back(index);
if (!is_valid(index))
return;
auto &slot = slots[index];
slot.refcount--;
if (slot.refcount <= 0) {
delete slot.ptr;
slot.ptr = nullptr;
slot.alive = false;
free_indices.push_back(index);
}
}
bool is_valid(size_t index) const {
return index >= 0 && index < items.size() && std::find(free_indices.begin(), free_indices.end(), index) == free_indices.end();
bool is_valid(int index) const {
return index >= 0
&& index < (int)slots.size()
&& slots[index].alive;
}
private:
std::vector<T> items;
struct Slot {
T *ptr = nullptr;
int refcount = 0;
bool alive = false;
};
std::vector<Slot> slots;
std::vector<int> free_indices;
};