1
2 /*
3 * Redistribution and use in source and binary forms, with or
4 * without modification, are permitted provided that the following
5 * conditions are met:
6 *
7 * 1. Redistributions of source code must retain the above
8 * copyright notice, this list of conditions and the
9 * following disclaimer.
10 *
11 * 2. Redistributions in binary form must reproduce the above
12 * copyright notice, this list of conditions and the following
13 * disclaimer in the documentation and/or other materials
14 * provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
18 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
20 * <COPYRIGHT HOLDER> OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
21 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
24 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
27 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28 * SUCH DAMAGE.
29 */
30
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include <string.h>
34
35 #include <tarantool/tnt_mem.h>
36
custom_realloc(void * ptr,size_t size)37 static void *custom_realloc(void *ptr, size_t size) {
38 if (!ptr) {
39 if (!size)
40 return NULL;
41 return calloc(1, size);
42 }
43 if (size)
44 return realloc(ptr, size);
45 free(ptr);
46 return NULL;
47 }
48
49 /*
50 static void *(*_tnt_realloc)(void *ptr, size_t size) =
51 (void *(*)(void*, size_t))realloc;
52 */
53
54 static void *(*_tnt_realloc)(void *ptr, size_t size) = custom_realloc;
55
tnt_mem_init(tnt_allocator_t alloc)56 void *tnt_mem_init(tnt_allocator_t alloc) {
57 void *ptr = _tnt_realloc;
58 if (alloc)
59 _tnt_realloc = alloc;
60 return ptr;
61 }
62
tnt_mem_alloc(size_t size)63 void *tnt_mem_alloc(size_t size) {
64 return _tnt_realloc(NULL, size);
65 }
66
tnt_mem_realloc(void * ptr,size_t size)67 void *tnt_mem_realloc(void *ptr, size_t size) {
68 return _tnt_realloc(ptr, size);
69 }
70
tnt_mem_dup(char * sz)71 char *tnt_mem_dup(char *sz) {
72 size_t len = strlen(sz);
73 char *szp = tnt_mem_alloc(len + 1);
74 if (szp == NULL)
75 return NULL;
76 memcpy(szp, sz, len + 1);
77 return szp;
78 }
79
tnt_mem_free(void * ptr)80 void tnt_mem_free(void *ptr) {
81 _tnt_realloc(ptr, 0);
82 }
83