fix(json_render): add json render unittest & optimized Number formatter.
This commit is contained in:
parent
b372611e86
commit
16c5a64bbd
@ -47,20 +47,12 @@ template <typename Out> struct Renderer
|
|||||||
|
|
||||||
void operator()(const Number &number)
|
void operator()(const Number &number)
|
||||||
{
|
{
|
||||||
|
// we don't want to print NaN or Infinity
|
||||||
|
BOOST_ASSERT(std::isfinite(number.value));
|
||||||
// `fmt::memory_buffer` stores first 500 bytes in the object itself(i.e. on stack in this
|
// `fmt::memory_buffer` stores first 500 bytes in the object itself(i.e. on stack in this
|
||||||
// case) and then grows using heap if needed
|
// case) and then grows using heap if needed
|
||||||
fmt::memory_buffer buffer;
|
fmt::memory_buffer buffer;
|
||||||
fmt::format_to(std::back_inserter(buffer), FMT_COMPILE("{}"), number.value);
|
fmt::format_to(std::back_inserter(buffer), FMT_COMPILE("{:.10g}"), number.value);
|
||||||
|
|
||||||
// Truncate to 10 decimal places
|
|
||||||
size_t decimalpos = std::find(buffer.begin(), buffer.end(), '.') - buffer.begin();
|
|
||||||
if (buffer.size() > (decimalpos + 10))
|
|
||||||
{
|
|
||||||
buffer.clear();
|
|
||||||
fmt::format_to(std::back_inserter(buffer), FMT_COMPILE("{0:.10f}"), number.value);
|
|
||||||
|
|
||||||
// buffer.resize(decimalpos + 10);
|
|
||||||
}
|
|
||||||
|
|
||||||
write(buffer.data(), buffer.size());
|
write(buffer.data(), buffer.size());
|
||||||
}
|
}
|
||||||
|
|||||||
@ -16,7 +16,7 @@ BOOST_AUTO_TEST_CASE(number_truncating)
|
|||||||
|
|
||||||
// this number would have more than 10 decimals if not truncated
|
// this number would have more than 10 decimals if not truncated
|
||||||
renderer(Number{42.9995999594999399299});
|
renderer(Number{42.9995999594999399299});
|
||||||
BOOST_CHECK_EQUAL(str, "42.999599959");
|
BOOST_CHECK_EQUAL(str, "42.99959996");
|
||||||
}
|
}
|
||||||
|
|
||||||
BOOST_AUTO_TEST_CASE(integer)
|
BOOST_AUTO_TEST_CASE(integer)
|
||||||
@ -27,4 +27,11 @@ BOOST_AUTO_TEST_CASE(integer)
|
|||||||
BOOST_CHECK_EQUAL(str, "42");
|
BOOST_CHECK_EQUAL(str, "42");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
BOOST_AUTO_TEST_CASE(test_json_issue_6531) {
|
||||||
|
std::string output;
|
||||||
|
osrm::util::json::Renderer<std::string> renderer(output);
|
||||||
|
renderer(0.0000000000017114087924596788);
|
||||||
|
BOOST_CHECK_EQUAL(output, "1.711408792e-12");
|
||||||
|
}
|
||||||
|
|
||||||
BOOST_AUTO_TEST_SUITE_END()
|
BOOST_AUTO_TEST_SUITE_END()
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user