enum: Allow specifying the name used when none of the flags are set
This commit is contained in:
@@ -66,16 +66,17 @@ bool enum_from_name_as_int(enum_name_t *e, const char *name, int *val)
|
||||
/**
|
||||
* Get the position of a flag name using offset calculation
|
||||
*/
|
||||
static int find_flag_pos(u_int val, u_int first)
|
||||
static int find_flag_pos(u_int first, u_int val)
|
||||
{
|
||||
int offset = 0;
|
||||
|
||||
while (val != 0x01)
|
||||
while (first != 0x01)
|
||||
{
|
||||
val = val >> 1;
|
||||
first = first >> 1;
|
||||
offset++;
|
||||
}
|
||||
return first - offset;
|
||||
/* skip the first name as that's used if no flag is set */
|
||||
return 1 + val - offset;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -95,7 +96,7 @@ char *enum_flags_to_string(enum_name_t *e, u_int val, char *buf, size_t len)
|
||||
return buf;
|
||||
}
|
||||
|
||||
if (snprintf(buf, len, "(unset)") >= len)
|
||||
if (snprintf(buf, len, e->names[0]) >= len)
|
||||
{
|
||||
return NULL;
|
||||
}
|
||||
|
||||
@@ -130,13 +130,14 @@ struct enum_name_t {
|
||||
* @param name name of the enum_name list
|
||||
* @param first enum value of the first enum string
|
||||
* @param last enum value of the last enum string
|
||||
* @param unset name used if no flags are set
|
||||
* @param ... a list of strings
|
||||
*/
|
||||
#define ENUM_FLAGS(name, first, last, ...) \
|
||||
#define ENUM_FLAGS(name, first, last, unset, ...) \
|
||||
static enum_name_t name##last = {first, last + \
|
||||
BUILD_ASSERT((__builtin_ffs(last)-__builtin_ffs(first)+1) == \
|
||||
countof(((char*[]){__VA_ARGS__}))), \
|
||||
ENUM_FLAG_MAGIC, { __VA_ARGS__ }}; ENUM_END(name, last)
|
||||
ENUM_FLAG_MAGIC, { unset, __VA_ARGS__ }}; ENUM_END(name, last)
|
||||
|
||||
/**
|
||||
* Convert a enum value to its string representation.
|
||||
|
||||
Reference in New Issue
Block a user