From: Wei Hou Date: Thu, 1 Jun 2023 18:15:33 +0000 (+0200) Subject: util/types: Add generic spinner X-Git-Tag: v2.5~70 X-Git-Url: https://www.infradead.org/git/?a=commitdiff_plain;h=1a14c12b12b0806fc41b965954cf17b5e56094e5;p=users%2Fsagi%2Fnvme-cli.git util/types: Add generic spinner Signed-off-by: Wei Hou --- diff --git a/util/types.c b/util/types.c index 22782522..044391d4 100644 --- a/util/types.c +++ b/util/types.c @@ -169,3 +169,35 @@ int convert_ts(time_t time, char *ts_buf) return 0; } + +void util_spinner(const char *disp_name, float percent) +{ + static const char dash[51] = {[0 ... 49] = '=', '\0'}; + static const char space[51] = {[0 ... 49] = ' ', '\0'}; + static const char spin[] = {'-', '\\', '|', '/' }; + static int progress; + static int i; + const char *dn = disp_name ? disp_name : ""; + + if (percent < 0) + percent = 0; + else if (percent > 1) + percent = 1; + + progress = (int)(percent * 100.0); + if (progress < 2) + printf("\r%s [%c%.*s] %3d%%", dn, + spin[i % 4], 49, + space, progress); + else if (progress < 100) + printf("\r%s [%.*s%c%.*s] %3d%%", dn, + progress / 2 - 1, dash, + spin[i % 4], 50 - progress / 2, + space, progress); + else + printf("\r%s [%.*s] %3d%%\n", dn, + 50, dash, 100); + i++; + + fflush(stdout); +} diff --git a/util/types.h b/util/types.h index 6bb67c51..595958bb 100644 --- a/util/types.h +++ b/util/types.h @@ -45,4 +45,16 @@ const char *util_fw_to_string(char *c); */ int convert_ts(time_t time, char *ts_buf); +/** + * @brief print once a progress of spinner to stdout + * the output will be looks like if disp_name is "LogDump" and percent is 0.5 + * LogDump [========================- ] 50% + + * + * @param disp_name, const string displayed before spiner + * @param percent [0, 1.0] about the progress + * + */ +void util_spinner(const char *disp_name, float percent); + #endif /* _MISC_H */