diff options
-rw-r--r-- | common/stringop.c | 33 | ||||
-rw-r--r-- | include/stringop.h | 9 |
2 files changed, 42 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 @@ | |||
1 | #define _POSIX_C_SOURCE 200809L | 1 | #define _POSIX_C_SOURCE 200809L |
2 | #include <ctype.h> | 2 | #include <ctype.h> |
3 | #include <stdarg.h> | ||
3 | #include <stdbool.h> | 4 | #include <stdbool.h> |
4 | #include <stdio.h> | 5 | #include <stdio.h> |
5 | #include <stdlib.h> | 6 | #include <stdlib.h> |
@@ -328,3 +329,35 @@ bool expand_path(char **path) { | |||
328 | wordfree(&p); | 329 | wordfree(&p); |
329 | return true; | 330 | return true; |
330 | } | 331 | } |
332 | |||
333 | char *vformat_str(const char *fmt, va_list args) { | ||
334 | char *str = NULL; | ||
335 | va_list args_copy; | ||
336 | va_copy(args_copy, args); | ||
337 | |||
338 | int len = vsnprintf(NULL, 0, fmt, args); | ||
339 | if (len < 0) { | ||
340 | sway_log_errno(SWAY_ERROR, "vsnprintf(\"%s\") failed", fmt); | ||
341 | goto out; | ||
342 | } | ||
343 | |||
344 | str = malloc(len + 1); | ||
345 | if (str == NULL) { | ||
346 | sway_log_errno(SWAY_ERROR, "malloc() failed"); | ||
347 | goto out; | ||
348 | } | ||
349 | |||
350 | vsnprintf(str, len + 1, fmt, args_copy); | ||
351 | |||
352 | out: | ||
353 | va_end(args_copy); | ||
354 | return str; | ||
355 | } | ||
356 | |||
357 | char *format_str(const char *fmt, ...) { | ||
358 | va_list args; | ||
359 | va_start(args, fmt); | ||
360 | char *str = vformat_str(fmt, args); | ||
361 | va_end(args); | ||
362 | return str; | ||
363 | } | ||
diff --git a/include/stringop.h b/include/stringop.h index b29f59b2..19a50f23 100644 --- a/include/stringop.h +++ b/include/stringop.h | |||
@@ -5,6 +5,12 @@ | |||
5 | #include <stddef.h> | 5 | #include <stddef.h> |
6 | #include "list.h" | 6 | #include "list.h" |
7 | 7 | ||
8 | #ifdef __GNUC__ | ||
9 | #define _SWAY_ATTRIB_PRINTF(start, end) __attribute__((format(printf, start, end))) | ||
10 | #else | ||
11 | #define _SWAY_ATTRIB_PRINTF(start, end) | ||
12 | #endif | ||
13 | |||
8 | void strip_whitespace(char *str); | 14 | void strip_whitespace(char *str); |
9 | void strip_quotes(char *str); | 15 | void strip_quotes(char *str); |
10 | 16 | ||
@@ -31,4 +37,7 @@ char *argsep(char **stringp, const char *delim, char *matched_delim); | |||
31 | // Expand a path using shell replacements such as $HOME and ~ | 37 | // Expand a path using shell replacements such as $HOME and ~ |
32 | bool expand_path(char **path); | 38 | bool expand_path(char **path); |
33 | 39 | ||
40 | char *vformat_str(const char *fmt, va_list args) _SWAY_ATTRIB_PRINTF(1, 0); | ||
41 | char *format_str(const char *fmt, ...) _SWAY_ATTRIB_PRINTF(1, 2); | ||
42 | |||
34 | #endif | 43 | #endif |