PDFxTMDLib  1.0.0
NumParser.h
Go to the documentation of this file.
1 #pragma once
2 #include <cerrno>
3 #include <cstdlib>
4 #include <cstring>
5 #include <string_view>
6 #include <type_traits>
7 
8 namespace PDFxTMD
9 {
10 
11 class NumParser
12 {
13  public:
14  explicit NumParser(std::string_view input) noexcept
15  : _current(input.data()), _end(input.data() + input.size())
16  {
17  }
18 
19  void reset(std::string_view input) noexcept
20  {
21  _current = input.data();
22  _end = input.data() + input.size();
23  }
24 
25  template <typename T> bool operator>>(T &value) noexcept
26  {
27  skipSpaces();
28  return parseNumber(value);
29  }
30 
31  [[nodiscard]] bool hasMore() const noexcept
32  {
33  return _current < _end;
34  }
35 
36  private:
37  const char *_current;
38  const char *_end;
39 
40  void skipSpaces() noexcept
41  {
42  while (_current < _end && *_current == ' ')
43  ++_current;
44  }
45 
46  template <typename T> bool parseNumber(T &value) noexcept
47  {
48  char *next = nullptr;
49  errno = 0;
50 
51  if constexpr (std::is_integral_v<T>)
52  {
53  // parse as signed long long, then cast
54  long long tmp = std::strtoll(_current, &next, /*base=*/10);
55  if (_current == next || errno == ERANGE)
56  return false;
57  value = static_cast<T>(tmp);
58  }
59  else if constexpr (std::is_unsigned_v<T>)
60  {
61  unsigned long long tmp = std::strtoull(_current, &next, /*base=*/10);
62  if (_current == next || errno == ERANGE)
63  return false;
64  value = static_cast<T>(tmp);
65  }
66  else if constexpr (std::is_floating_point_v<T>)
67  {
68  long double tmp = std::strtold(_current, &next);
69  if (_current == next || errno == ERANGE)
70  return false;
71  value = static_cast<T>(tmp);
72  }
73  else
74  {
75  static_assert(!sizeof(T *), "parseNumber only supports integral or floating types");
76  }
77 
78  // advance past what we just consumed:
79  _current = next;
80  return true;
81  }
82 };
83 
84 } // namespace PDFxTMD
Definition: NumParser.h:12
bool operator>>(T &value) noexcept
Definition: NumParser.h:25
bool hasMore() const noexcept
Definition: NumParser.h:31
void reset(std::string_view input) noexcept
Definition: NumParser.h:19
NumParser(std::string_view input) noexcept
Definition: NumParser.h:14
Definition: AllFlavorsShape.h:14