Skip to content

Commit 3d8a8fe

Browse files
committed
Allow ints to be passed as floats (Closes #18)
1 parent fa878e6 commit 3d8a8fe

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

include/jsonrpccxx/typemapper.hpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,11 @@ namespace jsonrpccxx {
7272
if (x.get<long long unsigned>() > std::numeric_limits<T>::max()) {
7373
throw JsonRpcException(-32602, "invalid parameter: exceeds value range of " + type_name(expectedType), index);
7474
}
75+
}
76+
else if ((x.type() == json::value_t::number_unsigned || x.type() == json::value_t::number_integer) && expectedType == json::value_t::number_float) {
77+
if (static_cast<long long int>(x.get<double>()) != x.get<long long int>()) {
78+
throw JsonRpcException(-32602, "invalid parameter: exceeds value range of " + type_name(expectedType), index);
79+
}
7580
} else if (x.type() != expectedType) {
7681
throw JsonRpcException(-32602, "invalid parameter: must be " + type_name(expectedType) + ", but is " + type_name(x.type()), index);
7782
}

test/typemapper.cpp

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
using namespace jsonrpccxx;
77
using namespace std;
88
using namespace Catch::Matchers;
9+
using namespace Catch::literals;
910

1011
#define TEST_MODULE "[typemapper]"
1112

@@ -184,8 +185,8 @@ TEST_CASE("test with custom params", TEST_MODULE) {
184185
}
185186

186187
unsigned long unsigned_add(unsigned int a, int b) { return a + b; }
187-
188188
unsigned long unsigned_add2(unsigned short a, short b) { return a + b; }
189+
float float_add(float a, float b) { return a+b; }
189190

190191
TEST_CASE("test number range checking", TEST_MODULE) {
191192
MethodHandle mh = GetHandle(&unsigned_add);
@@ -204,3 +205,10 @@ TEST_CASE("test number range checking", TEST_MODULE) {
204205
CHECK(mh2({max_su, max_ss}) == max_su + max_ss);
205206
REQUIRE_THROWS_WITH(mh2({max_su, max_su}), Contains("invalid parameter: exceeds value range of integer"));
206207
}
208+
209+
TEST_CASE("test auto conversion of float to int passed to float method", TEST_MODULE) {
210+
MethodHandle mh = GetHandle(&float_add);
211+
CHECK(mh(R"([3,3])"_json) == 6.0);
212+
CHECK(mh(R"([3.0,3.0])"_json) == 6.0);
213+
CHECK(mh(R"([3.1,3.2])"_json) == 6.3_a);
214+
}

0 commit comments

Comments
 (0)