libutil/util_fmt: Add util_fmt_type_to_name()

Add a function to get the textual name of an enum util_fmt_t value. To
make this robust to changes in the order of elements in the format array
initialize this using named indices.

Reviewed-by: Jan Höppner <hoeppner@linux.ibm.com>
Signed-off-by: Niklas Schnelle <schnelle@linux.ibm.com>
Signed-off-by: Jan Höppner <hoeppner@linux.ibm.com>
This commit is contained in:
Niklas Schnelle
2026-06-17 21:45:35 +02:00
committed by Jan Höppner
parent e8550a4f8d
commit 8a4a4e0557
2 changed files with 35 additions and 5 deletions

View File

@@ -157,6 +157,16 @@ void util_fmt_exit(void);
*/
bool util_fmt_name_to_type(const char *name, enum util_fmt_t *type);
/**
* util_fmt_type_to_name() - Get name of given format type identifier.
* @type: Format type identifier
*
* Get the name corresponding to the given format type identifier.
*
* Return: name of the format type
*/
const char *util_fmt_type_to_name(enum util_fmt_t type);
/**
* util_fmt_set_indent() - Set indentation parameters.
* @base : Base indentation level to apply to all output lines (default 0)

View File

@@ -89,11 +89,26 @@ static const struct {
const char *name;
enum util_fmt_t fmt;
} formats[] = {
{ "json", FMT_JSON },
{ "json-seq", FMT_JSONSEQ },
{ "jsonl", FMT_JSONL },
{ "pairs", FMT_PAIRS },
{ "csv", FMT_CSV },
[FMT_JSON] = {
.name = "json",
.fmt = FMT_JSON
},
[FMT_JSONSEQ] = {
.name = "json-seq",
.fmt = FMT_JSONSEQ
},
[FMT_JSONL] = {
.name = "jsonl",
.fmt = FMT_JSONL
},
[FMT_PAIRS] = {
.name = "pairs",
.fmt = FMT_PAIRS
},
[FMT_CSV] = {
.name = "csv",
.fmt = FMT_CSV
},
};
/* Signal mask for blocking INT and TERM signals. */
@@ -112,6 +127,11 @@ bool util_fmt_name_to_type(const char *name, enum util_fmt_t *type)
return false;
}
const char *util_fmt_type_to_name(enum util_fmt_t type)
{
return formats[type].name;
}
bool util_fmt_is_json(enum util_fmt_t type)
{
switch (type) {