mirror of
https://github.com/yshui/picom.git
synced 2025-04-14 17:53:25 -04:00
string_utils: add asnprintf
Signed-off-by: Yuxuan Shui <yshuiv7@gmail.com>
This commit is contained in:
parent
1746473a0b
commit
7899bafb88
2 changed files with 33 additions and 1 deletions
|
@ -1,6 +1,7 @@
|
|||
// SPDX-License-Identifier: MPL-2.0
|
||||
// Copyright (c) Yuxuan Shui <yshuiv7@gmail.com>
|
||||
|
||||
#include <stdarg.h>
|
||||
#include <string.h>
|
||||
|
||||
#include <test.h>
|
||||
|
@ -166,3 +167,30 @@ TEST_CASE(trim_both) {
|
|||
TEST_EQUAL(length, 9);
|
||||
TEST_STRNEQUAL(str, "asdf asdf", length);
|
||||
}
|
||||
|
||||
static int vasnprintf(char **strp, size_t *capacity, const char *fmt, va_list args) {
|
||||
va_list copy;
|
||||
va_copy(copy, args);
|
||||
int needed = vsnprintf(*strp, *capacity, fmt, copy);
|
||||
va_end(copy);
|
||||
|
||||
if ((size_t)needed + 1 > *capacity) {
|
||||
char *new_str = malloc((size_t)needed + 1);
|
||||
allocchk(new_str);
|
||||
free(*strp);
|
||||
*strp = new_str;
|
||||
*capacity = (size_t)needed + 1;
|
||||
} else {
|
||||
return needed;
|
||||
}
|
||||
|
||||
return vsnprintf(*strp, *capacity, fmt, args);
|
||||
}
|
||||
|
||||
int asnprintf(char **strp, size_t *capacity, const char *fmt, ...) {
|
||||
va_list args;
|
||||
va_start(args, fmt);
|
||||
int ret = vasnprintf(strp, capacity, fmt, args);
|
||||
va_end(args);
|
||||
return ret;
|
||||
}
|
||||
|
|
|
@ -57,4 +57,8 @@ static inline char *skip_space_mut(char *src) {
|
|||
}
|
||||
|
||||
#define skip_space(x) \
|
||||
_Generic((x), char * : skip_space_mut, const char * : skip_space_const)(x)
|
||||
_Generic((x), char *: skip_space_mut, const char *: skip_space_const)(x)
|
||||
|
||||
/// Similar to `asprintf`, but it reuses the allocated memory pointed to by `*strp`, and
|
||||
/// reallocates it if it's not big enough.
|
||||
int asnprintf(char **strp, size_t *capacity, const char *fmt, ...);
|
||||
|
|
Loading…
Add table
Reference in a new issue