File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed
src/tools/fdsdump/src/common Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change 1515#include < memory>
1616#include < string>
1717#include < vector>
18+ #include < cassert>
19+ #include < limits>
20+ #include < type_traits>
1821
1922#include < libfds.h>
2023
@@ -97,4 +100,48 @@ string_to_lower(std::string str);
97100void
98101memcpy_bits (uint8_t *dst, uint8_t *src, unsigned int n_bits);
99102
103+ template <typename T,
104+ typename std::enable_if<std::is_integral<T>::value && std::is_signed<T>::value, bool >::type = true
105+ >
106+ Optional<T>
107+ parse_number (const std::string &s)
108+ {
109+ static_assert (std::numeric_limits<T>::min () >= std::numeric_limits<long >::min ()
110+ && std::numeric_limits<T>::max () <= std::numeric_limits<long >::max (),
111+ " supplied type has range broader than long thus cannot be used with strtol" );
112+
113+ char *end;
114+ errno = 0 ;
115+ long value = std::strtol (s.c_str (), &end, 10 );
116+ if (errno != 0
117+ || *end != ' \0 '
118+ || value < std::numeric_limits<T>::min ()
119+ || value > std::numeric_limits<T>::max ()) {
120+ return {};
121+ }
122+ return value;
123+ }
124+
125+ template <typename T,
126+ typename std::enable_if<std::is_integral<T>::value && std::is_unsigned<T>::value, bool >::type = true
127+ >
128+ Optional<T>
129+ parse_number (const std::string &s)
130+ {
131+ static_assert (std::numeric_limits<T>::min () >= std::numeric_limits<unsigned long >::min ()
132+ && std::numeric_limits<T>::max () <= std::numeric_limits<unsigned long >::max (),
133+ " supplied type has range broader than unsigned long thus cannot be used with strtol" );
134+
135+ char *end;
136+ errno = 0 ;
137+ unsigned long value = std::strtoul (s.c_str (), &end, 10 );
138+ if (errno != 0
139+ || *end != ' \0 '
140+ || value < std::numeric_limits<T>::min ()
141+ || value > std::numeric_limits<T>::max ()) {
142+ return {};
143+ }
144+ return value;
145+ }
146+
100147} // fdsdump
You can’t perform that action at this time.
0 commit comments