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