1181834Sroberto
2181834Sroberto#ifndef HAVE_VPRINTF
3181834Sroberto#include "choke-me: no vprintf and no snprintf"
4290001Sglebius  choke me.
5181834Sroberto#endif
6181834Sroberto
7181834Sroberto#if defined(HAVE_STDARG_H)
8181834Sroberto#  include <stdarg.h>
9181834Sroberto#  ifndef   VA_START
10181834Sroberto#    define VA_START(a, f)  va_start(a, f)
11181834Sroberto#    define VA_END(a)       va_end(a)
12181834Sroberto#  endif /* VA_START */
13181834Sroberto#  define SNV_USING_STDARG_H
14181834Sroberto
15181834Sroberto#elif defined(HAVE_VARARGS_H)
16181834Sroberto#  include <varargs.h>
17181834Sroberto#  ifndef   VA_START
18181834Sroberto#    define VA_START(a, f) va_start(a)
19181834Sroberto#    define VA_END(a)    va_end(a)
20181834Sroberto#  endif /* VA_START */
21181834Sroberto#  undef  SNV_USING_STDARG_H
22181834Sroberto
23181834Sroberto#else
24181834Sroberto#  include "must-have-stdarg-or-varargs"
25290001Sglebius  choke me.
26181834Sroberto#endif
27181834Sroberto
28181834Srobertostatic int
29181834Srobertosnprintf(char *str, size_t n, char const *fmt, ...)
30181834Sroberto{
31181834Sroberto    va_list ap;
32181834Sroberto    int rval;
33181834Sroberto
34181834Sroberto#ifdef VSPRINTF_CHARSTAR
35181834Sroberto    char *rp;
36181834Sroberto    VA_START(ap, fmt);
37181834Sroberto    rp = vsprintf(str, fmt, ap);
38181834Sroberto    VA_END(ap);
39181834Sroberto    rval = strlen(rp);
40181834Sroberto
41181834Sroberto#else
42181834Sroberto    VA_START(ap, fmt);
43181834Sroberto    rval = vsprintf(str, fmt, ap);
44181834Sroberto    VA_END(ap);
45181834Sroberto#endif
46181834Sroberto
47181834Sroberto    if (rval > n) {
48181834Sroberto        fprintf(stderr, "snprintf buffer overrun %d > %d\n", rval, (int)n);
49181834Sroberto        abort();
50181834Sroberto    }
51181834Sroberto    return rval;
52181834Sroberto}
53181834Sroberto
54181834Srobertostatic int
55181834Srobertovsnprintf( char *str, size_t n, char const *fmt, va_list ap )
56181834Sroberto{
57181834Sroberto#ifdef VSPRINTF_CHARSTAR
58181834Sroberto    return (strlen(vsprintf(str, fmt, ap)));
59181834Sroberto#else
60181834Sroberto    return (vsprintf(str, fmt, ap));
61181834Sroberto#endif
62181834Sroberto}
63