Project

General

Profile

test.cc

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

Download (1.62 KB)

 
1
#include <iostream>
2
#include <limits>
3
#include <map>
4
#include <string>
5

    
6
using namespace std;
7

    
8
template<typename T>
9
T strict_si_cast(const char *str, std::string *err)
10
{
11
  std::string s(str);
12
  if (s.empty()) {
13
    *err = "strict_sistrtoll: value not specified";
14
    return 0;
15
      
16
  }
17
  const char &u = s.at(s.size()-1); //str[std::strlen(str)-1];
18
  int m = 0;
19
  if (u == 'B')
20
    m = 0;
21
  else if (u == 'K')
22
    m = 10;
23
  else if (u == 'M')
24
    m = 20;
25
  else if (u == 'G')
26
    m = 30;
27
  else if (u == 'T')
28
    m = 40;
29
  else if (u == 'P')
30
    m = 50;
31
  else if (u == 'E')
32
    m = 60;
33
  else
34
    m = -1;
35

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

    
40
  if (m < 0) {
41
    m = 0;
42
  }
43
  long long ll = std::stoll(s);
44
  if (ll < 0 && !numeric_limits<T>::is_signed) {
45
    *err = "strict_sistrtoll: value should not be negative";
46
    return 0;
47
  }
48
  if (ll < (long long)numeric_limits<T>::min() >> m) {
49
    *err = "strict_sistrtoll: value seems to be too small";
50
    return 0;
51
  }
52
  cout << "max" << numeric_limits<T>::max() << endl;
53
  cout << "max" << (numeric_limits<T>::max() >> m) << endl;
54
  if (ll > numeric_limits<T>::max() >> m) {
55
    *err = "strict_sistrtoll: value seems to be too large";
56
    return 0;
57
      
58
  }
59
  return (ll << m);  
60
}
61

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

    
67
int main()
68
{
69
  std::string err;
70
  const char* val = "-4";
71
  int f = strict_si_cast<int>(val, &err);
72
  cout << "err: " << err << endl;
73
  cout << f << endl;
74

    
75

    
76
  err.clear();
77
  uint64_t u = strict_sistrtoll(val, &err);
78
  cout << "err: " << err << endl;
79
  cout << u << endl;
80
}