diff options
author | Thomas Haller <thaller@redhat.com> | 2018-09-21 15:45:59 +0200 |
---|---|---|
committer | Thomas Haller <thaller@redhat.com> | 2018-10-04 10:58:50 +0200 |
commit | 0b37c236c4bafacce8195ae3d9d6b93ea944e69f (patch) | |
tree | b8a098b1e92ac44d67f4e8eec8946103b0bb21cb | |
parent | eea1886d935232a2f355e1a32d75aae2612e0110 (diff) |
shared: add nm_strndup_a() helper
-rw-r--r-- | shared/nm-utils/nm-shared-utils.h | 31 |
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 97e030b00..968e375c4 100644 --- a/shared/nm-utils/nm-shared-utils.h +++ b/shared/nm-utils/nm-shared-utils.h @@ -236,6 +236,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]; |