string_utils: add asnprintf

Signed-off-by: Yuxuan Shui <yshuiv7@gmail.com>
This commit is contained in:
Yuxuan Shui 2024-04-29 20:06:58 +01:00
parent 1746473a0b
commit 7899bafb88
No known key found for this signature in database
GPG Key ID: D3A4405BE6CC17F4
2 changed files with 33 additions and 1 deletions

View File

@ -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;
}

View File

@ -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, ...);