From ac36e48d688402aada39245545c0c3e7bbbc7c3b Mon Sep 17 00:00:00 2001 From: Thomas Haller Date: Thu, 29 Jul 2021 08:36:57 +0200 Subject: [PATCH] glib-aux: accept any strv pointer at nm_utils_strv_find_first() via NM_CAST_STRV_CC() macro We commonly have strv arrays as (char **), (const char*const*) or (const char **). We thus need to frequently cast the argument to nm_utils_strv_find_first(). Explicit casts in C don't make the code more typesafe, because they silently allow completely wrong casts too. On the other hand, changing the function argument to (const void *) also allows any pointer, and not just strv pointers. NM_CAST_STRV_CC() casts the the pointer to a (const char*const*) strv pointer. It uses _Generic() to only cast a string array, and not completely unrelated pointers. As such, it is more convenient to use, as it requires the user no longer to cast the strv argument, while still being strict about which types are accepted. --- src/libnm-glib-aux/nm-shared-utils.c | 4 ++-- src/libnm-glib-aux/nm-shared-utils.h | 5 ++++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/libnm-glib-aux/nm-shared-utils.c b/src/libnm-glib-aux/nm-shared-utils.c index 83f073d39d..c6e640e0a1 100644 --- a/src/libnm-glib-aux/nm-shared-utils.c +++ b/src/libnm-glib-aux/nm-shared-utils.c @@ -2261,7 +2261,7 @@ nm_utils_strsplit_quoted(const char *str) /*****************************************************************************/ /** - * nm_utils_strv_find_first: + * _nm_utils_strv_find_first: * @list: the strv list to search * @len: the length of the list, or a negative value if @list is %NULL terminated. * @needle: the value to search for. The search is done using strcmp(). @@ -2274,7 +2274,7 @@ nm_utils_strsplit_quoted(const char *str) * Returns: index of first occurrence or -1 if @needle is not found in @list. */ gssize -nm_utils_strv_find_first(char **list, gssize len, const char *needle) +_nm_utils_strv_find_first(const char *const *list, gssize len, const char *needle) { gssize i; diff --git a/src/libnm-glib-aux/nm-shared-utils.h b/src/libnm-glib-aux/nm-shared-utils.h index 9ffb28048b..3120502321 100644 --- a/src/libnm-glib-aux/nm-shared-utils.h +++ b/src/libnm-glib-aux/nm-shared-utils.h @@ -737,7 +737,10 @@ nm_utils_strsplit_set(const char *str, const char *delimiters) return nm_utils_strsplit_set_full(str, delimiters, NM_UTILS_STRSPLIT_SET_FLAGS_NONE); } -gssize nm_utils_strv_find_first(char **list, gssize len, const char *needle); +gssize _nm_utils_strv_find_first(const char *const *list, gssize len, const char *needle); + +#define nm_utils_strv_find_first(list, len, needle) \ + _nm_utils_strv_find_first(NM_CAST_STRV_CC(list), (len), (needle)) gboolean nm_strv_has_duplicate(const char *const *list, gssize len, gboolean is_sorted);