1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
From 6cc09f9717ebb657e9136ad138aa7e0ba5093704 Mon Sep 17 00:00:00 2001
From: Vladimir Davydov <vdavydov@tarantool.org>
Date: Mon, 27 Sep 2021 14:21:57 +0300
Subject: Move xmalloc to trivia/util.h
We want to use the xmalloc helper throughout the code, not only in
the core lib. Move its definition to trivia/util.h and use fprintf+exit
instead of say/panic in order not to create circular dependencies.
---
src/trivia/util.h | 21 +++++++++++++++++++++
1 file changed, 21 insertions(+)
diff --git a/src/trivia/util.h b/src/trivia/util.h
index da5a3705e..82c5911a4 100644
--- a/src/trivia/util.h
+++ b/src/trivia/util.h
@@ -104,6 +104,27 @@ strnindex(const char **haystack, const char *needle, uint32_t len, uint32_t hmax
#define lengthof(array) (sizeof (array) / sizeof ((array)[0]))
#endif
+/**
+ * An x* variant of a memory allocation function calls the original function
+ * and panics if it fails (i.e. it should never return NULL).
+ */
+#define xalloc_impl(size, func, args...) \
+ ({ \
+ void *ret = func(args); \
+ if (unlikely(ret == NULL)) { \
+ fprintf(stderr, "Can't allocate %zu bytes at %s:%d", \
+ (size_t)(size), __FILE__, __LINE__); \
+ exit(EXIT_FAILURE); \
+ } \
+ ret; \
+ })
+
+#define xmalloc(size) xalloc_impl((size), malloc, (size))
+#define xcalloc(n, size) xalloc_impl((n) * (size), calloc, (n), (size))
+#define xrealloc(ptr, size) xalloc_impl((size), realloc, (ptr), (size))
+#define xstrdup(s) xalloc_impl(strlen((s)) + 1, strdup, (s))
+#define xstrndup(s, n) xalloc_impl((n) + 1, strndup, (s), (n))
+
/** \cond public */
/**
--
2.30.2
|