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