]> mj.ucw.cz Git - eval.git/blob - lib/ff-printf.c
Polished configuration scripts.
[eval.git] / lib / ff-printf.c
1 /*
2  *      UCW Library -- Printf on Fastbuf Streams
3  *
4  *      (c) 2002--2005 Martin Mares <mj@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #include "lib/lib.h"
11 #include "lib/fastbuf.h"
12
13 #include <stdio.h>
14 #include <alloca.h>
15
16 int
17 vbprintf(struct fastbuf *b, const char *msg, va_list args)
18 {
19   byte *buf;
20   int len, r;
21   va_list args2;
22
23   len = bdirect_write_prepare(b, &buf);
24   if (len >= 16)
25     {
26       va_copy(args2, args);
27       r = vsnprintf(buf, len, msg, args2);
28       va_end(args2);
29       if (r < 0)
30         len = 256;
31       else if (r < len)
32         {
33           bdirect_write_commit(b, buf+r);
34           return r;
35         }
36       else
37         len = r+1;
38     }
39   else
40     len = 256;
41
42   while (1)
43     {
44       buf = alloca(len);
45       va_copy(args2, args);
46       r = vsnprintf(buf, len, msg, args2);
47       va_end(args2);
48       if (r < 0)
49         len += len;
50       else if (r < len)
51         {
52           bwrite(b, buf, r);
53           return r;
54         }
55       else
56         len = r+1;
57     }
58 }
59
60 int
61 bprintf(struct fastbuf *b, const char *msg, ...)
62 {
63   va_list args;
64   int res;
65
66   va_start(args, msg);
67   res = vbprintf(b, msg, args);
68   va_end(args);
69   return res;
70 }
71
72 #ifdef TEST
73
74 int main(void)
75 {
76   struct fastbuf *b = bfdopen_shared(1, 65536);
77   for (int i=0; i<10000; i++)
78     bprintf(b, "13=%d str=<%s> msg=%m\n", 13, "str");
79   bclose(b);
80   return 0;
81 }
82
83 #endif