]> git.ipfire.org Git - people/ms/network.git/commitdiff
string: Add macros to easily define string table lookups
authorMichael Tremer <michael.tremer@ipfire.org>
Wed, 7 Jun 2023 13:16:58 +0000 (13:16 +0000)
committerMichael Tremer <michael.tremer@ipfire.org>
Wed, 7 Jun 2023 13:16:58 +0000 (13:16 +0000)
Signed-off-by: Michael Tremer <michael.tremer@ipfire.org>
src/networkd/string.h

index 5bdfc3d24c4949091236c1b3ec75968b12f66e7e..d94e27064e9361261439aa81d5138fbc42e9dc8b 100644 (file)
@@ -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
 */