summaryrefslogtreecommitdiff
path: root/compat/snprintf.c
blob: fc91d63a9cf68bf868742dad824aedf8f717b9c0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60

#ifndef HAVE_VPRINTF
#include "choke-me: no vprintf and no snprintf"
#endif

#if defined(HAVE_STDARG_H)
#  include <stdarg.h>
#  ifndef   VA_START
#    define VA_START(a, f)  va_start(a, f)
#    define VA_END(a)       va_end(a)
#  endif /* VA_START */
#  define SNV_USING_STDARG_H

#elif defined(HAVE_VARARGS_H)
#  include <varargs.h>
#  ifndef   VA_START
#    define VA_START(a, f) va_start(a)
#    define VA_END(a)    va_end(a)
#  endif /* VA_START */
#  undef  SNV_USING_STDARG_H

#else
#  include "must-have-stdarg-or-varargs"
#endif

static int
snprintf(char *str, size_t n, char const *fmt, ...)
{
    va_list ap;
    int rval;

#ifdef VSPRINTF_CHARSTAR
    char *rp;
    VA_START(ap, fmt);
    rp = vsprintf(str, fmt, ap);
    VA_END(ap);
    rval = strlen(rp);

#else
    VA_START(ap, fmt);
    rval = vsprintf(str, fmt, ap);
    VA_END(ap);
#endif

    if (rval > n) {
        fprintf(stderr, "snprintf buffer overrun %d > %d\n", rval, (int)n);
        abort();
    }
    return rval;
}

static int
vsnprintf( char *str, size_t n, char const *fmt, va_list ap )
{
#ifdef VSPRINTF_CHARSTAR
    return (strlen(vsprintf(str, fmt, ap)));
#else
    return (vsprintf(str, fmt, ap));
#endif
}