20 const uint64_t redzone_pattern = 0xdeadbeefcafebabe;
24 const int initial_pool_size = 64;
27 static bool inFreeList(
cache_t *cache,
void *
object) {
30 rv |= cache->
ptr[
i] == object;
36 cache_t* cache_create(
const char *
name,
size_t bufsize,
size_t align,
37 cache_constructor_t* constructor,
38 cache_destructor_t* destructor) {
40 char* nm = strdup(name);
41 void** ptr = calloc(initial_pool_size,
sizeof(
void*));
42 if (ret == NULL || nm == NULL || ptr == NULL ||
43 pthread_mutex_init(&ret->
mutex, NULL) == -1) {
57 ret->
bufsize = bufsize + 2 *
sizeof(redzone_pattern);
65 static inline void* get_object(
void *ptr) {
74 void cache_destroy(
cache_t *cache) {
84 pthread_mutex_destroy(&cache->
mutex);
87 void* cache_alloc(
cache_t *cache) {
90 pthread_mutex_lock(&cache->
mutex);
93 object = get_object(ret);
94 assert(!inFreeList(cache, ret));
96 object = ret = malloc(cache->
bufsize);
98 object = get_object(ret);
107 pthread_mutex_unlock(&cache->
mutex);
110 if (
object != NULL) {
113 *pre = redzone_pattern;
115 memcpy(((
char*)ret) + cache->
bufsize - (2 *
sizeof(redzone_pattern)),
116 &redzone_pattern,
sizeof(redzone_pattern));
123 void cache_free(
cache_t *cache,
void *
object) {
125 pthread_mutex_lock(&cache->
mutex);
129 if (memcmp(((
char*)ptr) + cache->
bufsize - (2 *
sizeof(redzone_pattern)),
130 &redzone_pattern,
sizeof(redzone_pattern)) != 0) {
133 pthread_mutex_unlock(&cache->
mutex);
138 if (*pre != redzone_pattern) {
141 pthread_mutex_unlock(&cache->
mutex);
146 assert(!inFreeList(cache, ptr));
149 assert(inFreeList(cache, ptr));
153 void **new_free = realloc(cache->
ptr,
sizeof(
char *) * newtotal);
156 cache->
ptr = new_free;
158 assert(inFreeList(cache, ptr));
164 assert(!inFreeList(cache, ptr));
167 pthread_mutex_unlock(&cache->
mutex);