summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorThomas Haller <thaller@redhat.com>2018-09-21 15:45:59 +0200
committerThomas Haller <thaller@redhat.com>2018-10-19 00:13:08 +0200
commit2c685fc3e02b364d95450c6c1a00117e2ece5d63 (patch)
treedf404f09488426485937eba18ce5fe7cd43df0a0
parenta1831d1832391069573f7116159671fa39984c01 (diff)
downloadNetworkManager-2c685fc3e02b364d95450c6c1a00117e2ece5d63.tar.gz
shared: add nm_strndup_a() helper
(cherry picked from commit ba491a6674d322371ed1c989afc1ecee79a63c1a)
-rw-r--r--shared/nm-utils/nm-shared-utils.h31
1 files changed, 31 insertions, 0 deletions
diff --git a/shared/nm-utils/nm-shared-utils.h b/shared/nm-utils/nm-shared-utils.h
index 28d04b2951..3ea887b468 100644
--- a/shared/nm-utils/nm-shared-utils.h
+++ b/shared/nm-utils/nm-shared-utils.h
@@ -262,6 +262,37 @@ nm_memdup (gconstpointer data, gsize size)
return p;
}
+/* Similar to g_strndup(), however, if the string (including the terminating
+ * NUL char) fits into alloca_maxlen, this will alloca() the memory.
+ *
+ * It's a mix of strndup() and strndupa(), but deciding based on @alloca_maxlen
+ * which one to use.
+ *
+ * In case malloc() is necessary, @out_str_free will be set (this string
+ * must be freed afterwards). It is permissible to pass %NULL as @out_str_free,
+ * if you ensure that len < alloca_maxlen. */
+#define nm_strndup_a(alloca_maxlen, str, len, out_str_free) \
+ ({ \
+ const gsize _alloca_maxlen = (alloca_maxlen); \
+ const char *const _str = (str); \
+ const gsize _len = (len); \
+ char **const _out_str_free = (out_str_free); \
+ char *_s; \
+ \
+ if ( _out_str_free \
+ && _len >= _alloca_maxlen) { \
+ _s = g_malloc (_len + 1); \
+ *_out_str_free = _s; \
+ } else { \
+ g_assert (_len < _alloca_maxlen); \
+ _s = g_alloca (_len + 1); \
+ } \
+ if (_len > 0) \
+ strncpy (_s, _str, _len); \
+ _s[_len] = '\0'; \
+ _s; \
+ })
+
/*****************************************************************************/
extern const void *const _NM_PTRARRAY_EMPTY[1];