]> git.tdb.fi Git - libs/core.git/blob - source/strings/format.cpp
Make sure all classes have sensible copy semantics
[libs/core.git] / source / strings / format.cpp
1 #include "format.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 Formatter::Formatter(const Formatter &other):
15         fmt(other.fmt),
16         pos(fmt.begin()+(other.pos-other.fmt.begin())),
17         result(other.result)
18 { }
19
20 Formatter &Formatter::operator=(const Formatter &other)
21 {
22         fmt = other.fmt;
23         pos = fmt.begin()+(other.pos-other.fmt.begin());
24         result = other.result;
25         return *this;
26 }
27
28 const string &Formatter::str() const
29 {
30         if(pos!=fmt.end())
31                 throw format_error("Too few arguments for format");
32
33         return result;
34 }
35
36 void Formatter::advance()
37 {
38         for(; pos!=fmt.end(); ++pos)
39         {
40                 if(*pos=='%')
41                 {
42                         ++pos;
43                         if(pos==fmt.end())
44                                 throw format_error("Malformed format string");
45                         if(*pos!='%')
46                                 break;
47                 }
48
49                 result += *pos;
50         }
51 }
52
53 Fmt Formatter::get_conversion()
54 {
55         if(pos==fmt.end())
56                 throw format_error("Too many arguments for format");
57
58         string::iterator i = pos;
59         for(; i!=fmt.end(); ++i)
60                 if(isalpha(*i))
61                         break;
62
63         if(i==fmt.end())
64                 throw format_error("Malformed format string");
65
66         ++i;
67         string c(pos, i);
68         pos = i;
69
70         return Fmt(c);
71 }
72
73 } // namespace Msp