Implemented generic enum name to enum value mapping
This commit is contained in:
@@ -16,12 +16,14 @@
|
||||
#include <stddef.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#include <library.h>
|
||||
|
||||
#include "enum.h"
|
||||
|
||||
/**
|
||||
* get the name of an enum value in a enum_name_t list
|
||||
* See header.
|
||||
*/
|
||||
static char *enum_name(enum_name_t *e, int val)
|
||||
char *enum_to_name(enum_name_t *e, int val)
|
||||
{
|
||||
do
|
||||
{
|
||||
@@ -34,6 +36,27 @@ static char *enum_name(enum_name_t *e, int val)
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/**
|
||||
* See header.
|
||||
*/
|
||||
int enum_from_name(enum_name_t *e, char *name)
|
||||
{
|
||||
do
|
||||
{
|
||||
int i, count = e->last - e->first;
|
||||
|
||||
for (i = 0; i < count; i++)
|
||||
{
|
||||
if (strcaseeq(name, e->names[i]))
|
||||
{
|
||||
return e->first + i;
|
||||
}
|
||||
}
|
||||
}
|
||||
while ((e = e->next));
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Described in header.
|
||||
*/
|
||||
@@ -43,7 +66,7 @@ int enum_printf_hook(char *dst, size_t len, printf_hook_spec_t *spec,
|
||||
enum_name_t *ed = *((enum_name_t**)(args[0]));
|
||||
int val = *((int*)(args[1]));
|
||||
|
||||
char *name = enum_name(ed, val);
|
||||
char *name = enum_to_name(ed, val);
|
||||
|
||||
if (name == NULL)
|
||||
{
|
||||
|
||||
@@ -106,6 +106,24 @@ struct enum_name_t {
|
||||
*/
|
||||
#define ENUM(name, first, last, ...) ENUM_BEGIN(name, first, last, __VA_ARGS__); ENUM_END(name, last)
|
||||
|
||||
/**
|
||||
* Convert a enum value to its string representation.
|
||||
*
|
||||
* @param e enum names for this enum value
|
||||
* @param val enum value to get string for
|
||||
* @return string for enum, NULL if not found
|
||||
*/
|
||||
char *enum_to_name(enum_name_t *e, int val);
|
||||
|
||||
/**
|
||||
* Convert a enum string back to its enum value.
|
||||
*
|
||||
* @param e enum names for this enum value
|
||||
* @param name name to get enum value for
|
||||
* @return enum value, -1 if not found
|
||||
*/
|
||||
int enum_from_name(enum_name_t *e, char *name);
|
||||
|
||||
/**
|
||||
* printf hook function for enum_names_t.
|
||||
*
|
||||
|
||||
Reference in New Issue
Block a user