glib-aux: fix nicks for zero flag in nm_utils_enum_to_str()

nm_utils_enum_to_str() can print flags, that is, combinations of
powers of two integers.

It also supports nicks, for certain flags.

When we have a nick for value zero, then that requires special
handling. Otherwise, that zero nick will always show up in the
string representation, although, it should only be used if the
enum value is exactly zero.
This commit is contained in:
Thomas Haller 2022-08-25 23:07:44 +02:00
parent c00873e08f
commit eec9efd989
No known key found for this signature in database
GPG key ID: 29C2366E4DFC5728
2 changed files with 14 additions and 1 deletions

View file

@ -9123,6 +9123,10 @@ test_nm_utils_enum(void)
.nick = "nick-5",
.value = 5,
},
{
.nick = "nick-0",
.value = 0,
},
{
.nick = "nick-red",
.value = NM_TEST_GENERAL_COLOR_FLAGS_RED,
@ -9170,6 +9174,11 @@ test_nm_utils_enum(void)
"nick-5, green",
color_value_infos);
_test_nm_utils_enum_to_str_do_full(color_flags,
0,
"nick-0",
color_value_infos);
_test_nm_utils_enum_from_str_do(bool_enum, "", FALSE, 0, NULL);
_test_nm_utils_enum_from_str_do(bool_enum, " ", FALSE, 0, NULL);
_test_nm_utils_enum_from_str_do(bool_enum, "invalid", FALSE, 0, "invalid");

View file

@ -136,7 +136,8 @@ _nm_utils_enum_to_str_full(GType type,
else
return g_strdup(enum_value->value_nick);
} else if (G_IS_FLAGS_CLASS(klass)) {
unsigned uvalue = (unsigned) value;
unsigned uvalue = (unsigned) value;
gboolean uvalue_was_zero = (uvalue == 0);
GFlagsValue *flags_value;
NMStrBuf strbuf;
@ -147,6 +148,9 @@ _nm_utils_enum_to_str_full(GType type,
for (; value_infos && value_infos->nick; value_infos++) {
nm_assert(_enum_is_valid_flags_nick(value_infos->nick));
if (value_infos->value == 0 && !uvalue_was_zero)
continue;
if (uvalue == 0) {
if (value_infos->value != 0)
continue;