From 945620624aea21d2d5429bba4f092f8bdf67615e Mon Sep 17 00:00:00 2001 From: Thomas Haller Date: Fri, 3 May 2019 08:32:20 +0200 Subject: [PATCH] shared: add nm_malloc_maybe_a(), nm_malloc0_maybe_a() and nm_memdup_maybe_a() utils --- shared/nm-glib-aux/nm-macros-internal.h | 55 +++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/shared/nm-glib-aux/nm-macros-internal.h b/shared/nm-glib-aux/nm-macros-internal.h index 2da234e112..3e261abfb1 100644 --- a/shared/nm-glib-aux/nm-macros-internal.h +++ b/shared/nm-glib-aux/nm-macros-internal.h @@ -1531,6 +1531,61 @@ nm_memdup (gconstpointer data, gsize size) return p; } +#define nm_malloc_maybe_a(alloca_maxlen, bytes, to_free) \ + ({ \ + const gsize _bytes = (bytes); \ + gpointer _ptr; \ + typeof (to_free) _to_free = (to_free); \ + \ + G_STATIC_ASSERT_EXPR ((alloca_maxlen) <= 500); \ + nm_assert (_to_free && !*_to_free); \ + \ + if (_bytes <= (alloca_maxlen)) { \ + _ptr = g_alloca (_bytes); \ + } else { \ + _ptr = g_malloc (_bytes); \ + *_to_free = _ptr; \ + }; \ + \ + _ptr; \ + }) + +#define nm_malloc0_maybe_a(alloca_maxlen, bytes, to_free) \ + ({ \ + const gsize _bytes = (bytes); \ + gpointer _ptr; \ + typeof (to_free) _to_free = (to_free); \ + \ + G_STATIC_ASSERT_EXPR ((alloca_maxlen) <= 500); \ + nm_assert (_to_free && !*_to_free); \ + \ + if (_bytes <= (alloca_maxlen)) { \ + _ptr = g_alloca (_bytes); \ + memset (_ptr, 0, _bytes); \ + } else { \ + _ptr = g_malloc0 (_bytes); \ + *_to_free = _ptr; \ + }; \ + \ + _ptr; \ + }) + +#define nm_memdup_maybe_a(alloca_maxlen, data, size, to_free) \ + ({ \ + const gsize _size = (size); \ + gpointer _ptr_md = NULL; \ + typeof (to_free) _to_free_md = (to_free); \ + \ + nm_assert (_to_free_md && !*_to_free_md); \ + \ + if (_size > 0u) { \ + _ptr_md = nm_malloc_maybe_a ((alloca_maxlen), _size, _to_free_md); \ + memcpy (_ptr_md, (data), _size); \ + } \ + \ + _ptr_md; \ + }) + static inline char * _nm_strndup_a_step (char *s, const char *str, gsize len) {