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

Make sure that floats are serialized properly in YAML; fixes #363 #370

Merged
merged 1 commit into from
Mar 1, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions include/rfl/yaml/Writer.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -88,10 +88,14 @@ class Writer {
const T& _var) const noexcept {
if constexpr (std::is_same<std::remove_cvref_t<T>, std::string>() ||
std::is_same<std::remove_cvref_t<T>, bool>() ||
std::is_floating_point<std::remove_cvref_t<T>>() ||
std::is_same<std::remove_cvref_t<T>,
std::remove_cvref_t<decltype(YAML::Null)>>()) {
(*out_) << YAML::Key << _name.data() << YAML::Value << _var;
} else if constexpr (std::is_floating_point<std::remove_cvref_t<T>>()) {
// std::to_string is necessary to ensure that floating point values are
// always written as floats.
(*out_) << YAML::Key << _name.data() << YAML::Value
<< std::to_string(_var);
} else if constexpr (std::is_integral<std::remove_cvref_t<T>>()) {
(*out_) << YAML::Key << _name.data() << YAML::Value
<< static_cast<int64_t>(_var);
Expand All @@ -103,7 +107,20 @@ class Writer {

template <class T>
OutputVarType insert_value(const T& _var) const noexcept {
(*out_) << _var;
if constexpr (std::is_same<std::remove_cvref_t<T>, std::string>() ||
std::is_same<std::remove_cvref_t<T>, bool>() ||
std::is_same<std::remove_cvref_t<T>,
std::remove_cvref_t<decltype(YAML::Null)>>()) {
(*out_) << _var;
} else if constexpr (std::is_floating_point<std::remove_cvref_t<T>>()) {
// std::to_string is necessary to ensure that floating point values are
// always written as floats.
(*out_) << std::to_string(_var);
} else if constexpr (std::is_integral<std::remove_cvref_t<T>>()) {
(*out_) << static_cast<int64_t>(_var);
} else {
static_assert(rfl::always_false_v<T>, "Unsupported type.");
}
return OutputVarType{};
}

Expand Down
21 changes: 21 additions & 0 deletions tests/yaml/test_double.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#include <iostream>
#include <rfl.hpp>
#include <string>
#include <vector>

#include "write_and_read.hpp"

namespace test_double {

TEST(yaml, test_double) {
auto obj = rfl::Generic::Object();
const double age = 10;
obj["age"] = age;
const auto s = rfl::yaml::write(obj);
EXPECT_EQ(
rfl::from_generic<double>(
rfl::yaml::read<rfl::Generic::Object>(s).value().get("age").value())
.value(),
10.0);
}
} // namespace test_double
Loading