From 47605e1dfabd856d68fbf1971e2ad99f3063cdfd Mon Sep 17 00:00:00 2001 From: "Daniel P. Berrange" Date: Tue, 24 Jun 2008 15:00:15 +0000 Subject: [PATCH] Added helpers for dealing with enumerations --- ChangeLog | 5 +++++ src/util.c | 22 ++++++++++++++++++++++ src/util.h | 28 ++++++++++++++++++++++++++++ 3 files changed, 55 insertions(+) diff --git a/ChangeLog b/ChangeLog index a3fe8dccdc..0c6ef6de3f 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ +Tue Jun 24 15:59:33 EST 2008 Daniel P. Berrange + + * src/util.h, src/util.c: Added helpers for managing enumerations + and conversion to/from string vs integer format + Tue Jun 24 15:29:33 EST 2008 Daniel P. Berrange * src/storage_backend.h, src/storage_backend.c: Fix const-ness diff --git a/src/util.c b/src/util.c index 5e50ef2f3b..3980d1ba5b 100644 --- a/src/util.c +++ b/src/util.c @@ -764,6 +764,28 @@ virParseMacAddr(const char* str, unsigned char *addr) return -1; } +int virEnumFromString(const char *const*types, + unsigned int ntypes, + const char *type) +{ + unsigned int i; + for (i = 0 ; i < ntypes ; i++) + if (STREQ(types[i], type)) + return i; + + return -1; +} + +const char *virEnumToString(const char *const*types, + unsigned int ntypes, + int type) +{ + if (type < 0 || type >= ntypes) + return NULL; + + return types[type]; +} + /* Translates a device name of the form (regex) "[fhv]d[a-z]+" into * the corresponding index (e.g. sda => 1, hdz => 26, vdaa => 27) * @param name The name of the device diff --git a/src/util.h b/src/util.h index 9a634672ab..a0cd109d57 100644 --- a/src/util.h +++ b/src/util.h @@ -25,6 +25,7 @@ #define __VIR_UTIL_H__ #include "util-lib.h" +#include "verify.h" int virExec(virConnectPtr conn, char **argv, int *retpid, int infd, int *outfd, int *errfd); @@ -88,4 +89,31 @@ int virParseMacAddr(const char* str, unsigned char *addr); int virDiskNameToIndex(const char* str); + +int virEnumFromString(const char *const*types, + unsigned int ntypes, + const char *type); + +const char *virEnumToString(const char *const*types, + unsigned int ntypes, + int type); + +#define VIR_ENUM_IMPL(name, lastVal, ...) \ + static const char const *name ## TypeList[] = { __VA_ARGS__ }; \ + verify(ARRAY_CARDINALITY(name ## TypeList) == lastVal); \ + const char *name ## TypeToString(int type) { \ + return virEnumToString(name ## TypeList, \ + ARRAY_CARDINALITY(name ## TypeList), \ + type); \ + } \ + int name ## TypeFromString(const char *type) { \ + return virEnumFromString(name ## TypeList, \ + ARRAY_CARDINALITY(name ## TypeList), \ + type); \ + } + +#define VIR_ENUM_DECL(name) \ + const char *name ## TypeToString(int type); \ + int name ## TypeFromString(const char*type); + #endif /* __VIR_UTIL_H__ */