Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

XmlRpcValue::_doubleFormat should be used during write. #2003

Merged
merged 9 commits into from
Sep 23, 2020
24 changes: 23 additions & 1 deletion utilities/xmlrpcpp/src/XmlRpcValue.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
#endif

#include <sstream>
#include <mutex>

namespace XmlRpc {

Expand Down Expand Up @@ -610,7 +611,28 @@ namespace XmlRpc {
default: break;
case TypeBoolean: os << _value.asBool; break;
case TypeInt: os << _value.asInt; break;
case TypeDouble: os << _value.asDouble; break;
case TypeDouble:
{
static std::once_flag once;
char buf[128]; // Should be long enough
int required_size = std::snprintf(buf, sizeof(buf)-1,
getDoubleFormat().c_str(), _value.asDouble);
if (required_size < 0) {
std::call_once(once,
[](){XmlRpcUtil::error("Failed to format with %s", getDoubleFormat().c_str());});
os << _value.asDouble;
} else if (required_size >= 0 && required_size < static_cast<int>(sizeof(buf))) {
fujitatomoya marked this conversation as resolved.
Show resolved Hide resolved
buf[sizeof(buf)-1] = 0;
os << buf;
} else { // required_size >= static_cast<int>(sizeof(buf)
char required_buf[required_size+1];
std::snprintf(required_buf, required_size,
getDoubleFormat().c_str(), _value.asDouble);
required_buf[required_size] = 0;
os << required_buf;
}
break;
}
case TypeString: os << *_value.asString; break;
case TypeDateTime:
{
Expand Down
34 changes: 34 additions & 0 deletions utilities/xmlrpcpp/test/TestValues.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,40 @@ TEST(XmlRpc, testDouble) {
std::stringstream ss;
ss << d;
EXPECT_EQ("43.7", ss.str());
ss.str("");

// Test format
const XmlRpc::XmlRpcValue a(2.0);
ASSERT_EQ(XmlRpcValue::TypeDouble, d.getType());
const std::string save_format = XmlRpc::XmlRpcValue::getDoubleFormat();

XmlRpc::XmlRpcValue::setDoubleFormat("%32.10f");
ss << a;
EXPECT_EQ(" 2.0000000000", ss.str());
ss.str("");

XmlRpc::XmlRpcValue::setDoubleFormat("%10.32f");
ss << a;
EXPECT_EQ("2.00000000000000000000000000000000", ss.str());
ss.str("");

XmlRpc::XmlRpcValue::setDoubleFormat("%128.10f");
ss << a;
EXPECT_EQ(" "
" "
" "
" 2.000000000", ss.str());
ss.str("");

XmlRpc::XmlRpcValue::setDoubleFormat("%10.128f");
ss << a;
EXPECT_EQ("2.000000000000000000000000000000"
"00000000000000000000000000000000"
"00000000000000000000000000000000"
"000000000000000000000000000000000", ss.str());
ss.str("");

XmlRpc::XmlRpcValue::setDoubleFormat(save_format.c_str());
}

TEST(XmlRpc, testString) {
Expand Down