src
s_to_n32_unsafe.cc
Go to the documentation of this file.
1 #include <limits>
2 
4 
5 // assumes that string matches regexp [0-9]+
6 // returns false on overflow
7 bool s_to_u32_unsafe (const char * s, const char * s_end, uint32_t & number)
8 {
9  uint64_t u = 0;
10  for (; s != s_end; ++s)
11  {
12  u *= 10;
13  u += static_cast<uint32_t> (*s) - 0x30;
14  if (u >= std::numeric_limits<uint32_t>::max())
15  {
16  return false;
17  }
18  }
19  number = static_cast<uint32_t> (u);
20  return true;
21 }
22 
23 // assumes that string matches regexp "-"? [0-9]+
24 // returns false on underflow/overflow
25 bool s_to_i32_unsafe (const char * s, const char * s_end, int32_t & number)
26 {
27  int64_t i = 0;
28  if (*s == '-')
29  {
30  ++s;
31  for (; s != s_end; ++s)
32  {
33  i *= 10;
34  i -= *s - 0x30;
35  if (i < std::numeric_limits<int32_t>::min())
36  {
37  return false;
38  }
39  }
40  }
41  else
42  {
43  for (; s != s_end; ++s)
44  {
45  i *= 10;
46  i += *s - 0x30;
47  if (i > std::numeric_limits<int32_t>::max())
48  {
49  return false;
50  }
51  }
52  }
53  number = static_cast<int32_t> (i);
54  return true;
55 }
bool s_to_u32_unsafe(const char *s, const char *s_end, uint32_t &number)
bool s_to_i32_unsafe(const char *s, const char *s_end, int32_t &number)