- port to Cygwin (DLL support, etc.)
[citadel.git] / citadel / snprintf.c
1 /*
2  * $Id$
3  *
4  * Replacements for snprintf() and vsnprintf()
5  *
6  * modified from Sten Gunterberg's BUGTRAQ post of 22 Jul 1997
7  * --nathan bryant <nathan@designtrust.com>
8  *
9  * Use it only if you have the "spare" cycles needed to effectively
10  * do every snprintf operation twice! Why is that? Because everything
11  * is first vfprintf()'d to /dev/null to determine the number of bytes.
12  * Perhaps a bit slow for demanding applications on slow machines,
13  * no problem for a fast machine with some spare cycles.
14  *
15  * You don't have a /dev/null? Every Linux contains one for free!
16  *
17  * Because the format string is never even looked at, all current and
18  * possible future printf-conversions should be handled just fine.
19  *
20  * Written July 1997 by Sten Gunterberg (gunterberg@ergon.ch)
21  */
22
23 #ifdef DLL_EXPORT
24 #define IN_LIBCIT
25 #endif
26
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <stdarg.h>
30 #include <string.h>
31
32 static int
33 needed (const char *fmt, va_list argp)
34 {
35   static FILE *sink = NULL;
36
37   /* ok, there's a small race here that could result in the sink being
38    * opened more than once if we're threaded, but I'd rather ignore it than
39    * spend cycles synchronizing :-) */
40
41   if (sink == NULL)
42     {
43       if ((sink = fopen("/dev/null", "w")) == NULL)
44         {
45           perror("/dev/null");
46           exit(1);
47         }
48     }
49
50   return vfprintf(sink, fmt, argp);
51 }
52
53 int
54 vsnprintf (char *buf, size_t max, const char *fmt, va_list argp)
55 {
56   char *p;
57   int size;
58
59   if ((p = malloc(needed(fmt, argp) + 1)) == NULL)
60     {
61       fprintf(stderr, "vsnprintf: malloc failed, aborting\n");
62       abort();
63     }
64
65   if ((size = vsprintf(p, fmt, argp)) >= max)
66     size = -1;
67
68   strncpy(buf, p, max);
69   buf[max - 1] = 0;
70   free(p);
71   return size;
72 }
73
74 int
75 snprintf (char *buf, size_t max, const char *fmt, ...)
76 {
77   va_list argp;
78   int bytes;
79
80   va_start(argp, fmt);
81   bytes = vsnprintf(buf, max, fmt, argp);
82   va_end(argp);
83
84   return bytes;
85 }