]> git.tdb.fi Git - libs/core.git/blob - source/fmt.h
2317ae4b848a4c451eeebc62cbc9f61ee810f4e5
[libs/core.git] / source / fmt.h
1 #ifndef MSP_STRINGS_FMT_H_
2 #define MSP_STRINGS_FMT_H_
3
4 #include <ostream>
5 #include <string>
6
7 namespace Msp {
8
9 /**
10 Stores formatting information for converting variables into strings.  Can be
11 applied to an std::ostream or fed to lexical_cast.  Also used internally by
12 Formatter.
13
14 Formats can be constructed from printf-style conversion specifications, by
15 chaining calls to the various setter functions, or with a mixture of both.
16
17 Since type information for conversions is acquired through templates, the
18 meaning of the conversion specifier character is reduced to only specifying
19 what the conversion should look like.  In particular, the d, i, u, c and s
20 conversions are no-ops.
21 */
22 class Fmt
23 {
24 public:
25         Fmt()                        { reset(); }
26         Fmt(const char *f)           { reset(); parse(f); }
27         Fmt(const std::string &f)    { reset(); parse(f.c_str()); }
28         Fmt  &width(unsigned w)      { wd=w; return *this; }
29         Fmt  &precision(unsigned p)  { prec=p; return *this; }
30         Fmt  &showpos(bool s=true)   { spos=s; return *this; }
31         Fmt  &fill(wchar_t f)        { fillc=f; return *this; }
32         Fmt  &fixed()                { fmode=FIXED; return *this; }
33         Fmt  &scientific()           { fmode=SCI; return *this; }
34         Fmt  &showpoint(bool s=true) { spoint=s; return *this; }
35         Fmt  &showbase(bool s=true)  { sbase=s; return *this; }
36         Fmt  &left()                 { align=LEFT; return *this; }
37         Fmt  &right()                { align=RIGHT; return *this; }
38         Fmt  &dec()                  { base=DEC; return *this; }
39         Fmt  &hex()                  { base=HEX; return *this; }
40         Fmt  &oct()                  { base=OCT; return *this; }
41         Fmt  &uppercase(bool u=true) { ucase=u; return *this; }
42         Fmt  &reset();
43         void apply(std::ostream &) const;
44 private:
45         enum Base
46         {
47                 DEC,
48                 HEX,
49                 OCT
50         };
51
52         enum FloatMode
53         {
54                 FIXED,
55                 EXP,
56                 SCI
57         };
58
59         enum Align
60         {
61                 LEFT,
62                 RIGHT
63         };
64
65         unsigned  wd;
66         unsigned  prec;
67         bool      spos;
68         wchar_t   fillc;
69         Base      base;
70         bool      sbase;
71         FloatMode fmode;
72         bool      spoint;
73         Align     align;
74         bool      ucase;
75
76         void parse(const char *);
77 };
78
79 inline std::ostream &operator<<(std::ostream &o, const Fmt &f)
80 { f.apply(o); return o; }
81
82 } // namespace Msp
83
84 #endif