pixwhile/numberhelper.cpp

32 lines
868 B
C++
Raw Permalink Normal View History

#include <climits>
#include <stdexcept>
#include "numberhelper.h"
unsigned long long to_ull(const std::string& str) {
char* endptr;
errno = 0;
unsigned long long ret = strtoull(str.c_str(), &endptr, 10);
if (ret > ULLONG_MAX && errno == ERANGE) {
throw std::overflow_error(str + " is too big");
} else if (endptr[0] != '\0') {
throw std::invalid_argument(str + " has trailing text");
}
return ret;
}
int to_int(const std::string& str) {
char* endptr;
long ret = strtol(str.c_str(), &endptr, 10);
if (ret > INT_MAX) {
throw std::overflow_error(str + " is too big");
} else if (ret < INT_MIN) {
throw std::underflow_error(str + " is too small");
} else if (endptr[0] != '\0') {
throw std::invalid_argument(str + " has trailing text");
}
return static_cast<int>(ret);
}