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