-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFormatString.cpp
More file actions
117 lines (105 loc) · 2.24 KB
/
FormatString.cpp
File metadata and controls
117 lines (105 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#include "FormatString.h"
using namespace QLang;
using namespace std;
ParsedFormatString ParsedFormatString::parse( const std::string &fmt )
{
ParsedFormatString result;
string current;
int argIndex = 0;
size_t i = 0;
while ( i < fmt.size() )
{
char c = fmt[i];
// Escape sequences: {{ -> {, }} -> }
if ( c == '{' && i + 1 < fmt.size() && fmt[i + 1] == '{' )
{
current += '{';
i += 2;
continue;
}
if ( c == '}' && i + 1 < fmt.size() && fmt[i + 1] == '}' )
{
current += '}';
i += 2;
continue;
}
if ( c == '{' )
{
// Start of placeholder
result.literals.push_back( current );
current.clear();
FormatPlaceholder ph;
ph.argIndex = argIndex++;
i++; // skip '{'
// Check for specifier after ':'
if ( i < fmt.size() && fmt[i] == ':' )
{
i++; // skip ':'
string spec;
while ( i < fmt.size() && fmt[i] != '}' )
{
spec += fmt[i];
i++;
}
if ( spec.empty() )
{
result.error = "empty format specifier after ':'";
return result;
}
ph.specifier = spec;
// Parse the specifier
char last = spec.back();
if ( last == 'x' || last == 'X' || last == 'o' || last == 'b' )
{
ph.type = last;
}
else if ( last == 'f' )
{
ph.type = 'f';
if ( spec.size() >= 2 && spec[0] == '.' )
{
string digits = spec.substr( 1, spec.size() - 2 );
ph.precision = 0;
for ( char d : digits )
{
if ( d < '0' || d > '9' )
{
result.error = "invalid precision in format specifier: '" + spec + "'";
return result;
}
ph.precision = ph.precision * 10 + ( d - '0' );
}
}
}
else if ( last == 'e' )
{
ph.type = 'e';
}
else
{
result.error = "unknown format specifier: '" + spec + "'";
return result;
}
}
if ( i >= fmt.size() || fmt[i] != '}' )
{
result.error = "unterminated format placeholder, expected '}'";
return result;
}
i++; // skip '}'
result.placeholders.push_back( ph );
}
else if ( c == '}' )
{
result.error = "unexpected '}' in format string (use '}}' for literal '}')";
return result;
}
else
{
current += c;
i++;
}
}
result.literals.push_back( current );
return result;
}