-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlineparser.cpp
128 lines (116 loc) · 1.68 KB
/
lineparser.cpp
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
118
119
120
121
122
123
124
125
126
127
128
#include <string>
#include <cassert>
#include <climits>
#include "lineparser.h"
LineParser::LineParser(const std::string& ln)
: line(ln), pos(0)
{
}
bool LineParser::GetNum(uint32_t& value, int base)
{
bool negative = false;
std::string w = GetWord();
if (w[0] == '-')
{
negative = true;
w = w.substr(1);
}
uint64_t tmp;
try
{
tmp = std::stoul(w, 0, base);
}
catch(...)
{
return false;
}
if (tmp > UINT_MAX)
{
return false;
}
if (negative)
{
if(tmp > (uint64_t)INT_MAX+1)
{
return false;
}
tmp = -tmp;
}
value = tmp;
return true;
}
std::string LineParser::GetWord()
{
std::string w;
while(!IsSeparator(line[pos]))
{
w += line[pos];
pos++;
}
SkipSpaces();
return w;
}
char LineParser::Get()
{
if (pos < line.length())
{
char res = line[pos];
pos++;
return res;
}
return EOF;
}
char LineParser::Peek()
{
if (pos < line.length())
{
return line[pos];
}
return EOF;
}
bool LineParser::Done()
{
return pos >= line.length();
}
bool LineParser::Accept(char c)
{
assert(pos <= line.length());
if (line[pos] == c)
{
pos++;
return true;
}
return false;
}
void LineParser::Expect(char c)
{
assert(pos <= line.length());
if (line[pos] == c)
{
pos++;
}
else
{
Error(std::string("Unexpected character, expected ") + c);
}
}
void LineParser::SkipSpaces()
{
while(isspace(Peek()))
{
Get();
}
}
void LineParser::Save()
{
save_pos = pos;
}
void LineParser::Restore()
{
pos = save_pos;
}
void LineParser::Error(const std::string& msg)
{
ErrOutput(msg);
pos = line.length();
}