Euphoria
numparse.cc
Go to the documentation of this file.
1 #include "base/numparse.h"
2 
3 #include <cstdlib>
4 #include <limits>
5 
6 namespace eu
7 {
8 
9 
10 std::optional<int> locale_parse_int(const std::string& str)
11 {
12  char* end = nullptr;
13  const auto r = std::strtol(str.c_str(), &end, 10);
14  if(end == str.c_str()) { return std::nullopt; }
15 
16  // validate to int range
17  if(r < static_cast<long>(std::numeric_limits<int>::min())) { return std::nullopt; }
18  if(r > static_cast<long>(std::numeric_limits<int>::max())) { return std::nullopt; }
19 
20  return static_cast<int>(r);
21 }
22 
23 
24 
25 std::optional<float> locale_parse_float(const std::string& str)
26 {
27  char* end = nullptr;
28  const auto r = std::strtof(str.c_str(), &end);
29  if(end == str.c_str()) { return std::nullopt; }
30  return r;
31 }
32 
33 
34 
35 std::optional<bool> locale_parse_bool(const std::string& str)
36 {
37  if(str == "true") { return true; }
38  if(str == "yes") { return true; }
39 
40  if(str == "false") { return false; }
41  if(str == "no") { return false; }
42 
43  return std::nullopt;
44 }
45 
46 
47 #define SPECIALIZE(TYPE, FUN) \
48  template<> std::optional<TYPE> \
49  locale_parse_generic<TYPE>(const std::string& str) { return FUN(str); }
50 
54  SPECIALIZE(std::string, [](const std::string& s) { return s; })
55 #undef SPECIALIZE
56 
57 
58 }
59 
Definition: assert.h:90
std::optional< bool > locale_parse_bool(const std::string &str)
Definition: numparse.cc:35
std::optional< float > locale_parse_float(const std::string &str)
Definition: numparse.cc:25
size2f min(const size2f lhs, const size2f rhs)
Definition: size2.cc:140
size2f max(const size2f lhs, const size2f rhs)
Definition: size2.cc:149
std::optional< int > locale_parse_int(const std::string &str)
Definition: numparse.cc:10
#define SPECIALIZE(TYPE, FUN)
Definition: numparse.cc:47