123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152 |
- #ifndef POOL_ALLOCATOR_H
- #define POOL_ALLOCATOR_H
- #include "core/typedefs.h"
- enum {
- POOL_ALLOCATOR_INVALID_ID = -1
- };
- class PoolAllocator {
- public:
- typedef int ID;
- private:
- enum {
- CHECK_BITS = 8,
- CHECK_LEN = (1 << CHECK_BITS),
- CHECK_MASK = CHECK_LEN - 1
- };
- struct Entry {
- unsigned int pos;
- unsigned int len;
- unsigned int lock;
- unsigned int check;
- inline void clear() {
- pos = 0;
- len = 0;
- lock = 0;
- check = 0;
- }
- Entry() { clear(); }
- };
- typedef int EntryArrayPos;
- typedef int EntryIndicesPos;
- Entry *entry_array;
- int *entry_indices;
- int entry_max;
- int entry_count;
- uint8_t *pool;
- void *mem_ptr;
- int pool_size;
- int free_mem;
- int free_mem_peak;
- unsigned int check_count;
- int align;
- bool needs_locking;
- inline int entry_end(const Entry &p_entry) const {
- return p_entry.pos + aligned(p_entry.len);
- }
- inline int aligned(int p_size) const {
- int rem = p_size % align;
- if (rem)
- p_size += align - rem;
- return p_size;
- }
- void compact(int p_up_to = -1);
- void compact_up(int p_from = 0);
- bool get_free_entry(EntryArrayPos *p_pos);
- bool find_hole(EntryArrayPos *p_pos, int p_for_size);
- bool find_entry_index(EntryIndicesPos *p_map_pos, Entry *p_entry);
- Entry *get_entry(ID p_mem);
- const Entry *get_entry(ID p_mem) const;
- void create_pool(void *p_mem, int p_size, int p_max_entries);
- protected:
- virtual void mt_lock() const;
- virtual void mt_unlock() const;
- public:
- enum {
- DEFAULT_MAX_ALLOCS = 4096,
- };
- ID alloc(int p_size);
- void free(ID p_mem);
- Error resize(ID p_mem, int p_new_size);
- int get_size(ID p_mem) const;
- int get_free_mem();
- int get_used_mem() const;
- int get_free_peak();
- Error lock(ID p_mem);
- void *get(ID p_mem);
- const void *get(ID p_mem) const;
- void unlock(ID p_mem);
- bool is_locked(ID p_mem) const;
- PoolAllocator(int p_size, bool p_needs_locking = false, int p_max_entries = DEFAULT_MAX_ALLOCS);
- PoolAllocator(void *p_mem, int p_size, int p_align = 1, bool p_needs_locking = false, int p_max_entries = DEFAULT_MAX_ALLOCS);
- PoolAllocator(int p_align, int p_size, bool p_needs_locking = false, int p_max_entries = DEFAULT_MAX_ALLOCS);
- virtual ~PoolAllocator();
- };
- #endif
|