-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParseInteger.h
97 lines (76 loc) · 1.62 KB
/
ParseInteger.h
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
// ParseInteger.h
// Implements a template function to parse any kind of integer from a string
#ifndef PARSEINTEGER_H
#define PARSEINTEGER_H
template <typename T>
bool parseInteger(const char * a_Str, T & a_Num, size_t a_MaxLength = std::numeric_limits<size_t>::max())
{
size_t i = 0;
bool isPositive = true;
T result = 0;
if (a_Str[0] == '+')
{
i++;
}
else if (a_Str[0] == '-')
{
i++;
isPositive = false;
}
if (isPositive)
{
for (; (i < a_MaxLength) && (a_Str[i] != 0); i++)
{
if ((a_Str[i] < '0') || (a_Str[i] > '9'))
{
// Not a digit
return false;
}
if (std::numeric_limits<T>::max() / 10 < result)
{
// Number too large to represent using the specified type
return false;
}
result *= 10;
T digit = static_cast<T>(a_Str[i] - '0');
if (std::numeric_limits<T>::max() - digit < result)
{
// Number too large to represent using the specified type
return false;
}
result += digit;
}
}
else
{
// Unsigned result cannot be signed!
if (!std::numeric_limits<T>::is_signed)
{
return false;
}
for (; a_Str[i] != 0; i++)
{
if ((a_Str[i] < '0') || (a_Str[i] > '9'))
{
// Not a digit
return false;
}
if (std::numeric_limits<T>::min() / 10 > result)
{
// Number too small to represent using the specified type
return false;
}
result *= 10;
T digit = static_cast<T>(a_Str[i] - '0');
if (std::numeric_limits<T>::min() + digit > result)
{
// Number too small to represent using the specified type
return false;
}
result -= digit;
}
}
a_Num = result;
return true;
}
#endif // PARSEINTEGER_H