Skip to content

Commit 37dbcef

Browse files
Make sure that floating point values are serialized properly in YAML; #363 (#370)
1 parent e6a2623 commit 37dbcef

File tree

2 files changed

+40
-2
lines changed

2 files changed

+40
-2
lines changed

include/rfl/yaml/Writer.hpp

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,10 +88,14 @@ class Writer {
8888
const T& _var) const noexcept {
8989
if constexpr (std::is_same<std::remove_cvref_t<T>, std::string>() ||
9090
std::is_same<std::remove_cvref_t<T>, bool>() ||
91-
std::is_floating_point<std::remove_cvref_t<T>>() ||
9291
std::is_same<std::remove_cvref_t<T>,
9392
std::remove_cvref_t<decltype(YAML::Null)>>()) {
9493
(*out_) << YAML::Key << _name.data() << YAML::Value << _var;
94+
} else if constexpr (std::is_floating_point<std::remove_cvref_t<T>>()) {
95+
// std::to_string is necessary to ensure that floating point values are
96+
// always written as floats.
97+
(*out_) << YAML::Key << _name.data() << YAML::Value
98+
<< std::to_string(_var);
9599
} else if constexpr (std::is_integral<std::remove_cvref_t<T>>()) {
96100
(*out_) << YAML::Key << _name.data() << YAML::Value
97101
<< static_cast<int64_t>(_var);
@@ -103,7 +107,20 @@ class Writer {
103107

104108
template <class T>
105109
OutputVarType insert_value(const T& _var) const noexcept {
106-
(*out_) << _var;
110+
if constexpr (std::is_same<std::remove_cvref_t<T>, std::string>() ||
111+
std::is_same<std::remove_cvref_t<T>, bool>() ||
112+
std::is_same<std::remove_cvref_t<T>,
113+
std::remove_cvref_t<decltype(YAML::Null)>>()) {
114+
(*out_) << _var;
115+
} else if constexpr (std::is_floating_point<std::remove_cvref_t<T>>()) {
116+
// std::to_string is necessary to ensure that floating point values are
117+
// always written as floats.
118+
(*out_) << std::to_string(_var);
119+
} else if constexpr (std::is_integral<std::remove_cvref_t<T>>()) {
120+
(*out_) << static_cast<int64_t>(_var);
121+
} else {
122+
static_assert(rfl::always_false_v<T>, "Unsupported type.");
123+
}
107124
return OutputVarType{};
108125
}
109126

tests/yaml/test_double.cpp

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
#include <iostream>
2+
#include <rfl.hpp>
3+
#include <string>
4+
#include <vector>
5+
6+
#include "write_and_read.hpp"
7+
8+
namespace test_double {
9+
10+
TEST(yaml, test_double) {
11+
auto obj = rfl::Generic::Object();
12+
const double age = 10;
13+
obj["age"] = age;
14+
const auto s = rfl::yaml::write(obj);
15+
EXPECT_EQ(
16+
rfl::from_generic<double>(
17+
rfl::yaml::read<rfl::Generic::Object>(s).value().get("age").value())
18+
.value(),
19+
10.0);
20+
}
21+
} // namespace test_double

0 commit comments

Comments
 (0)