* Cleaned up the rcs/cvs Id tags and leading comments at the top of some files
[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 <stdio.h>
27 #include <stdlib.h>
28 #include <stdarg.h>
29 #include <string.h>
30 #include "webserver.h"
31
32 static int needed(const char *fmt, va_list argp)
33 {
34         static FILE *sink = NULL;
35
36         /* ok, there's a small race here that could result in the sink being
37          * opened more than once if we're threaded, but I'd rather ignore it than
38          * spend cycles synchronizing :-) */
39
40         if (sink == NULL) {
41                 if ((sink = fopen("/dev/null", "w")) == NULL) {
42                         perror("/dev/null");
43                         exit(1);
44                 }
45         }
46         return vfprintf(sink, fmt, argp);
47 }
48
49 int vsnprintf(char *buf, size_t max, const char *fmt, va_list argp)
50 {
51         char *p;
52         int size;
53
54         if ((p = malloc(needed(fmt, argp) + 1)) == NULL) {
55                 lprintf(1, "vsnprintf: malloc failed, aborting\n");
56                 abort();
57         }
58         if ((size = vsprintf(p, fmt, argp)) >= max)
59                 size = -1;
60
61         strncpy(buf, p, max);
62         buf[max - 1] = 0;
63         free(p);
64         return size;
65 }
66
67 int snprintf(char *buf, size_t max, const char *fmt,...)
68 {
69         va_list argp;
70         int bytes;
71
72         va_start(argp, fmt);
73         bytes = vsnprintf(buf, max, fmt, argp);
74         va_end(argp);
75
76         return bytes;
77 }