OSSIA
Open Scenario System for Interactive Application
parse_relax.hpp
1 #pragma once
2 #include <ossia/detail/config.hpp>
3 
4 #include <optional>
5 #include <string_view>
6 #include <version>
7 
8 #if defined(__cpp_lib_to_chars)
9 #include <charconv>
10 #else
11 #include <boost/spirit/home/x3.hpp>
12 #endif
13 
14 namespace ossia
15 {
16 // parse_relax:
17 // "123" => 123
18 // "123x" => 123
19 // " 123" => std::nullopt
20 // "123 " => 123
21 
22 #if defined(__cpp_lib_to_chars)
23 template <typename T>
24 static std::optional<T> parse_relax(std::string_view v)
25 {
26  T n{};
27 
28  const auto begin = v.data();
29  const auto end = v.data() + v.size();
30  const auto [ptr, ec] = std::from_chars(begin, end, n);
31  return (ec == std::errc{}) ? std::optional<T>{n} : std::nullopt;
32 }
33 #else
34 template <typename T>
35 static std::optional<T> parse_relax(std::string_view v);
36 
37 template <>
38 std::optional<int> parse_relax<int>(std::string_view v)
39 {
40  using boost::spirit::x3::int_;
41  int32_t x{};
42  int err = boost::spirit::x3::parse(v.begin(), v.end(), int_, x);
43  if(err == 0)
44  return std::nullopt;
45  return x;
46 }
47 template <>
48 std::optional<float> parse_relax<float>(std::string_view v)
49 {
50  using boost::spirit::x3::float_;
51  float x{};
52  int err = boost::spirit::x3::parse(v.begin(), v.end(), float_, x);
53  if(err == 0)
54  return std::nullopt;
55  return x;
56 }
57 template <>
58 std::optional<double> parse_relax<double>(std::string_view v)
59 {
60  using boost::spirit::x3::double_;
61  double x{};
62  int err = boost::spirit::x3::parse(v.begin(), v.end(), double_, x);
63  if(err == 0)
64  return std::nullopt;
65  return x;
66 }
67 #endif
68 
69 }
Definition: git_info.h:7