]> git.lyx.org Git - lyx.git/blob - src/support/fmt.C
small cleanup, doxygen, formatting changes
[lyx.git] / src / support / fmt.C
1 #include <config.h>
2 #include <cstdio>
3 #include <cstdarg>
4
5 #ifndef HAVE_DECL_VSNPRINTF
6 #include "support/snprintf.h"
7 #endif
8
9 #include "LString.h"
10
11 /* This output manipulator gives the option to use Old style format
12    specifications in ostreams. Note that this is done at the expense
13    of typesafety, so if possible this manipulator should be avoided.
14    When is it allowed to use this manipulator? I wrote it to be used
15    i18n strings and gettext, and it should only(?) be used in that
16    context.
17
18    Ad. the implementation. I have only tested this on egcs-2.91.66 with
19    glibc 2.1.2. So further testing is needed. The loop in fmt(...) will
20    usually spin one or two times, but might spin more times with older
21    glibc libraries, since the returned -1 when size is too small. Newer
22    glibc returns the needed size.
23    One problem can be that vsnprintf is not implemented on all archs,
24    but AFAIK it is part of the new ANSI C standard.
25    
26    Lgb
27 */
28
29 string fmt(char const * fmtstr ...)
30 {
31         int size = 80;
32         char * str = new char[size];
33         va_list ap;
34         while (true) {
35                 va_start(ap, fmtstr);
36                 int const r = vsnprintf(str, size, fmtstr, ap);
37                 va_end(ap);
38                 if (r == -1) { // size is too small
39                         delete [] str;
40                         size *= 2; // seems quite safe to double.
41                         str = new char[size];
42                 } else if (r >= size) { // r gives the needed size
43                         delete [] str;
44                         size += r;
45                         str = new char[size];
46                 } else {
47                         break;
48                 }
49         }
50         string res(str);
51         delete [] str;
52         return res;
53 }