From 37dbcef95a72f76eeb6e2beed7e05a561b111500 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dr=2E=20Patrick=20Urbanke=20=28=E5=8A=89=E8=87=AA=E6=88=90?= =?UTF-8?q?=29?= Date: Sat, 1 Mar 2025 14:51:46 +0800 Subject: [PATCH] Make sure that floating point values are serialized properly in YAML; #363 (#370) --- include/rfl/yaml/Writer.hpp | 21 +++++++++++++++++++-- tests/yaml/test_double.cpp | 21 +++++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 tests/yaml/test_double.cpp diff --git a/include/rfl/yaml/Writer.hpp b/include/rfl/yaml/Writer.hpp index 1a8db584..7ad1aacb 100644 --- a/include/rfl/yaml/Writer.hpp +++ b/include/rfl/yaml/Writer.hpp @@ -88,10 +88,14 @@ class Writer { const T& _var) const noexcept { if constexpr (std::is_same, std::string>() || std::is_same, bool>() || - std::is_floating_point>() || std::is_same, std::remove_cvref_t>()) { (*out_) << YAML::Key << _name.data() << YAML::Value << _var; + } else if constexpr (std::is_floating_point>()) { + // 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>()) { (*out_) << YAML::Key << _name.data() << YAML::Value << static_cast(_var); @@ -103,7 +107,20 @@ class Writer { template OutputVarType insert_value(const T& _var) const noexcept { - (*out_) << _var; + if constexpr (std::is_same, std::string>() || + std::is_same, bool>() || + std::is_same, + std::remove_cvref_t>()) { + (*out_) << _var; + } else if constexpr (std::is_floating_point>()) { + // 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>()) { + (*out_) << static_cast(_var); + } else { + static_assert(rfl::always_false_v, "Unsupported type."); + } return OutputVarType{}; } diff --git a/tests/yaml/test_double.cpp b/tests/yaml/test_double.cpp new file mode 100644 index 00000000..da2247f6 --- /dev/null +++ b/tests/yaml/test_double.cpp @@ -0,0 +1,21 @@ +#include +#include +#include +#include + +#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( + rfl::yaml::read(s).value().get("age").value()) + .value(), + 10.0); +} +} // namespace test_double