]> git.tdb.fi Git - libs/core.git/blob - source/formatter.cpp
8db3f4d56ebdc5b0e9af459f9a19006290e90043
[libs/core.git] / source / formatter.cpp
1 #include "formatter.h"
2
3 using namespace std;
4
5 namespace Msp {
6
7 Formatter::Formatter(const string &f):
8         fmt(f),
9         pos(fmt.begin())
10 {
11         advance();
12 }
13
14 /**
15 Returns the result of the formatting operation.  Will throw if not enough
16 values have been fed to the formatter.
17 */
18 const string &Formatter::str() const
19 {
20         if(pos!=fmt.end())
21                 throw Exception("Too few arguments for format");
22
23         return result;
24 }
25
26 /**
27 Advances the pos iterator to the next conversion, adding literal characters to
28 the result.  The iterator is left at the second character of the conversion
29 (i.e. after the %).
30 */
31 void Formatter::advance()
32 {
33         for(; pos!=fmt.end(); ++pos)
34         {
35                 if(*pos=='%')
36                 {
37                         ++pos;
38                         if(pos==fmt.end())
39                                 throw Exception("Malformed format string");
40                         if(*pos!='%')
41                                 break;
42                 }
43
44                 result+=*pos;
45         }
46 }
47
48 /**
49 Reads the next conversion from the format string and returns a corresponding
50 Fmt object.
51 */
52 Fmt Formatter::get_conversion()
53 {
54         if(pos==fmt.end())
55                 throw Exception("Too many arguments for format");
56
57         string::iterator i=pos;
58         for(; i!=fmt.end(); ++i)
59                 if(isalpha(*i))
60                         break;
61
62         if(i==fmt.end())
63                 throw Exception("Malformed format string");
64
65         ++i;
66         string c(pos, i);
67         pos=i;
68
69         return Fmt(c);
70 }
71
72 } // namespace Msp