enum: Add helper to parse enum flags from strings

Individual flag names are separated by |.
This commit is contained in:
Tobias Brunner
2022-04-14 18:42:01 +02:00
parent 4f4d4021b4
commit 7137fd96c2
3 changed files with 149 additions and 9 deletions
+49
View File
@@ -17,6 +17,7 @@
#include <stdio.h>
#include <library.h>
#include <collections/enumerator.h>
#include <utils/utils.h>
#include "enum.h"
@@ -135,6 +136,54 @@ char *enum_flags_to_string(enum_name_t *e, u_int val, char *buf, size_t len)
return buf;
}
/*
* Described in header
*/
bool enum_flags_from_string_as_int(enum_name_t *e, const char *str, u_int *val)
{
enumerator_t *enumerator;
char *name;
*val = 0;
if (!str || !*str)
{
return TRUE;
}
else if (e->next != ENUM_FLAG_MAGIC)
{
return enum_from_name_as_int(e, str, val);
}
enumerator = enumerator_create_token(str, "|", " ");
while (enumerator->enumerate(enumerator, &name))
{
u_int flag, i;
bool found = FALSE;
if (strcaseeq(name, e->names[0]))
{ /* accept name used if no flags are set */
continue;
}
for (i = 1, flag = e->first; flag <= e->last; i++, flag <<= 1)
{
if (e->names[i] && strcaseeq(name, e->names[i]))
{
*val |= flag;
found = TRUE;
break;
}
}
if (!found)
{
enumerator->destroy(enumerator);
return FALSE;
}
}
enumerator->destroy(enumerator);
return TRUE;
}
/**
* See header.
*/