Skip to content

Commit

Permalink
Backport newest appendToStream functions
Browse files Browse the repository at this point in the history
Signed-off-by: Louise Poubel <[email protected]>
  • Loading branch information
chapulina committed Jul 6, 2022
1 parent b6f9587 commit 5c43624
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 0 deletions.
25 changes: 25 additions & 0 deletions include/ignition/math/Helpers.hh
Original file line number Diff line number Diff line change
Expand Up @@ -619,6 +619,31 @@ namespace ignition
sort2(_a, _b);
}

/// \brief Append a number to a stream. Makes sure "-0" is returned as "0".
/// \param[out] _out Output stream.
/// \param[in] _number Number to append.
template<typename T>
inline void appendToStream(std::ostream &_out, T _number)
{
if (std::fpclassify(_number) == FP_ZERO)
{
_out << 0;
}
else
{
_out << _number;
}
}

/// \brief Append a number to a stream, specialized for int.
/// \param[out] _out Output stream.
/// \param[in] _number Number to append.
template<>
inline void appendToStream(std::ostream &_out, int _number)
{
_out << _number;
}

/// \brief Is this a power of 2?
/// \param[in] _x the number
/// \return true if _x is a power of 2, false otherwise
Expand Down
52 changes: 52 additions & 0 deletions src/Helpers_TEST.cc
Original file line number Diff line number Diff line change
Expand Up @@ -970,3 +970,55 @@ TEST(HelpersTest, roundUpMultiple)
EXPECT_EQ(0, math::roundUpMultiple(0, -2));
EXPECT_EQ(-2, math::roundUpMultiple(-2, -2));
}

/////////////////////////////////////////////////
TEST(HelpersTest, AppendToStream)
{
std::ostringstream out;

math::appendToStream(out, 0.0f);
EXPECT_EQ(out.str(), "0");

out << " ";

math::appendToStream(out, 456);
EXPECT_EQ(out.str(), "0 456");

out << " ";

math::appendToStream(out, 0);
EXPECT_EQ(out.str(), "0 456 0");

out << " ";

// ref: https://en.cppreference.com/w/cpp/io/manip/setprecision
const long double pi = std::acos(-1.L);
math::appendToStream(out, pi);
EXPECT_EQ(out.str(), "0 456 0 3.14159");

out << " "
<< std::setprecision(10);

math::appendToStream(out, pi);
EXPECT_EQ(out.str(), "0 456 0 3.14159 3.141592654");

out << " "
<< std::setprecision(std::numeric_limits<long double>::digits10 + 1);

math::appendToStream(out, pi);
#ifdef _WIN32
EXPECT_EQ(out.str(), "0 456 0 3.14159 3.141592654 3.141592653589793");
#else
EXPECT_EQ(out.str(), "0 456 0 3.14159 3.141592654 3.141592653589793239");
#endif

out << " "
<< std::setprecision(3);

math::appendToStream(out, pi);
#ifdef _WIN32
EXPECT_EQ(out.str(), "0 456 0 3.14159 3.141592654 3.141592653589793 3.14");
#else
EXPECT_EQ(out.str(), "0 456 0 3.14159 3.141592654 3.141592653589793239 3.14");
#endif
}

0 comments on commit 5c43624

Please sign in to comment.