From: Michael Tremer Date: Wed, 7 Jun 2023 13:16:58 +0000 (+0000) Subject: string: Add macros to easily define string table lookups X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=f9975100fdb9b9d66d9f21436e7973f9824bbcde;p=network.git string: Add macros to easily define string table lookups Signed-off-by: Michael Tremer --- diff --git a/src/networkd/string.h b/src/networkd/string.h index 5bdfc3d2..d94e2706 100644 --- a/src/networkd/string.h +++ b/src/networkd/string.h @@ -125,6 +125,51 @@ static inline void nw_string_empty(char* s) { *s = '\0'; } +/* + Tables +*/ + +struct nw_string_table { + const int id; + const char* string; +}; + +static inline const char* nw_string_table_lookup_string( + const struct nw_string_table* table, const int id) { + const struct nw_string_table* entry = NULL; + + for (entry = table; entry->string; entry++) + if (entry->id == id) + return entry->string; + + return NULL; +} + +static inline int nw_string_table_lookup_id( + const struct nw_string_table* table, const char* string) { + const struct nw_string_table* entry = NULL; + + for (entry = table; entry->string; entry++) + if (strcmp(entry->string, string) == 0) + return entry->id; + + return -1; +} + +#define NW_STRING_TABLE_LOOKUP_ID(type, table, method) \ + __attribute__((unused)) static type method(const char* s) { \ + return nw_string_table_lookup_id(table, s); \ + } + +#define NW_STRING_TABLE_LOOKUP_STRING(type, table, method) \ + __attribute__((unused)) static const char* method(const type id) { \ + return nw_string_table_lookup_string(table, id); \ + } + +#define NW_STRING_TABLE_LOOKUP(type, table) \ + NW_STRING_TABLE_LOOKUP_ID(type, table, table ## _from_string) \ + NW_STRING_TABLE_LOOKUP_STRING(type, table, table ## _to_string) + /* Paths */