#include <cstdio>
#include <cstdlib>
#include <cerrno>
#include <climits>
#include "Int.hpp"
using namespace Lib;
std::string Int::toString (int i)
{
constexpr auto BUFSIZE = 20;
char tmp [BUFSIZE];
snprintf(tmp,BUFSIZE,"%d",i);
std::string result(tmp);
return result;
}
std::string Int::toString(double d)
{
constexpr auto BUFSIZE = 256;
char tmp [BUFSIZE];
snprintf(tmp,BUFSIZE,"%g",d);
std::string result(tmp);
return result;
}
std::string Int::toString(long l)
{
constexpr auto BUFSIZE = 256;
char tmp [BUFSIZE];
snprintf(tmp,BUFSIZE,"%ld",l);
std::string result(tmp);
return result;
}
std::string Int::toString(unsigned i)
{
constexpr auto BUFSIZE = 256;
char tmp [BUFSIZE];
snprintf(tmp,BUFSIZE,"%u",i);
std::string result(tmp);
return result;
}
std::string Int::toString(unsigned long i)
{
constexpr auto BUFSIZE = 256;
char tmp [BUFSIZE];
snprintf(tmp,BUFSIZE,"%lu",i);
std::string result(tmp);
return result;
}
bool Int::stringToLong (const char* str,long& result)
{
if (! *str) { return false;
}
errno = 0;
char* endptr = 0;
result = strtol(str,&endptr,10);
if (*endptr ||
(result == 0 && errno) ||
( (result == LONG_MAX || result == LONG_MIN) && errno==ERANGE ) ) { return false;
}
return true;
}
bool Int::stringToInt (const std::string& str,int& result)
{
return stringToInt(str.c_str(),result);
}
bool Int::stringToUnsignedInt (const std::string& str,unsigned& result)
{
return stringToUnsignedInt(str.c_str(),result);
}
bool Int::stringToUnsignedInt (const char* str,unsigned& result)
{
if (! *str) { return false;
}
errno = 0; char* endptr = 0; result = strtoul(str,&endptr,10);
return (errno == 0 && !*endptr);
}
bool Int::stringToInt (const char* str,int& result)
{
long ln;
bool converted = stringToLong(str,ln);
if (! converted || ln > INT_MAX || ln < INT_MIN) {
return false;
}
result = (int)ln;
return true;
}
bool Int::stringToDouble (const char* str,double& result)
{
errno = 0;
char* endptr = 0;
result = strtod(str,&endptr);
if (*endptr ||
(result == 0.0 && errno)) { return false;
}
return true;
}
bool Int::stringToFloat (const char* str,float& result)
{
double d;
bool converted = stringToDouble(str,d);
if (! converted) {
return false;
}
result = (float)d;
return true;
}
bool Int::stringToUnsigned64 (const char* str,long long unsigned& result)
{
result = 0;
if (! *str) { return false;
}
while (*str == '0') {
str++;
}
while (*str) {
char nextChar = *str;
str++;
if (nextChar < '0' || nextChar > '9') {
return false;
}
result = 10*result + (nextChar - '0');
}
return true;
}
bool Int::stringToUnsigned64 (const std::string& str,long long unsigned& result)
{
return stringToUnsigned64(str.c_str(),result);
}