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.
This commit is contained in:
@@ -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_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, ...) \
|
#define _NM_UTILS_STRING_LOOKUP_TABLE_DEFINE(scope, fcn_name, lookup_type, unknown_val, ...) \
|
||||||
scope const char * \
|
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__ \
|
__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, ...) \
|
#define NM_UTILS_STRING_LOOKUP_TABLE_DEFINE(fcn_name, lookup_type, unknown_val, ...) \
|
||||||
|
Reference in New Issue
Block a user