123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196 |
- #ifndef ALLOCATORS_H
- #define ALLOCATORS_H
- #include "core/os/memory.h"
- template <int PREALLOC_COUNT = 64, int MAX_HANDS = 8>
- class BalloonAllocator {
- enum {
- USED_FLAG = (1 << 30),
- USED_MASK = USED_FLAG - 1
- };
- struct Balloon {
- Balloon *next;
- Balloon *prev;
- uint32_t hand;
- };
- struct Hand {
- int used;
- int allocated;
- Balloon *first;
- Balloon *last;
- };
- Hand hands[MAX_HANDS];
- public:
- void *alloc(size_t p_size) {
- size_t max = (1 << MAX_HANDS);
- ERR_FAIL_COND_V(p_size > max, NULL);
- unsigned int hand = 0;
- while (p_size > (size_t)(1 << hand))
- ++hand;
- Hand &h = hands[hand];
- if (h.used == h.allocated) {
- for (int i = 0; i < PREALLOC_COUNT; i++) {
- Balloon *b = (Balloon *)memalloc(sizeof(Balloon) + (1 << hand));
- b->hand = hand;
- if (h.last) {
- b->prev = h.last;
- h.last->next = b;
- h.last = b;
- } else {
- b->prev = NULL;
- h.last = b;
- h.first = b;
- }
- }
- h.last->next = NULL;
- h.allocated += PREALLOC_COUNT;
- }
- Balloon *pick = h.last;
- ERR_FAIL_COND_V((pick->hand & USED_FLAG), NULL);
-
- h.last = h.last->prev;
- h.last->next = NULL;
- pick->next = h.first;
- h.first->prev = pick;
- pick->prev = NULL;
- h.first = pick;
- h.used++;
- pick->hand |= USED_FLAG;
- return (void *)(pick + 1);
- }
- void free(void *p_ptr) {
- Balloon *b = (Balloon *)p_ptr;
- b -= 1;
- ERR_FAIL_COND(!(b->hand & USED_FLAG));
- b->hand = b->hand & USED_MASK;
- int hand = b->hand;
- Hand &h = hands[hand];
- if (b == h.first)
- h.first = b->next;
- if (b->prev)
- b->prev->next = b->next;
- if (b->next)
- b->next->prev = b->prev;
- if (h.last != b) {
- h.last->next = b;
- b->prev = h.last;
- b->next = NULL;
- h.last = b;
- }
- h.used--;
- if (h.used <= (h.allocated - (PREALLOC_COUNT * 2))) {
- for (int i = 0; i < PREALLOC_COUNT; i++) {
- ERR_CONTINUE(h.last->hand & USED_FLAG);
- Balloon *new_last = h.last->prev;
- if (new_last)
- new_last->next = NULL;
- memfree(h.last);
- h.last = new_last;
- }
- h.allocated -= PREALLOC_COUNT;
- }
- }
- BalloonAllocator() {
- for (int i = 0; i < MAX_HANDS; i++) {
- hands[i].allocated = 0;
- hands[i].used = 0;
- hands[i].first = NULL;
- hands[i].last = NULL;
- }
- }
- void clear() {
- for (int i = 0; i < MAX_HANDS; i++) {
- while (hands[i].first) {
- Balloon *b = hands[i].first;
- hands[i].first = b->next;
- memfree(b);
- }
- hands[i].allocated = 0;
- hands[i].used = 0;
- hands[i].first = NULL;
- hands[i].last = NULL;
- }
- }
- ~BalloonAllocator() {
- clear();
- }
- };
- #endif
|