Skip to content
Snippets Groups Projects
Commit f3b5ad97 authored by Vladimir Davydov's avatar Vladimir Davydov Committed by Vladimir Davydov
Browse files

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.
parent b424f44d
No related branches found
No related tags found
No related merge requests found
/*
* SPDX-License-Identifier: BSD-2-Clause
*
* Copyright 2010-2021, Tarantool AUTHORS, please see AUTHORS file.
*/
#pragma once
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include "say.h"
#include "trivia/util.h"
/**
* 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)) \
panic("Can't allocate %zu bytes", (size_t)(size)); \
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))
......@@ -105,6 +105,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 */
/**
......
......@@ -57,7 +57,7 @@ target_link_libraries(uuid.test uuid unit)
add_executable(random.test random.c core_test_utils.c)
target_link_libraries(random.test core unit)
add_executable(xmalloc.test xmalloc.c core_test_utils.c)
target_link_libraries(xmalloc.test core unit)
target_link_libraries(xmalloc.test unit)
add_executable(bps_tree.test bps_tree.cc)
target_link_libraries(bps_tree.test small misc)
......
#include "unit.h"
#include "xmalloc.h"
#include "trivia/util.h"
#include <stddef.h>
#include <string.h>
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment