From 1f3779fcebcd414fb64c91c80311dd6b7b1a17aa Mon Sep 17 00:00:00 2001 From: Jan Vaclav Date: Mon, 16 Oct 2023 10:17:58 +0200 Subject: [PATCH] glib-aux: create nm_strvarray_get_idxnull_or_greturn macro This commit adds a getter macro which checks the bounds of a StrvArray when getting elements, while allowing access at `len` - returning NULL. https://gitlab.freedesktop.org/NetworkManager/NetworkManager/-/merge_requests/1765 --- src/libnm-glib-aux/nm-shared-utils.h | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/libnm-glib-aux/nm-shared-utils.h b/src/libnm-glib-aux/nm-shared-utils.h index fb88578b28..ab2dc013b7 100644 --- a/src/libnm-glib-aux/nm-shared-utils.h +++ b/src/libnm-glib-aux/nm-shared-utils.h @@ -3019,6 +3019,20 @@ nm_strvarray_get_idx(GArray *array, guint idx) return nm_g_array_index(array, const char *, idx); } +/* nm_strvarray_get_idxnull_or_greturn() permits access at `len`, + * returning NULL. If the access is out of bounds, the assertion + * will fail (and also return NULL). */ +#define nm_strvarray_get_idxnull_or_greturn(arr, idx) \ + ({ \ + GArray *_arr = (arr); \ + gsize _idx = (idx); \ + guint _len = nm_g_array_len(_arr); \ + \ + g_return_val_if_fail(_idx <= _len, NULL); \ + \ + _idx == _len ? NULL : nm_strvarray_get_idx(_arr, _idx); \ + }) + static inline const char *const * nm_strvarray_get_strv_non_empty(GArray *arr, guint *length) {