From b9df6009ffbe2dea39b91972c52e426899f94c44 Mon Sep 17 00:00:00 2001 From: Thomas Haller Date: Sun, 24 Jan 2016 13:33:48 +0100 Subject: [PATCH] utils: implement NM_UTILS_STRING_LOOKUP_TABLE_DEFINE() as switch() statement The compiler will likely optimize a switch() statement also to a table lookup, but it also works for negative values and values with large gaps. --- src/NetworkManagerUtils.h | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/NetworkManagerUtils.h b/src/NetworkManagerUtils.h index d6676481e..09bbf4208 100644 --- a/src/NetworkManagerUtils.h +++ b/src/NetworkManagerUtils.h @@ -260,19 +260,20 @@ const char *nm_utils_enum2str (const NMUtilsEnum2StrDesc *descs, /*****************************************************************************/ -#define NM_UTILS_STRING_LOOKUP_TABLE_ITEM(v, n) [v] = n +#define NM_UTILS_STRING_LOOKUP_TABLE_ITEM(v, n) (void) 0; case v: return (n); (void) 0 #define NM_UTILS_STRING_LOOKUP_TABLE_ITEM_S(v, n) NM_UTILS_STRING_LOOKUP_TABLE_ITEM(v, ""n"") #define _NM_UTILS_STRING_LOOKUP_TABLE_DEFINE(scope, fcn_name, lookup_type, unknown_val, ...) \ scope const char * \ -fcn_name (lookup_type idx) \ +fcn_name (lookup_type val) \ { \ - static const char *const descs[] = { \ + switch (val) { \ + default: \ + return (unknown_val); \ + (void) 0, \ __VA_ARGS__ \ + (void) 0; \ }; \ - if ((gsize) idx < G_N_ELEMENTS (descs)) \ - return descs[idx]; \ - return unknown_val; \ } #define NM_UTILS_STRING_LOOKUP_TABLE_DEFINE(fcn_name, lookup_type, unknown_val, ...) \