Merge in conversion to C++.
[m6w6/libmemcached] / libmemcached / allocators.cc
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 struct memcached_allocator_t memcached_allocators_return_default(void)
39 {
40 static struct memcached_allocator_t global_default_allocator= { _libmemcached_calloc, _libmemcached_free, _libmemcached_malloc, _libmemcached_realloc, 0 };
41 return global_default_allocator;
42 }
43
44 memcached_return_t memcached_set_memory_allocators(memcached_st *ptr,
45 memcached_malloc_fn mem_malloc,
46 memcached_free_fn mem_free,
47 memcached_realloc_fn mem_realloc,
48 memcached_calloc_fn mem_calloc,
49 void *context)
50 {
51 /* All should be set, or none should be set */
52 if (mem_malloc == NULL && mem_free == NULL && mem_realloc == NULL && mem_calloc == NULL)
53 {
54 ptr->allocators= memcached_allocators_return_default();
55 }
56 else if (mem_malloc == NULL || mem_free == NULL || mem_realloc == NULL || mem_calloc == NULL)
57 {
58 return MEMCACHED_FAILURE;
59 }
60 else
61 {
62 ptr->allocators.malloc= mem_malloc;
63 ptr->allocators.free= mem_free;
64 ptr->allocators.realloc= mem_realloc;
65 ptr->allocators.calloc= mem_calloc;
66 ptr->allocators.context= context;
67 }
68
69 return MEMCACHED_SUCCESS;
70 }
71
72 void *memcached_get_memory_allocators_context(const memcached_st *ptr)
73 {
74 return ptr->allocators.context;
75 }
76
77 void memcached_get_memory_allocators(const memcached_st *ptr,
78 memcached_malloc_fn *mem_malloc,
79 memcached_free_fn *mem_free,
80 memcached_realloc_fn *mem_realloc,
81 memcached_calloc_fn *mem_calloc)
82 {
83 *mem_malloc= ptr->allocators.malloc;
84 *mem_free= ptr->allocators.free;
85 *mem_realloc= ptr->allocators.realloc;
86 *mem_calloc= ptr->allocators.calloc;
87 }