Skip to content

Commit 0c4a74e

Browse files
committedFeb 9, 2025·
apply fixes suggested in #919
1 parent b2fc82c commit 0c4a74e

File tree

1 file changed

+35
-2
lines changed

1 file changed

+35
-2
lines changed
 

‎include/behaviortree_cpp/utils/convert_impl.hpp

+35-2
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
#pragma once
1414

1515
#include <type_traits>
16+
#include <cmath>
1617
#include "simple_string.hpp"
1718

1819
#undef max
@@ -88,9 +89,41 @@ inline void checkLowerLimit(const From& from)
8889
template <typename From, typename To>
8990
inline void checkTruncation(const From& from)
9091
{
91-
if(from != static_cast<From>(static_cast<To>(from)))
92+
// Handle integer to floating point
93+
if constexpr(std::is_integral_v<From> && std::is_floating_point_v<To>)
9294
{
93-
throw std::runtime_error("Floating point truncated");
95+
// Check if value can be represented exactly in the target type
96+
To as_float = static_cast<To>(from);
97+
From back_conv = static_cast<From>(as_float);
98+
if(back_conv != from)
99+
{
100+
throw std::runtime_error("Loss of precision in conversion to floating point");
101+
}
102+
}
103+
// Handle floating point to integer
104+
if constexpr(std::is_floating_point_v<From> && std::is_integral_v<To>)
105+
{
106+
if(from > static_cast<From>(std::numeric_limits<To>::max()) ||
107+
from < static_cast<From>(std::numeric_limits<To>::lowest()) ||
108+
from != std::nearbyint(from))
109+
{
110+
throw std::runtime_error("Invalid floating point to integer conversion");
111+
}
112+
}
113+
// Handle other conversions
114+
else
115+
{
116+
if(from > static_cast<From>(std::numeric_limits<To>::max()) ||
117+
from < static_cast<From>(std::numeric_limits<To>::lowest()))
118+
{
119+
throw std::runtime_error("Value outside numeric limits");
120+
}
121+
To as_target = static_cast<To>(from);
122+
From back_to_source = static_cast<From>(as_target);
123+
if(from != back_to_source)
124+
{
125+
throw std::runtime_error("Value truncated in conversion");
126+
}
94127
}
95128
}
96129

0 commit comments

Comments
 (0)
Please sign in to comment.