diff options
author | Simon Ser <contact@emersion.fr> | 2023-02-28 16:00:28 +0100 |
---|---|---|
committer | Simon Ser <contact@emersion.fr> | 2023-04-14 18:34:54 +0200 |
commit | aab4c9da5fb4138ca5f07df8bd8b698d02242a62 (patch) | |
tree | 4f26a160ebce948ca29855da4f05fa42e3c5e815 /common | |
parent | 4118c493499fc03fd2c77a061b4905cd7523d67c (diff) |
Add format_str() and vformat_str()
Simple helpers to allocate and format a string.
Diffstat (limited to 'common')
-rw-r--r-- | common/stringop.c | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/common/stringop.c b/common/stringop.c index 7fb3fe12..c503143a 100644 --- a/common/stringop.c +++ b/common/stringop.c @@ -1,5 +1,6 @@ #define _POSIX_C_SOURCE 200809L #include <ctype.h> +#include <stdarg.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> @@ -328,3 +329,35 @@ bool expand_path(char **path) { wordfree(&p); return true; } + +char *vformat_str(const char *fmt, va_list args) { + char *str = NULL; + va_list args_copy; + va_copy(args_copy, args); + + int len = vsnprintf(NULL, 0, fmt, args); + if (len < 0) { + sway_log_errno(SWAY_ERROR, "vsnprintf(\"%s\") failed", fmt); + goto out; + } + + str = malloc(len + 1); + if (str == NULL) { + sway_log_errno(SWAY_ERROR, "malloc() failed"); + goto out; + } + + vsnprintf(str, len + 1, fmt, args_copy); + +out: + va_end(args_copy); + return str; +} + +char *format_str(const char *fmt, ...) { + va_list args; + va_start(args, fmt); + char *str = vformat_str(fmt, args); + va_end(args); + return str; +} |