Skip to content

Commit af642a4

Browse files
committed
Fix Infinity and NaN to int cast
1 parent 078c4ab commit af642a4

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

src/scratch/value_functions.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,7 @@ extern "C"
192192
long value_toLong(const libscratchcpp::ValueData *v)
193193
{
194194
if (v->type == ValueType::Number) {
195-
return v->numberValue;
195+
return std::isnan(v->numberValue) || std::isinf(v->numberValue) ? 0 : v->numberValue;
196196
} else if (v->type == ValueType::Bool)
197197
return v->boolValue;
198198
else if (v->type == ValueType::String)
@@ -205,7 +205,7 @@ extern "C"
205205
int value_toInt(const libscratchcpp::ValueData *v)
206206
{
207207
if (v->type == ValueType::Number)
208-
return v->numberValue;
208+
return std::isnan(v->numberValue) || std::isinf(v->numberValue) ? 0 : v->numberValue;
209209
else if (v->type == ValueType::Bool)
210210
return v->boolValue;
211211
else if (v->type == ValueType::String)

test/scratch_classes/value_test.cpp

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -653,6 +653,13 @@ TEST(ValueTest, ToInt)
653653
v = "NaN";
654654
ASSERT_EQ(v.toInt(), 0);
655655

656+
v = std::numeric_limits<double>::infinity();
657+
ASSERT_EQ(v.toInt(), 0);
658+
v = -std::numeric_limits<double>::infinity();
659+
ASSERT_EQ(v.toInt(), 0);
660+
v = std::numeric_limits<double>::quiet_NaN();
661+
ASSERT_EQ(v.toInt(), 0);
662+
656663
v = "something";
657664
ASSERT_EQ(v.toInt(), 0);
658665

@@ -795,6 +802,13 @@ TEST(ValueTest, ToLong)
795802
v = "NaN";
796803
ASSERT_EQ(v.toLong(), 0);
797804

805+
v = std::numeric_limits<double>::infinity();
806+
ASSERT_EQ(v.toLong(), 0);
807+
v = -std::numeric_limits<double>::infinity();
808+
ASSERT_EQ(v.toLong(), 0);
809+
v = std::numeric_limits<double>::quiet_NaN();
810+
ASSERT_EQ(v.toLong(), 0);
811+
798812
v = "something";
799813
ASSERT_EQ(v.toLong(), 0);
800814

0 commit comments

Comments
 (0)