string-table: add new DUMP_STRING_TABLE() macro
authorLennart Poettering <lennart@poettering.net>
Tue, 22 May 2018 10:06:54 +0000 (12:06 +0200)
committerLennart Poettering <lennart@poettering.net>
Tue, 22 May 2018 11:14:18 +0000 (13:14 +0200)
The macro is inspired by the other string table macros, and takes the
same arguments in the same order and dumps a string table to stdout.
Since it's typesafe it's nice to implement this as macro rather than
regular function.

This new macro is useful for implementing commands such as "systemctl -t
help" and similar, i.e. wherever we want to dump all values of an enum
to stdout.

src/basic/string-table.h

index a39206f..92825c4 100644 (file)
@@ -102,3 +102,18 @@ ssize_t string_table_lookup(const char * const *table, size_t len, const char *k
         _DEFINE_STRING_TABLE_LOOKUP_TO_STRING_FALLBACK(name,type,max,static)
 #define DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING_FALLBACK(name,type,max) \
         _DEFINE_STRING_TABLE_LOOKUP_FROM_STRING_FALLBACK(name,type,max,static)
+
+#define DUMP_STRING_TABLE(name,type,max)                                \
+        do {                                                            \
+                type _k;                                                \
+                flockfile(stdout);                                      \
+                for (_k = 0; _k < (max); _k++) {                        \
+                        const char *_t;                                 \
+                        _t = name##_to_string(_k);                      \
+                        if (!_t)                                        \
+                                continue;                               \
+                        fputs_unlocked(_t, stdout);                     \
+                        fputc_unlocked('\n', stdout);                   \
+                }                                                       \
+                funlockfile(stdout);                                    \
+        } while(false)