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