Add mempool

This commit is contained in:
c9s 2015-11-12 22:15:35 +08:00
parent 576d568c16
commit e09667818e
2 changed files with 67 additions and 0 deletions

43
src/mempool.c Normal file
View file

@ -0,0 +1,43 @@
#include <stdio.h>
#include <stdlib.h>
#include "mempool.h"
void ex_mpool_init(ex_mpool *pmp, char *begin, size_t len)
{
pmp->begin = begin;
pmp->len = len;
pmp->index = 0;
pmp->cflag = 0;
}
void *ex_mpool_malloc(ex_mpool *pmp, size_t mlen)
{
void *ret = NULL;
size_t rIndex = pmp->index + mlen;
if (rIndex > pmp->len) {
ret = malloc(mlen);
pmp->cflag = 1;
}
else {
ret = pmp->begin + pmp->index;
pmp->index = rIndex;
}
return ret;
}
void ex_mpool_free(ex_mpool *pmp, void *p)
{
/* only perform free when allocated in heap */
if (p < (void *) pmp->begin ||
p >= (void *) (pmp->begin + pmp->len)) {
free(p);
}
}
void ex_mpool_clear(ex_mpool *pmp)
{
pmp->index = 0;
pmp->cflag = 0;
}

24
src/mempool.h Normal file
View file

@ -0,0 +1,24 @@
#ifndef __ESERV_MPOOL_H__
#define __ESERV_MPOOL_H__
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
char *begin; /* start pos */
size_t len; /* capacity */
int index; /* curIndex */
int cflag; /* clear flag */
} ex_mpool;
void ex_mpool_init(ex_mpool *pmp, char *begin, size_t len);
void *ex_mpool_malloc(ex_mpool *pmp, size_t mlen);
void ex_mpool_free(ex_mpool *pmp, void *p);
void ex_mpool_clear(ex_mpool *pmp);
#ifdef __cplusplus
}
#endif
#endif