Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion include/behaviortree_cpp/utils/convert_impl.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,11 @@ inline void checkTruncation(const From& from)
}
else
{
doesnt_fit = std::abs(static_cast<int64_t>(from)) > static_cast<int64_t>(max_exact);
// Negate in unsigned arithmetic: std::abs(INT64_MIN) overflows.
const auto value = static_cast<int64_t>(from);
const uint64_t magnitude =
value < 0 ? 0 - static_cast<uint64_t>(value) : static_cast<uint64_t>(value);
doesnt_fit = magnitude > max_exact;
}
if(doesnt_fit)
{
Expand Down
6 changes: 6 additions & 0 deletions include/behaviortree_cpp/utils/safe_any.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,12 @@ inline bool ValidCast(const SRC& val)
{
// For integral to float, check if we can represent the value exactly
TO as_float = static_cast<TO>(val);
// as_float can round up to 2^digits (e.g. INT64_MAX -> 2^63), one past
// the max of SRC. Casting that back to SRC would overflow.
if(as_float >= std::ldexp(TO(1), std::numeric_limits<SRC>::digits))
{
return false;
}
SRC back_conv = static_cast<SRC>(as_float);
return back_conv == val;
}
Expand Down
19 changes: 19 additions & 0 deletions tests/gtest_basic_types.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,25 @@ TEST(BasicTypes, DoubleToIntBoundary)
EXPECT_NO_THROW(bb->set("k", in_range));
}

TEST(BasicTypes, IntToDoubleBoundary)
{
// The precision check must not negate INT64_MIN (signed overflow, undefined
// behavior). Its magnitude is above 2^53, so it is rejected like INT64_MAX.
EXPECT_ANY_THROW((void)BT::Any(INT64_MIN).cast<double>());
EXPECT_ANY_THROW((void)BT::Any(INT64_MAX).cast<double>());
EXPECT_EQ(BT::Any(int64_t(-4503599627370496LL)).cast<double>(), -4503599627370496.0);

// Through Blackboard::set, INT64_MAX rounds up to 2^63 as a double, which must
// not be cast back to int64_t. All three extremes are beyond 2^53.
auto bb = BT::Blackboard::create();
bb->set("d", 1.0); // lock the entry to double
EXPECT_ANY_THROW(bb->set("d", INT64_MAX));
EXPECT_ANY_THROW(bb->set("d", UINT64_MAX));
EXPECT_ANY_THROW(bb->set("d", INT64_MIN));
EXPECT_NO_THROW(bb->set("d", int64_t(1000)));
EXPECT_EQ(bb->get<double>("d"), 1000.0);
}

TEST(BasicTypes, ConvertFromString_Bool)
{
ASSERT_TRUE(convertFromString<bool>("true"));
Expand Down
Loading