shared: fix accessing "str" argument to NM_STR_HAS_PREFIX() macro twice

Macros preferably behave function-like, for example in that they evaluate
arguments exactly ones. Sometimes, we want to evaluate arguments
lazily, like in NM_IN_SET() or nm_g_set_error_take_lazy(). But it
is almost always undesirable to evaluate an argument more than once.

Fix NM_STR_HAS_PREFIX() for that.

Also, rename the local variable to not use the name "_str",
which may be a common name that the caller would like to use.
This commit is contained in:
Thomas Haller 2020-05-05 09:12:01 +02:00
parent 6325297367
commit 5a09292f1f
No known key found for this signature in database
GPG key ID: 29C2366E4DFC5728

View file

@ -929,19 +929,24 @@ nm_streq0 (const char *s1, const char *s2)
#define NM_STR_HAS_PREFIX(str, prefix) \
({ \
const char *const _str = (str); \
const char *const _str_has_prefix = (str); \
\
_str && (strncmp ((str), ""prefix"", NM_STRLEN (prefix)) == 0); \
nm_assert (strlen (prefix) == NM_STRLEN (prefix)); \
\
_str_has_prefix \
&& (strncmp (_str_has_prefix, ""prefix"", NM_STRLEN (prefix)) == 0); \
})
#define NM_STR_HAS_SUFFIX(str, suffix) \
({ \
const char *_str; \
const char *const _str_has_suffix = (str); \
gsize _l; \
\
( (_str = (str)) \
&& ((_l = strlen (_str)) >= NM_STRLEN (suffix)) \
&& (memcmp (&_str[_l - NM_STRLEN (suffix)], \
nm_assert (strlen (suffix) == NM_STRLEN (suffix)); \
\
( _str_has_suffix \
&& ((_l = strlen (_str_has_suffix)) >= NM_STRLEN (suffix)) \
&& (memcmp (&_str_has_suffix[_l - NM_STRLEN (suffix)], \
""suffix"", \
NM_STRLEN (suffix)) == 0)); \
})