From eec9efd98950104da7d210318729b7f8600df229 Mon Sep 17 00:00:00 2001 From: Thomas Haller Date: Thu, 25 Aug 2022 23:07:44 +0200 Subject: 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. --- src/libnm-core-impl/tests/test-general.c | 9 +++++++++ src/libnm-glib-aux/nm-enum-utils.c | 6 +++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/libnm-core-impl/tests/test-general.c b/src/libnm-core-impl/tests/test-general.c index 19d3271944..bcf86917e8 100644 --- a/src/libnm-core-impl/tests/test-general.c +++ b/src/libnm-core-impl/tests/test-general.c @@ -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"); diff --git a/src/libnm-glib-aux/nm-enum-utils.c b/src/libnm-glib-aux/nm-enum-utils.c index b7f7a3f6cc..2593a9cdfd 100644 --- a/src/libnm-glib-aux/nm-enum-utils.c +++ b/src/libnm-glib-aux/nm-enum-utils.c @@ -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; -- cgit v1.2.1