BehaviorTree
Core Library to create and execute Behavior Trees
Loading...
Searching...
No Matches
convert_impl.hpp
1/* Copyright (C) 2022-2025 Davide Faconti, Eurecat - All Rights Reserved
2*
3* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
4* to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
5* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7*
8* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
9* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
10* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
11*/
12
13#pragma once
14
16
17#include <cmath>
18#include <type_traits>
19
20#undef max
21#undef min
22
23namespace SafeAny
24{
25
26namespace details
27{
28
29template <typename BoolCondition>
30using EnableIf = typename std::enable_if<BoolCondition::value, void>::type;
31
32template <typename T>
33constexpr bool is_integer()
34{
35 return std::is_same<T, bool>::value || std::is_same<T, char>::value ||
36 std::is_integral<T>::value;
37}
38
39template <typename T>
40constexpr bool is_convertible_type()
41{
42 return is_integer<T>() || std::is_floating_point<T>::value ||
43 std::is_same<T, std::string>::value || std::is_same<T, SimpleString>::value ||
44 std::is_enum<T>::value;
45}
46
47template <typename T>
48constexpr bool is_convertible_to_bool()
49{
50 return is_integer<T>() || std::is_floating_point<T>::value || std::is_enum<T>::value;
51}
52
53template <typename T>
54constexpr bool is_signed()
55{
56 return std::is_signed<T>::value;
57}
58
59template <typename T1, typename T2>
60constexpr bool is_same()
61{
62 return std::is_same<T1, T2>::value;
63}
64
65template <typename From, typename To>
66inline void checkUpperLimit(const From& from)
67{
68 if(from > static_cast<From>(std::numeric_limits<To>::max()))
69 {
70 throw std::runtime_error("Value outside the max numerical limit.");
71 }
72}
73
74template <typename From, typename To>
75inline void checkLowerLimit(const From& from)
76{
77 if constexpr(std::is_same<To, bool>::value)
78 {
79 if(from != 0 && from != 1)
80 {
81 throw std::runtime_error("Implicit casting to bool is not allowed");
82 }
83 }
84 else if(from < std::numeric_limits<To>::min())
85 {
86 throw std::runtime_error("Value outside the lovest numerical limit.");
87 }
88}
89
90template <typename From, typename To>
91inline void checkTruncation(const From& from)
92{
93 // Handle integer to floating point
94 if constexpr(std::is_integral_v<From> && std::is_floating_point_v<To>)
95 {
96 // Check if value can be represented exactly in the target type
97 constexpr uint64_t max_exact = (1LL << std::numeric_limits<double>::digits) - 1;
98 bool doesnt_fit = false;
99 if constexpr(!std::is_signed_v<From>)
100 {
101 doesnt_fit = static_cast<uint64_t>(from) > max_exact;
102 }
103 else
104 {
105 doesnt_fit = std::abs(static_cast<int64_t>(from)) > static_cast<int64_t>(max_exact);
106 }
107 if(doesnt_fit)
108 {
109 throw std::runtime_error("Loss of precision when converting a large integer number "
110 "to floating point:" +
111 std::to_string(from));
112 }
113 }
114 // Handle floating point to integer
115 else if constexpr(std::is_floating_point_v<From> && std::is_integral_v<To>)
116 {
117 // static_cast<From>(To::max) rounds up to an out-of-range value when To has
118 // more significant bits than From's mantissa (e.g. double -> int64_t). In
119 // that case a plain `>` lets the rounded boundary through and the cast to To
120 // below overflows, so use a half-open upper bound to reject it first.
121 constexpr bool max_rounds_up =
122 std::numeric_limits<To>::digits > std::numeric_limits<From>::digits;
123 const From max_limit = static_cast<From>(std::numeric_limits<To>::max());
124 const bool over = max_rounds_up ? (from >= max_limit) : (from > max_limit);
125 if(over || from < static_cast<From>(std::numeric_limits<To>::lowest()) ||
126 from != std::nearbyint(from))
127 {
128 throw std::runtime_error("Invalid floating point to integer conversion");
129 }
130 }
131 // Handle other conversions
132 else
133 {
134 if(from > static_cast<From>(std::numeric_limits<To>::max()) ||
135 from < static_cast<From>(std::numeric_limits<To>::lowest()))
136 {
137 throw std::runtime_error("Value outside numeric limits");
138 }
139 To as_target = static_cast<To>(from);
140 From back_to_source = static_cast<From>(as_target);
141 if(from != back_to_source)
142 {
143 throw std::runtime_error("Value truncated in conversion");
144 }
145 }
146}
147
148//----------------------- Implementation ----------------------------------------------
149
150template <typename SRC, typename DST>
151void convertNumber(const SRC& source, DST& target)
152{
153 static_assert(is_convertible_type<SRC>() && is_convertible_type<DST>(), "Not "
154 "convertible");
155
156 constexpr bool both_integers = is_integer<SRC>() && is_integer<DST>();
157
158 if constexpr(is_signed<SRC>() && !is_signed<DST>())
159 {
160 if(source < 0)
161 {
162 throw std::runtime_error("Value is negative and can't be converted to unsigned");
163 }
164 }
165 // these conversions are always safe (no check needed):
166 // - same type
167 // - float -> double
168 // - floating point to bool (C-style: any non-zero is true)
169 if constexpr(is_same<SRC, DST>() || (is_same<SRC, float>() && is_same<DST, double>()) ||
170 (std::is_floating_point<SRC>::value && is_same<DST, bool>()))
171 {
172 target = static_cast<DST>(source);
173 }
174 // integer to bool: only 0 and 1 are valid
175 else if constexpr(is_integer<SRC>() && is_same<DST, bool>())
176 {
177 checkLowerLimit<SRC, DST>(source);
178 target = static_cast<DST>(source);
179 }
180 else if constexpr(both_integers)
181 {
182 if constexpr(sizeof(SRC) == sizeof(DST) && !is_signed<SRC>() && is_signed<DST>())
183 {
184 checkUpperLimit<SRC, DST>(source);
185 }
186 // casting to a smaller number need to be check
187 else if constexpr(sizeof(SRC) > sizeof(DST))
188 {
189 if constexpr(is_signed<SRC>())
190 {
191 checkLowerLimit<SRC, DST>(source);
192 }
193 checkUpperLimit<SRC, DST>(source);
194 }
195 target = static_cast<DST>(source);
196 }
197 // casting to/from floating points might cause truncation.
198 else if constexpr(std::is_floating_point<SRC>::value ||
199 std::is_floating_point<DST>::value)
200 {
201 bool both_float =
202 std::is_floating_point<SRC>::value && std::is_floating_point<DST>::value;
203 // to avoid being too pedantic, let's accept casting between double and float
204 if(!both_float)
205 {
206 checkTruncation<SRC, DST>(source);
207 }
208 target = static_cast<DST>(source);
209 }
210}
211
212} //end namespace details
213} //end namespace SafeAny
Definition: simple_string.hpp:19