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