ros2_control - rolling
Loading...
Searching...
No Matches
lexical_casts.hpp
1// Copyright 2023 ros2_control Development Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#ifndef HARDWARE_INTERFACE__LEXICAL_CASTS_HPP_
16#define HARDWARE_INTERFACE__LEXICAL_CASTS_HPP_
17
18#include <cstdint>
19#include <limits>
20#include <regex>
21#include <stdexcept>
22#include <string>
23#include <type_traits>
24#include <typeinfo>
25#include <vector>
26
27namespace hardware_interface
28{
29
35double stod(const std::string & s);
36
40float stof(const std::string & s);
41
46template <typename T>
47T stoi_generic(const std::string & s)
48{
49 static_assert(std::is_integral_v<T> && std::is_signed_v<T>, "T must be a signed integral type");
50
51 size_t pos;
52 // stoll is used because long is only 32 bits wide on some platforms.
53 const auto v = std::stoll(s, &pos);
54 if (pos != s.length())
55 {
56 throw std::invalid_argument("Invalid characters in string");
57 }
58 if (v < std::numeric_limits<T>::min() || v > std::numeric_limits<T>::max())
59 {
60 throw std::out_of_range("value not in range of target type");
61 }
62
63 return static_cast<T>(v);
64}
65
66// Explicit instantiations for common signed integer types
67inline int8_t stoi8(const std::string & s) { return stoi_generic<int8_t>(s); }
68inline int16_t stoi16(const std::string & s) { return stoi_generic<int16_t>(s); }
69inline int32_t stoi32(const std::string & s) { return stoi_generic<int32_t>(s); }
70inline int64_t stoi64(const std::string & s) { return stoi_generic<int64_t>(s); }
71
76template <typename T>
77T stoui_generic(const std::string & s)
78{
79 static_assert(
80 std::is_integral_v<T> && std::is_unsigned_v<T>, "T must be an unsigned integral type");
81
82 size_t pos;
83 // stoull is used because unsigned long is only 32 bits wide on some platforms.
84 const auto v = std::stoull(s, &pos);
85 if (pos != s.length())
86 {
87 throw std::invalid_argument("Invalid characters in string");
88 }
89 // stoull wraps a negative input around instead of rejecting it.
90 // A wrapped value can still fit in the target type, so the sign is checked explicitly.
91 const auto first_char = s.find_first_not_of(" \t\n\v\f\r");
92 if (first_char != std::string::npos && s[first_char] == '-' && v != 0)
93 {
94 throw std::out_of_range("value not in range of target type");
95 }
96 if (v > std::numeric_limits<T>::max())
97 {
98 throw std::out_of_range("value not in range of target type");
99 }
100
101 return static_cast<T>(v);
102}
103
104// Explicit instantiations for common unsigned integer types
105inline uint8_t stoui8(const std::string & s) { return stoui_generic<uint8_t>(s); }
106inline uint16_t stoui16(const std::string & s) { return stoui_generic<uint16_t>(s); }
107inline uint32_t stoui32(const std::string & s) { return stoui_generic<uint32_t>(s); }
108inline uint64_t stoui64(const std::string & s) { return stoui_generic<uint64_t>(s); }
109
115std::string to_lower_case(const std::string & string);
116
123bool parse_bool(const std::string & bool_string);
124
125template <typename T>
126std::vector<T> parse_array(const std::string & array_string)
127{
128 // Use regex to check for a flat array: starts with [, ends with ], no nested brackets
129 const std::regex array_regex(R"(^\‍[\s*([^\‍[\‍]]*\s*(,\s*[^\‍[\‍]]+\s*)*)?\‍]$)");
130 if (!std::regex_match(array_string, array_regex))
131 {
132 throw std::invalid_argument(
133 "String must be a flat array: starts with '[' and ends with ']', no nested arrays");
134 }
135
136 // Use regex for the expression that either empty or contains only spaces
137 const std::regex empty_or_spaces_regex(R"(^\‍[\s*\‍]$)");
138 if (std::regex_match(array_string, empty_or_spaces_regex))
139 {
140 return {}; // Return empty array if input is "[]"
141 }
142
143 // Use regex to find cases of comma-separated but only whitespaces or no spaces between them like
144 // "[,]" "[a,b,,c]"
145 const std::regex comma_separated_regex(R"(^\‍[\s*([^,\s]+(\s*,\s*[^,\s]+)*)?\s*\‍]$)");
146 if (!std::regex_match(array_string, comma_separated_regex))
147 {
148 throw std::invalid_argument(
149 "String must be a flat array with comma-separated values and no spaces between them");
150 }
151
152 std::vector<T> result = {};
153 if (array_string == "[]")
154 {
155 return result; // Return empty array if input is "[]"
156 }
157
158 // regex for comma separated values and no spaces between them or just content like "[a,b,c]" or
159 // "[a]" or "[a, b, c]"
160 const std::regex value_regex(R"([^\s,\‍[\‍]]+)");
161 auto begin = std::sregex_iterator(array_string.begin(), array_string.end(), value_regex);
162 auto end = std::sregex_iterator();
163
164 for (auto it = begin; it != end; ++it)
165 {
166 const std::string value_str = it->str(); // Get the first capturing group
167 if constexpr (std::is_same_v<T, std::string>)
168 {
169 result.push_back(value_str);
170 }
171 else if constexpr (std::is_same_v<T, bool>)
172 {
173 result.push_back(parse_bool(value_str));
174 }
175 else if constexpr (std::is_floating_point_v<T> || std::is_integral_v<T>)
176 {
177 try
178 {
179 const T value = static_cast<T>(hardware_interface::stod(value_str));
180 result.push_back(value);
181 }
182 catch (const std::exception &)
183 {
184 throw std::invalid_argument(
185 "Failed converting string to floating point or integer: " + value_str);
186 }
187 }
188 else
189 {
190 throw std::invalid_argument("Unsupported type for parsing: " + std::string(typeid(T).name()));
191 }
192 }
193 return result;
194}
195
196std::vector<std::string> parse_string_array(const std::string & string_array_string);
197
198} // namespace hardware_interface
199
200#endif // HARDWARE_INTERFACE__LEXICAL_CASTS_HPP_
Definition mujoco_system_interface.hpp:57
T stoui_generic(const std::string &s)
Overflow-safe conversion from string to the unsigned integral type T.
Definition lexical_casts.hpp:77
std::string to_lower_case(const std::string &string)
Convert a string to lower case.
Definition lexical_casts.cpp:125
T stoi_generic(const std::string &s)
Overflow-safe conversion from string to the signed integral type T.
Definition lexical_casts.hpp:47
float stof(const std::string &s)
Helper function to convert a std::string to float in a locale-independent way.
Definition lexical_casts.cpp:116
double stod(const std::string &s)
Helper function to convert a std::string to double in a locale-independent way.
Definition lexical_casts.cpp:107
bool parse_bool(const std::string &bool_string)
Parse a boolean value from a string.
Definition lexical_casts.cpp:134