From d5d45c8ce6fc282286372ae0c2ba1f438ef96985 Mon Sep 17 00:00:00 2001 From: Thomas Haller Date: Wed, 23 Sep 2020 11:49:17 +0200 Subject: [PATCH] libnm: cleanup nm_utils_hwaddr_canonical() and nm_utils_hwaddr_valid() - only call hwaddr_aton() once per function. Also, pass it sizeof(buf) as buffer size, it seems more correct. - the only downside is that we now would always first parse up to 20 characters, before comparing the requested length. Previously, a MAC address that was too long was rejected earlier (and the parsing aborted earlier). But that is a tiny overhead, also we expect that in common cases the MAC addresses are in fact of the right size, then there is no difference. --- libnm-core/nm-utils.c | 38 +++++++++++++++++--------------------- 1 file changed, 17 insertions(+), 21 deletions(-) diff --git a/libnm-core/nm-utils.c b/libnm-core/nm-utils.c index e066d00cd7..ff6d5d6cdc 100644 --- a/libnm-core/nm-utils.c +++ b/libnm-core/nm-utils.c @@ -4217,17 +4217,17 @@ nm_utils_hwaddr_valid (const char *asc, gssize length) gsize l; g_return_val_if_fail (asc != NULL, FALSE); + g_return_val_if_fail ( length >= -1 + && length <= NM_UTILS_HWADDR_LEN_MAX, FALSE); - if (length > 0 && length <= NM_UTILS_HWADDR_LEN_MAX) { - if (!hwaddr_aton (asc, buf, length, &l)) - return FALSE; - return length == l; - } else if (length == -1) - return !!hwaddr_aton (asc, buf, sizeof (buf), &l); - else if (length == 0) + if (length == 0) return FALSE; - else - g_return_val_if_reached (FALSE); + + if (!hwaddr_aton (asc, buf, sizeof (buf), &l)) + return FALSE; + + return length == -1 + || length == (gssize) l; } /** @@ -4250,19 +4250,15 @@ nm_utils_hwaddr_canonical (const char *asc, gssize length) gsize l; g_return_val_if_fail (asc, NULL); - g_return_val_if_fail (length == -1 || (length > 0 && length <= NM_UTILS_HWADDR_LEN_MAX), NULL); - - if (length > 0 && length <= NM_UTILS_HWADDR_LEN_MAX) { - if (!hwaddr_aton (asc, buf, length, &l)) - return NULL; - if (l != length) - return NULL; - } else if (length == -1) { - if (!hwaddr_aton (asc, buf, NM_UTILS_HWADDR_LEN_MAX, &l)) - return NULL; - } else - g_return_val_if_reached (NULL); + g_return_val_if_fail ( length == -1 + || ( length > 0 + && length <= NM_UTILS_HWADDR_LEN_MAX), NULL); + if (!hwaddr_aton (asc, buf, sizeof (buf), &l)) + return NULL; + if ( length != -1 + && length != (gssize) l) + return NULL; return nm_utils_hwaddr_ntoa (buf, l); }