Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- template <typename T> int SignBit(T val) {
- return (T(0) < val) - (val < T(0));
- }
- template <typename T>
- bool ParseInt(const AuString& in, T& out)
- {
- T res = 0;
- T sign = 1;
- out = 0;
- auto itr = in.begin();
- if constexpr (std::is_same<T, AuSInt>::value)
- {
- if (itr != in.end())
- {
- if (*itr == '-')
- {
- itr++;
- sign = -1;
- }
- }
- }
- for (;
- (itr != in.end()) &&
- (*itr != '\0');
- itr++)
- {
- auto c = *itr;
- if ((c < '0') || (c > '9')) return false;
- auto old = res;
- res *= 10;
- res += static_cast<AuUInt>(*itr) - static_cast<AuUInt>('0');
- if constexpr (std::is_same<T, AuUInt>::value)
- {
- if (old > res)
- {
- LogDbg("Unsigned integer overflow");
- return false;
- }
- }
- else if constexpr (std::is_same<T, AuSInt>::value)
- {
- if (SignBit(old) != SignBit(res))
- {
- LogDbg("Signed integer overflow");
- return false;
- }
- }
- }
- out = res * sign;
- return true;
- }
- template <typename T>
- bool ParseUInt(const AuString& in, T& out)
- {
- auto temp = AuUInt{};
- out = 0;
- if (!ParseInt<AuUInt>(in, temp)) return false;
- if (temp > std::numeric_limits<T>::max()) return false;
- out = temp;
- return true;
- }
- template <typename T>
- bool ParseSInt(const AuString& in, T& out)
- {
- auto temp = AuSInt{};
- out = 0;
- if (!ParseInt<AuSInt>(in, temp)) return false;
- if (temp > std::numeric_limits<T>::max()) return false;
- if (temp < std::numeric_limits<T>::min()) return false;
- out = temp;
- return true;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement