klib
[Ported from github.com/attractivechaos/klib] added block arena
Brought by drakestapleton
klib / kmempool.c
| 1 | #include <stdint.h> |
| 2 | #include <stdlib.h> |
| 3 | #include "kmempool.h" |
| 4 | |
| 5 | #define Malloc(type, cnt) ((type*)malloc((cnt) * sizeof(type))) |
| 6 | #define Calloc(type, cnt) ((type*)calloc((cnt), sizeof(type))) |
| 7 | #define Realloc(type, ptr, cnt) ((type*)realloc((ptr), (cnt) * sizeof(type))) |
| 8 | |
| 9 | typedef struct { |
| 10 | uint32_t sz; // size of an entry |
| 11 | uint32_t chunk_size; // number of entries in a chunk |
| 12 | uint32_t n_chunk; // number of chunks |
| 13 | uint8_t *p; // pointing to an entry that can be allocated from a chunk |
| 14 | uint8_t *p_end; // end of the current chunk |
| 15 | uint8_t **chunk; // list of chunks |
| 16 | uint32_t n_buf, m_buf; // number/max number of buffered free entries |
| 17 | void **buf; // list of pointers to free entries |
| 18 | } kmempool_t; |
| 19 | |
| 20 | static void kmp_add_chunk(kmempool_t *mp) // add a new chunk |
| 21 | { |
| 22 | uint64_t x = (uint64_t)mp->sz * mp->chunk_size; |
| 23 | mp->chunk = Realloc(uint8_t*, mp->chunk, mp->n_chunk + 1); |
| 24 | mp->p = mp->chunk[mp->n_chunk++] = Calloc(uint8_t, x); |
| 25 | mp->p_end = mp->p + x; |
| 26 | } |
| 27 | |
| 28 | void *kmp_init2(unsigned sz, unsigned chunk_size) |
| 29 | { |
| 30 | kmempool_t *mp; |
| 31 | mp = Calloc(kmempool_t, 1); |
| 32 | mp->sz = sz, mp->chunk_size = chunk_size; |
| 33 | kmp_add_chunk(mp); |
| 34 | return mp; |
| 35 | } |
| 36 | |
| 37 | void *kmp_init(unsigned sz) // fixed chunk size |
| 38 | { |
| 39 | return kmp_init2(sz, 0x10000); |
| 40 | } |
| 41 | |
| 42 | void kmp_destroy(void *mp_) |
| 43 | { |
| 44 | kmempool_t *mp = (kmempool_t*)mp_; |
| 45 | uint32_t i; |
| 46 | for (i = 0; i < mp->n_chunk; ++i) // free all chunks |
| 47 | free(mp->chunk[i]); |
| 48 | free(mp->chunk); free(mp->buf); free(mp); |
| 49 | } |
| 50 | |
| 51 | void *kmp_alloc(void *mp_) |
| 52 | { |
| 53 | kmempool_t *mp = (kmempool_t*)mp_; |
| 54 | void *ret; |
| 55 | if (mp->n_buf > 0) { // there are buffered free entries |
| 56 | ret = mp->buf[--mp->n_buf]; |
| 57 | } else { // need to "allocate" from chunks |
| 58 | if (mp->p == mp->p_end) kmp_add_chunk(mp); // chunk full; add a new one |
| 59 | ret = (void*)mp->p; |
| 60 | mp->p += mp->sz; |
| 61 | } |
| 62 | return ret; |
| 63 | } |
| 64 | |
| 65 | void kmp_free(void *mp_, void *p) |
| 66 | { |
| 67 | kmempool_t *mp = (kmempool_t*)mp_; |
| 68 | if (mp->n_buf == mp->m_buf) { // then enlarge the buffer |
| 69 | mp->m_buf += (mp->m_buf>>1) + 16; |
| 70 | mp->buf = Realloc(void*, mp->buf, mp->m_buf); |
| 71 | } |
| 72 | mp->buf[mp->n_buf++] = p; |
| 73 | } |