#pragma once #include #include #include template struct callback_list { struct node { alignas(T) uint8_t storage[sizeof(T)]; node* prev = nullptr; node* next = nullptr; bool active = false; T& value() { return *reinterpret_cast(storage); } const T& value() const { return *reinterpret_cast(storage); } }; node nodes[N]; node* free_head = &nodes[0]; node sentinel; callback_list() { for (int i = 0; i < N - 1; i++) nodes[i].next = &nodes[i + 1]; nodes[N - 1].next = nullptr; sentinel.prev = &sentinel; sentinel.next = &sentinel; } bool empty() const { return sentinel.next == &sentinel; } node* insert(T value) { if (!free_head) return nullptr; node* n = alloc(std::move(value)); link_before(&sentinel, n); return n; } template node* insert_sorted(T value, Less&& less) { if (!free_head) return nullptr; node* n = alloc(std::move(value)); node* pos = sentinel.next; while (pos != &sentinel && !less(n->value(), pos->value())) pos = pos->next; link_before(pos, n); return n; } void remove(node* n) { if (!n || !n->active) return; n->prev->next = n->next; n->next->prev = n->prev; n->active = false; n->value().~T(); n->next = free_head; n->prev = nullptr; free_head = n; } node* front() { return sentinel.next != &sentinel ? sentinel.next : nullptr; } template void for_each(Fn&& fn) { node* cur = sentinel.next; while (cur != &sentinel) { node* next = cur->next; fn(cur); cur = next; } } private: node* alloc(T value) { node* n = free_head; free_head = n->next; new (n->storage) T(std::move(value)); n->active = true; return n; } void link_before(node* pos, node* n) { n->prev = pos->prev; n->next = pos; pos->prev->next = n; pos->prev = n; } };