drop mem_alloc and mem_free, use my own hand crafted optmized macros that
[apps/madmutt.git] / lib-lib / mem.h
1 /*
2  *  This program is free software; you can redistribute it and/or modify it
3  *  under the terms of the GNU General Public License as published by the Free
4  *  Software Foundation; either version 2 of the License, or (at your option)
5  *  any later version.
6  *
7  *  This program is distributed in the hope that it will be useful, but
8  *  WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
9  *  or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
10  *  for more details.
11  *
12  *  You should have received a copy of the GNU General Public License along
13  *  with this program; if not, write to the Free Software Foundation, Inc.,
14  *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * Author: Pierre Habouzit <madcoder@debian.org>
17  */
18
19 #ifndef MUTT_LIB_LIB_MEM_H
20 #define MUTT_LIB_LIB_MEM_H
21
22 #include <stdlib.h>
23 #include <string.h>
24 #include <unistd.h>
25
26 static inline void *xmalloc(ssize_t size) {
27     void *mem;
28
29     if (size <= 0)
30         return NULL;
31
32     mem = calloc(size, 1);
33     if (!mem)
34         abort();
35     return mem;
36 }
37
38 static inline void *xrealloc(void *mem, ssize_t newsize) {
39     mem = realloc(mem, newsize);
40     if (!mem)
41         abort();
42     return mem;
43 }
44
45 static inline void *xmemdup(const void *src, ssize_t size) {
46     return memcpy(xmalloc(size), src, size);
47 }
48
49 static inline void *xmemdupstr(const void *src, ssize_t len) {
50     char *res = xmalloc(len + 1);
51     memcpy(res, src, len);
52     res[len] = '\0';
53     return res;
54 }
55
56 #define p_new(type, count)      ((type *)xmalloc(sizeof(type) * (count)))
57 #define p_clear(p, count)       ((void)memset((p), 0, sizeof(*(p)) * (count)))
58 #define p_dup(p, count)         xmemdup((p), sizeof(*(p)) * (count))
59 #define p_dupstr(p, len)        xmemdupstr((p), (len))
60
61 #ifdef __GNUC__
62
63 #  define p_delete(mem_pp)                          \
64         ({                                          \
65             typeof(**(mem_pp)) **__ptr = (mem_pp);  \
66             free(*__ptr);                           \
67             *__ptr = NULL;                          \
68         })
69
70 #else
71
72 #  define p_delete(mem_p)                           \
73         do {                                        \
74             void *__ptr = (mem_p);                  \
75             free(*__ptr);                           \
76             *(void **)__ptr = NULL;                 \
77         } while (0)
78
79 #endif
80
81 static inline void xmemfree(void **ptr) {
82     p_delete(ptr);
83 }
84
85 #endif /* MUTT_LIB_LIB_MEM_H */