Skip to content

Commit d526f8a

Browse files
committed
1 parent 7b90db0 commit d526f8a

1 file changed

Lines changed: 47 additions & 23 deletions

File tree

simplecpp.cpp

Lines changed: 47 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,11 @@ static bool isOct(const std::string &s)
6868
return s.size()>1 && (s[0]=='0') && (s[1] >= '0') && (s[1] < '8');
6969
}
7070

71+
static bool isBin(const std::string &s)
72+
{
73+
return s.size()>2 && s.compare(0,2,"0b")==0;
74+
}
75+
7176
// TODO: added an undercore since this conflicts with a function of the same name in utils.h from Cppcheck source when building Cppcheck with MSBuild
7277
static bool isStringLiteral_(const std::string &s)
7378
{
@@ -120,32 +125,51 @@ static std::string locstring(const simplecpp::Location &loc)
120125
}
121126
#endif
122127

123-
static long long stringToLL(const std::string &s)
124-
{
125-
long long ret;
126-
const bool hex = isHex(s);
127-
const bool oct = isOct(s);
128-
std::istringstream istr(hex ? s.substr(2) : oct ? s.substr(1) : s);
129-
if (hex)
130-
istr >> std::hex;
131-
else if (oct)
132-
istr >> std::oct;
133-
istr >> ret;
134-
return ret;
128+
static unsigned long long stringToULL(const std::string &s, std::size_t offset = 0)
129+
{
130+
unsigned long long base = 10;
131+
if (isHex(s.substr(offset))) {
132+
offset += 2;
133+
base = 16;
134+
} else if (isOct(s.substr(offset))) {
135+
offset += 1;
136+
base = 8;
137+
} else if (isBin(s.substr(offset))) {
138+
offset += 2;
139+
base = 2;
140+
}
141+
142+
unsigned long long result = 0;
143+
for (std::size_t i = offset; i < s.size(); i++) {
144+
const char c = s[i];
145+
result *= base;
146+
147+
unsigned long long d;
148+
if ('0' <= c && c <= '9') {
149+
d = c - '0';
150+
} else if ('a' <= c && c <= 'f') {
151+
d = 10 + c - 'a';
152+
} else if ('A' <= c && c <= 'F') {
153+
d = 10 + c - 'A';
154+
} else {
155+
throw std::runtime_error("invalid integer literal");
156+
}
157+
158+
if (d >= base) {
159+
throw std::runtime_error("invalid integer literal");
160+
}
161+
162+
result += d;
163+
}
164+
165+
return result;
135166
}
136167

137-
static unsigned long long stringToULL(const std::string &s)
168+
static long long stringToLL(const std::string &s)
138169
{
139-
unsigned long long ret;
140-
const bool hex = isHex(s);
141-
const bool oct = isOct(s);
142-
std::istringstream istr(hex ? s.substr(2) : oct ? s.substr(1) : s);
143-
if (hex)
144-
istr >> std::hex;
145-
else if (oct)
146-
istr >> std::oct;
147-
istr >> ret;
148-
return ret;
170+
if (s.size() > 0 && s[0] == '-')
171+
return -stringToULL(s, 1);
172+
return stringToULL(s);
149173
}
150174

151175
static bool endsWith(const std::string &s, const std::string &e)

0 commit comments

Comments
 (0)