drop mem_alloc and mem_free, use my own hand crafted optmized macros that
[apps/madmutt.git] / lib-lib / mem.h
diff --git a/lib-lib/mem.h b/lib-lib/mem.h
new file mode 100644 (file)
index 0000000..c1eb0b1
--- /dev/null
@@ -0,0 +1,85 @@
+/*
+ *  This program is free software; you can redistribute it and/or modify it
+ *  under the terms of the GNU General Public License as published by the Free
+ *  Software Foundation; either version 2 of the License, or (at your option)
+ *  any later version.
+ *
+ *  This program is distributed in the hope that it will be useful, but
+ *  WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ *  or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ *  for more details.
+ *
+ *  You should have received a copy of the GNU General Public License along
+ *  with this program; if not, write to the Free Software Foundation, Inc.,
+ *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * Author: Pierre Habouzit <madcoder@debian.org>
+ */
+
+#ifndef MUTT_LIB_LIB_MEM_H
+#define MUTT_LIB_LIB_MEM_H
+
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+static inline void *xmalloc(ssize_t size) {
+    void *mem;
+
+    if (size <= 0)
+        return NULL;
+
+    mem = calloc(size, 1);
+    if (!mem)
+        abort();
+    return mem;
+}
+
+static inline void *xrealloc(void *mem, ssize_t newsize) {
+    mem = realloc(mem, newsize);
+    if (!mem)
+        abort();
+    return mem;
+}
+
+static inline void *xmemdup(const void *src, ssize_t size) {
+    return memcpy(xmalloc(size), src, size);
+}
+
+static inline void *xmemdupstr(const void *src, ssize_t len) {
+    char *res = xmalloc(len + 1);
+    memcpy(res, src, len);
+    res[len] = '\0';
+    return res;
+}
+
+#define p_new(type, count)      ((type *)xmalloc(sizeof(type) * (count)))
+#define p_clear(p, count)       ((void)memset((p), 0, sizeof(*(p)) * (count)))
+#define p_dup(p, count)         xmemdup((p), sizeof(*(p)) * (count))
+#define p_dupstr(p, len)        xmemdupstr((p), (len))
+
+#ifdef __GNUC__
+
+#  define p_delete(mem_pp)                          \
+        ({                                          \
+            typeof(**(mem_pp)) **__ptr = (mem_pp);  \
+            free(*__ptr);                           \
+            *__ptr = NULL;                          \
+        })
+
+#else
+
+#  define p_delete(mem_p)                           \
+        do {                                        \
+            void *__ptr = (mem_p);                  \
+            free(*__ptr);                           \
+            *(void **)__ptr = NULL;                 \
+        } while (0)
+
+#endif
+
+static inline void xmemfree(void **ptr) {
+    p_delete(ptr);
+}
+
+#endif /* MUTT_LIB_LIB_MEM_H */