Skip to content

Kmempool: expose kmempool_t as an opaque type #189

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 6 additions & 9 deletions kmempool.c
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
#define Calloc(type, cnt) ((type*)calloc((cnt), sizeof(type)))
#define Realloc(type, ptr, cnt) ((type*)realloc((ptr), (cnt) * sizeof(type)))

typedef struct {
typedef struct kmempool_s {
uint32_t sz; // size of an entry
uint32_t chunk_size; // number of entries in a chunk
uint32_t n_chunk; // number of chunks
Expand All @@ -25,7 +25,7 @@ static void kmp_add_chunk(kmempool_t *mp) // add a new chunk
mp->p_end = mp->p + x;
}

void *kmp_init2(unsigned sz, unsigned chunk_size)
kmempool_t *kmp_init2(unsigned sz, unsigned chunk_size)
{
kmempool_t *mp;
mp = Calloc(kmempool_t, 1);
Expand All @@ -34,23 +34,21 @@ void *kmp_init2(unsigned sz, unsigned chunk_size)
return mp;
}

void *kmp_init(unsigned sz) // fixed chunk size
kmempool_t *kmp_init(unsigned sz) // fixed chunk size
{
return kmp_init2(sz, 0x10000);
}

void kmp_destroy(void *mp_)
void kmp_destroy(kmempool_t *mp)
{
kmempool_t *mp = (kmempool_t*)mp_;
uint32_t i;
for (i = 0; i < mp->n_chunk; ++i) // free all chunks
free(mp->chunk[i]);
free(mp->chunk); free(mp->buf); free(mp);
}

void *kmp_alloc(void *mp_)
void *kmp_alloc(kmempool_t *mp)
{
kmempool_t *mp = (kmempool_t*)mp_;
void *ret;
if (mp->n_buf > 0) { // there are buffered free entries
ret = mp->buf[--mp->n_buf];
Expand All @@ -62,9 +60,8 @@ void *kmp_alloc(void *mp_)
return ret;
}

void kmp_free(void *mp_, void *p)
void kmp_free(kmempool_t *mp, void *p)
{
kmempool_t *mp = (kmempool_t*)mp_;
if (mp->n_buf == mp->m_buf) { // then enlarge the buffer
mp->m_buf += (mp->m_buf>>1) + 16;
mp->buf = Realloc(void*, mp->buf, mp->m_buf);
Expand Down
10 changes: 6 additions & 4 deletions kmempool.h
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@
extern "C" {
#endif

void *kmp_init(unsigned sz);
void kmp_destroy(void *mp);
void *kmp_alloc(void *mp);
void kmp_free(void *mp, void *p);
typedef struct kmempool_s kmempool_t;

kmempool_t *kmp_init(unsigned sz);
void kmp_destroy(kmempool_t *mp);
void *kmp_alloc(kmempool_t *mp);
void kmp_free(kmempool_t *mp, void *p);

#ifdef __cplusplus
}
Expand Down