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