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.
This commit is contained in:
Thomas Haller 2021-07-29 08:36:57 +02:00
parent 38c57ec4b9
commit ac36e48d68
No known key found for this signature in database
GPG key ID: 29C2366E4DFC5728
2 changed files with 6 additions and 3 deletions

View file

@ -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;

View file

@ -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);