Skip to content

Commit

Permalink
Merge pull request #9 from steinwurf/allow-floats-to-be-ints
Browse files Browse the repository at this point in the history
Allow floats to be ints
  • Loading branch information
jpihl committed Mar 27, 2017
2 parents 0731160 + a577244 commit 47836c0
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 8 deletions.
2 changes: 1 addition & 1 deletion NEWS.rst
Expand Up @@ -6,7 +6,7 @@ every change, see the Git log.

Latest
------
* tbd
* Minor: Allow integers to be converted implicitly to floating point values.

4.0.0
-----
Expand Down
13 changes: 11 additions & 2 deletions src/bourne/json.cpp
Expand Up @@ -253,7 +253,8 @@ bool json::is_int() const

bool json::is_float() const
{
return m_type == class_type::floating;
return m_type == class_type::floating ||
m_type == class_type::integral;
}

bool json::is_string() const
Expand Down Expand Up @@ -286,7 +287,15 @@ int64_t json::to_int() const
double json::to_float() const
{
assert(is_float());
return m_internal.m_float;
if (m_type == class_type::floating)
{
return m_internal.m_float;
}
else
{
assert(m_type == class_type::integral);
return (double) m_internal.m_int;
}
}

std::string json::to_string() const
Expand Down
8 changes: 4 additions & 4 deletions src/bourne/json.hpp
Expand Up @@ -212,19 +212,19 @@ class json
{
if (std::is_same<T, bool>::value)
{
return m_type == class_type::boolean;
return is_bool();
}
else if (std::is_integral<T>::value)
{
return m_type == class_type::integral;
return is_int();
}
else if (std::is_floating_point<T>::value)
{
return m_type == class_type::floating;
return is_float();
}
else if (std::is_convertible<T, std::string>::value)
{
return m_type == class_type::string;
return is_string();
}
return false;
}
Expand Down
3 changes: 2 additions & 1 deletion test/src/test_json.cpp
Expand Up @@ -67,12 +67,13 @@ TEST(test_json, test_retrival_of_primitives)
element = 42;
EXPECT_FALSE(element.is_bool());
EXPECT_TRUE(element.is_int());
EXPECT_FALSE(element.is_float());
EXPECT_TRUE(element.is_float());
EXPECT_FALSE(element.is_string());
EXPECT_FALSE(element.is_object());
EXPECT_FALSE(element.is_array());
EXPECT_FALSE(element.is_null());
EXPECT_EQ(42, element.to_int());
EXPECT_EQ(42, element.to_float());

element = 13.37;
EXPECT_FALSE(element.is_bool());
Expand Down

0 comments on commit 47836c0

Please sign in to comment.