Skip to content

Commit 835f0cc

Browse files
committed
Add real function wrappers for asprintf, vasprintf, and jasprintf
1 parent a0d6089 commit 835f0cc

2 files changed

Lines changed: 63 additions & 1 deletion

File tree

c89stringutils/c89stringutils_string_extras.c

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -288,7 +288,6 @@ C89STRINGUTILS_EXPORT size_t c89stringutils_strerrorlen_s(errno_t errnum) {
288288
}
289289
}
290290

291-
#define HAVE_ASPRINTF
292291

293292
#ifndef VA_COPY
294293
#if defined(HAVE_VA_COPY) || defined(va_copy)
@@ -490,3 +489,58 @@ C89STRINGUTILS_EXPORT int c89stringutils_jasprintf(char **unto, const char *fmt,
490489
#if defined(__GNUC__) && __GNUC__ >= 7 && !defined(__clang__)
491490
#pragma GCC diagnostic pop
492491
#endif
492+
493+
494+
#if !defined(HAVE_ASPRINTF)
495+
C89STRINGUTILS_EXPORT int vasprintf(char **str, const char *fmt, va_list ap) {
496+
return c89stringutils_vasprintf(str, fmt, ap);
497+
}
498+
499+
C89STRINGUTILS_EXPORT int asprintf(char **str, const char *fmt, ...) {
500+
int rc;
501+
va_list args;
502+
va_start(args, fmt);
503+
rc = c89stringutils_vasprintf(str, fmt, args);
504+
va_end(args);
505+
return rc;
506+
}
507+
#endif
508+
509+
C89STRINGUTILS_EXPORT int jasprintf(char **unto, const char *fmt, ...) {
510+
int rc;
511+
va_list args;
512+
size_t base_length;
513+
int length;
514+
char *result;
515+
516+
if (unto == NULL || fmt == NULL) {
517+
return -1;
518+
}
519+
520+
base_length = *unto ? strlen(*unto) : 0;
521+
522+
va_start(args, fmt);
523+
length = vsnprintf(NULL, 0, fmt, args);
524+
va_end(args);
525+
526+
if (length < 0)
527+
return -1;
528+
529+
result = (char *)realloc(*unto, base_length + (size_t)length + 1);
530+
if (result == NULL) {
531+
return -1;
532+
}
533+
534+
va_start(args, fmt);
535+
rc = vsnprintf(result + base_length, (size_t)length + 1, fmt, args);
536+
va_end(args);
537+
538+
if (rc < 0) {
539+
free(result);
540+
*unto = NULL;
541+
return -1;
542+
}
543+
544+
*unto = result;
545+
return 0;
546+
}

c89stringutils/c89stringutils_string_extras.h

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,14 @@ extern C89STRINGUTILS_EXPORT int c89stringutils_asprintf(char **str,
206206
extern C89STRINGUTILS_EXPORT int c89stringutils_jasprintf(char **unto,
207207
const char *fmt, ...);
208208

209+
210+
#if !defined(HAVE_ASPRINTF)
211+
extern C89STRINGUTILS_EXPORT int vasprintf(char **str, const char *fmt, va_list ap);
212+
extern C89STRINGUTILS_EXPORT int asprintf(char **str, const char *fmt, ...);
213+
#endif
214+
215+
extern C89STRINGUTILS_EXPORT int jasprintf(char **unto, const char *fmt, ...);
216+
209217
#ifdef __cplusplus
210218
}
211219
#endif /* __cplusplus */

0 commit comments

Comments
 (0)