shared: add nm_str_is_empty() helper

We have nm_str_not_empty() which is the inverse of that. The purpose
of nm_str_not_empty() is to normalize a string to either return
%NULL or a non-empty string, like

   const char *
   get_name (Object *obj)
   {
        return nm_str_not_empty (obj->name);
   }

Sometimes, we however want to check whether a string is not empty.
So, we previously had two choices:

1) use a temporary variable:

     const char *tmp;

     tmp = get_string ();
     if (tmp && tmp[0])
        ...

The problem with this variant is that it's more verbose (by requiring a
temporary variable). Another downside is that there are multiple ways
how to check for an empty string (!tmp[0], tmp[0] == '\0', !strlen (tmp),
strlen (tmp) == 0), and sure enough they are all in use.

2) use !nm_str_not_empty(). But this double negation looks really odd
and confusing.

Add nm_str_is_empty() instead.
This commit is contained in:
Thomas Haller 2020-05-08 10:46:13 +02:00
parent f6e41c19ff
commit dbf14dc38c
No known key found for this signature in database
GPG key ID: 29C2366E4DFC5728

View file

@ -989,16 +989,23 @@ nm_gstring_add_space_delimiter (GString *str)
return str;
}
static inline gboolean
nm_str_is_empty (const char *str)
{
/* %NULL is also accepted, and also "empty". */
return !str || !str[0];
}
static inline const char *
nm_str_not_empty (const char *str)
{
return str && str[0] ? str : NULL;
return !nm_str_is_empty (str) ? str : NULL;
}
static inline char *
nm_strdup_not_empty (const char *str)
{
return str && str[0] ? g_strdup (str) : NULL;
return !nm_str_is_empty (str) ? g_strdup (str) : NULL;
}
static inline char *