Merge in updates (including removal of some depcrated bits from the examples).
[awesomized/libmemcached] / libmemcached / allocators.c
1 #include "common.h"
2
3 void _libmemcached_free(const memcached_st *ptr, void *mem, void *context)
4 {
5 (void) ptr;
6 (void) context;
7 free(mem);
8 }
9
10 void *_libmemcached_malloc(const memcached_st *ptr, size_t size, void *context)
11 {
12 (void) ptr;
13 (void) context;
14 return malloc(size);
15 }
16
17 void *_libmemcached_realloc(const memcached_st *ptr, void *mem, size_t size, void *context)
18 {
19 (void) ptr;
20 (void) context;
21 return realloc(mem, size);
22 }
23
24 void *_libmemcached_calloc(const memcached_st *ptr, size_t nelem, size_t size, void *context)
25 {
26 if (ptr->allocators.malloc != _libmemcached_malloc)
27 {
28 void *ret = _libmemcached_malloc(ptr, nelem * size, context);
29 if (ret != NULL)
30 memset(ret, 0, nelem * size);
31
32 return ret;
33 }
34
35 return calloc(nelem, size);
36 }
37
38 static const struct _allocators_st global_default_allocator= {
39 .calloc= _libmemcached_calloc,
40 .context= NULL,
41 .free= _libmemcached_free,
42 .malloc= _libmemcached_malloc,
43 .realloc= _libmemcached_realloc
44 };
45
46 struct _allocators_st memcached_allocators_return_default(void)
47 {
48 return global_default_allocator;
49 }
50
51 memcached_return_t memcached_set_memory_allocators(memcached_st *ptr,
52 memcached_malloc_fn mem_malloc,
53 memcached_free_fn mem_free,
54 memcached_realloc_fn mem_realloc,
55 memcached_calloc_fn mem_calloc,
56 void *context)
57 {
58 /* All should be set, or none should be set */
59 if (mem_malloc == NULL && mem_free == NULL && mem_realloc == NULL && mem_calloc == NULL)
60 {
61 ptr->allocators= memcached_allocators_return_default();
62 }
63 else if (mem_malloc == NULL || mem_free == NULL || mem_realloc == NULL || mem_calloc == NULL)
64 {
65 return MEMCACHED_FAILURE;
66 }
67 else
68 {
69 ptr->allocators.malloc= mem_malloc;
70 ptr->allocators.free= mem_free;
71 ptr->allocators.realloc= mem_realloc;
72 ptr->allocators.calloc= mem_calloc;
73 ptr->allocators.context= context;
74 }
75
76 return MEMCACHED_SUCCESS;
77 }
78
79 void *memcached_get_memory_allocators_context(const memcached_st *ptr)
80 {
81 return ptr->allocators.context;
82 }
83
84 void memcached_get_memory_allocators(const memcached_st *ptr,
85 memcached_malloc_fn *mem_malloc,
86 memcached_free_fn *mem_free,
87 memcached_realloc_fn *mem_realloc,
88 memcached_calloc_fn *mem_calloc)
89 {
90 *mem_malloc= ptr->allocators.malloc;
91 *mem_free= ptr->allocators.free;
92 *mem_realloc= ptr->allocators.realloc;
93 *mem_calloc= ptr->allocators.calloc;
94 }