Project

General

Profile

Bug #13829 ยป test.cc

Kefu Chai, 11/19/2015 07:58 AM

 
#include <iostream>
#include <limits>
#include <map>
#include <string>

using namespace std;

template<typename T>
T strict_si_cast(const char *str, std::string *err)
{
std::string s(str);
if (s.empty()) {
*err = "strict_sistrtoll: value not specified";
return 0;
}
const char &u = s.at(s.size()-1); //str[std::strlen(str)-1];
int m = 0;
if (u == 'B')
m = 0;
else if (u == 'K')
m = 10;
else if (u == 'M')
m = 20;
else if (u == 'G')
m = 30;
else if (u == 'T')
m = 40;
else if (u == 'P')
m = 50;
else if (u == 'E')
m = 60;
else
m = -1;

const char *v = NULL;
if (m >= 0)
s = std::string(str, s.size()-1);

if (m < 0) {
m = 0;
}
long long ll = std::stoll(s);
if (ll < 0 && !numeric_limits<T>::is_signed) {
*err = "strict_sistrtoll: value should not be negative";
return 0;
}
if (ll < (long long)numeric_limits<T>::min() >> m) {
*err = "strict_sistrtoll: value seems to be too small";
return 0;
}
cout << "max" << numeric_limits<T>::max() << endl;
cout << "max" << (numeric_limits<T>::max() >> m) << endl;
if (ll > numeric_limits<T>::max() >> m) {
*err = "strict_sistrtoll: value seems to be too large";
return 0;
}
return (ll << m);
}

uint64_t strict_sistrtoll(const char *str, std::string *err)
{
return strict_si_cast<uint64_t>(str, err);
}

int main()
{
std::string err;
const char* val = "-4";
int f = strict_si_cast<int>(val, &err);
cout << "err: " << err << endl;
cout << f << endl;


err.clear();
uint64_t u = strict_sistrtoll(val, &err);
cout << "err: " << err << endl;
cout << u << endl;
}
    (1-1/1)