From 22e1eeb195f9f2daa1eca455dd4e30d4ec50fb42 Mon Sep 17 00:00:00 2001 From: clockblocker Date: Fri, 27 Nov 2026 13:02:25 +0100 Subject: [PATCH 1/5] Add atomic overlay read_into / load_into deserialization for JSON, YAML, and Generic --- docs/content/generic.md | 14 + docs/content/supported_formats/json.md | 17 + docs/content/supported_formats/yaml.md | 13 + include/rfl/from_generic.hpp | 10 + include/rfl/generic/read.hpp | 19 + include/rfl/json/load.hpp | 20 + include/rfl/json/read.hpp | 59 +++ include/rfl/parsing/NamedTupleParser.hpp | 81 ++++ include/rfl/parsing/ParserBox.hpp | 22 + include/rfl/parsing/ParserCommented.hpp | 20 + include/rfl/parsing/ParserDefaultVal.hpp | 16 + include/rfl/parsing/ParserOptional.hpp | 34 ++ include/rfl/parsing/ParserPositional.hpp | 18 + include/rfl/parsing/ParserRef.hpp | 29 ++ include/rfl/parsing/ParserRename.hpp | 19 + include/rfl/parsing/ParserSharedPtr.hpp | 35 ++ include/rfl/parsing/ParserShort.hpp | 19 + include/rfl/parsing/ParserSkip.hpp | 27 ++ include/rfl/parsing/ParserUniquePtr.hpp | 31 ++ include/rfl/parsing/Parser_base.hpp | 22 + include/rfl/parsing/Parser_default.hpp | 183 ++++++++ include/rfl/parsing/ViewReaderWithDefault.hpp | 82 +++- ...ReaderWithDefaultAndStrippedFieldNames.hpp | 67 ++- include/rfl/yaml/load.hpp | 18 + include/rfl/yaml/read.hpp | 53 +++ tests/generic/test_read_into.cpp | 130 ++++++ tests/json/test_read_into.cpp | 420 ++++++++++++++++++ tests/yaml/test_read_into.cpp | 218 +++++++++ 28 files changed, 1678 insertions(+), 18 deletions(-) create mode 100644 tests/generic/test_read_into.cpp create mode 100644 tests/json/test_read_into.cpp create mode 100644 tests/yaml/test_read_into.cpp diff --git a/docs/content/generic.md b/docs/content/generic.md index 30f8478ab..901302e74 100644 --- a/docs/content/generic.md +++ b/docs/content/generic.md @@ -143,3 +143,17 @@ bart["age"] = 10; const auto person = rfl::from_generic(bart).value(); ``` +## Overlaying with `rfl::from_generic_into` + +You can also overlay a partial `rfl::Generic` object onto an existing base struct using `rfl::from_generic_into` (or `rfl::generic::read_into`): + +```cpp +auto patch = rfl::Generic::Object(); +patch["age"] = 11; + +const auto updated = rfl::from_generic_into(person, patch).value(); +// updated.first_name == "Bart", updated.last_name == "Simpson", updated.age == 11 +``` + +Missing fields preserve their values from the base struct, nested structs are overlaid recursively, and processors can be passed as template arguments (`rfl::from_generic_into(base, patch)`). Errors leave an lvalue base untouched. + diff --git a/docs/content/supported_formats/json.md b/docs/content/supported_formats/json.md index e85d91c39..46a7eb74b 100644 --- a/docs/content/supported_formats/json.md +++ b/docs/content/supported_formats/json.md @@ -78,6 +78,23 @@ Note that `std::cout` is also an ostream, so this works as well: rfl::json::write(person, std::cout) << std::endl; ``` +## Overlaying onto an existing struct (`read_into` / `load_into`) + +For layered configuration (e.g., workspace -> user -> local files), you can overlay partial JSON onto an existing base struct with `rfl::json::read_into` and `rfl::json::load_into`: + +```cpp +const auto config = + rfl::json::load_into(Config{}, "workspace.json") + .and_then([](Config c) { return rfl::json::load_into(std::move(c), "user.json"); }) + .and_then([](Config c) { return rfl::json::load_into(std::move(c), "local.json"); }); +``` + +- Fields absent from the JSON preserve their values from the base struct. +- Nested structs (including inside `std::optional` when engaged) are overlaid recursively; an explicit `null` clears `std::optional` to `std::nullopt`. +- Leaf values and containers (`std::vector`, `std::map`, etc.) replace the base value when present. +- Processors such as `rfl::NoExtraFields` and `rfl::SnakeCaseToCamelCase` are supported as template arguments (`rfl::json::read_into(base, json_str)`). +- Atomic on error: `_base` is taken by value and returned inside `rfl::Result`, so an lvalue base is never mutated if parsing or validation fails. + ## Custom constructors One of the great things about C++ is that it gives you control over diff --git a/docs/content/supported_formats/yaml.md b/docs/content/supported_formats/yaml.md index b07f6263e..c06d00738 100644 --- a/docs/content/supported_formats/yaml.md +++ b/docs/content/supported_formats/yaml.md @@ -63,6 +63,19 @@ Note that `std::cout` is also an ostream, so this works as well: rfl::yaml::write(person, std::cout) << std::endl; ``` +## Overlaying onto an existing struct (`read_into` / `load_into`) + +For layered configuration, you can overlay partial YAML onto an existing base struct with `rfl::yaml::read_into` and `rfl::yaml::load_into`: + +```cpp +const auto config = + rfl::yaml::load_into(Config{}, "workspace.yaml") + .and_then([](Config c) { return rfl::yaml::load_into(std::move(c), "user.yaml"); }) + .and_then([](Config c) { return rfl::yaml::load_into(std::move(c), "local.yaml"); }); +``` + +Missing fields preserve their values from the base struct, nested structs are overlaid recursively, explicit `null` clears `std::optional`, processors (such as `rfl::NoExtraFields` or `rfl::SnakeCaseToCamelCase`) work as template parameters, and errors leave an lvalue base untouched. + ## Custom constructors One of the great things about C++ is that it gives you control over diff --git a/include/rfl/from_generic.hpp b/include/rfl/from_generic.hpp index 0080a8114..16aef2b97 100644 --- a/include/rfl/from_generic.hpp +++ b/include/rfl/from_generic.hpp @@ -1,7 +1,10 @@ #ifndef RFL_FROM_GENERIC_HPP_ #define RFL_FROM_GENERIC_HPP_ +#include + #include "Generic.hpp" +#include "Result.hpp" #include "generic/read.hpp" namespace rfl { @@ -12,6 +15,13 @@ auto from_generic(const Generic& _g) { return rfl::generic::read(_g); } +/// Overlays a Generic value onto an existing base object, preserving missing +/// fields and recursively overlaying nested structs. Atomic on error. +template +Result from_generic_into(T _base, const Generic& _g) { + return rfl::generic::read_into(std::move(_base), _g); +} + } // namespace rfl #endif diff --git a/include/rfl/generic/read.hpp b/include/rfl/generic/read.hpp index 6d1a4c36f..51b6191b3 100644 --- a/include/rfl/generic/read.hpp +++ b/include/rfl/generic/read.hpp @@ -2,8 +2,12 @@ #define GENERIC_READ_HPP_ +#include + #include "../Generic.hpp" #include "../Processors.hpp" +#include "../Result.hpp" +#include "../parsing/Parser_base.hpp" #include "Parser.hpp" namespace rfl { @@ -22,6 +26,21 @@ auto read(const Generic& _g) { return Parser>::read(r, _g); } +/// Overlays a Generic value onto an existing C++ object, preserving fields +/// absent from `_g` and recursively overlaying nested structs. +/// Atomic on error: `_base` is taken by value and only returned on success. +/// @tparam Ps Optional processors to apply during deserialization +/// @tparam T The C++ type to overlay onto (deduced from `_base`) +/// @param _base The base object to overlay onto +/// @param _g The Generic value to overlay +/// @return A Result containing the merged object or an error +template +Result read_into(T _base, const Generic& _g) { + const auto r = Reader(); + return parsing::read_into_or_read>( + r, _g, std::move(_base)); +} + } // namespace generic } // namespace rfl diff --git a/include/rfl/json/load.hpp b/include/rfl/json/load.hpp index 0bf3b294f..f76b8caa7 100644 --- a/include/rfl/json/load.hpp +++ b/include/rfl/json/load.hpp @@ -1,6 +1,8 @@ #ifndef RFL_JSON_LOAD_HPP_ #define RFL_JSON_LOAD_HPP_ +#include + #include "../Result.hpp" #include "../io/load_string.hpp" #include "read.hpp" @@ -23,6 +25,24 @@ Result load(const std::string& _fname, const yyjson_read_flag _flag = 0) { return rfl::io::load_string(_fname).and_then(read_string); } +/// Loads a JSON file from disk and overlays it onto an existing object. +/// Missing fields preserve values from `_base`; atomic on error. +/// @tparam Ps Processors to apply during parsing +/// @tparam T The type to overlay onto (deduced from `_base`) +/// @param _base The base object to overlay onto +/// @param _fname The filename/path of the JSON file to load +/// @param _flag Optional yyjson flags for parsing (default: 0) +/// @return Result containing either the overlaid object or an error message +template +Result load_into(T _base, const std::string& _fname, + const yyjson_read_flag _flag = 0) { + auto str = rfl::io::load_string(_fname); + if (!str) { + return error(std::move(str).error()); + } + return read_into(std::move(_base), *str, _flag); +} + } // namespace json } // namespace rfl diff --git a/include/rfl/json/read.hpp b/include/rfl/json/read.hpp index ad3e47b1e..6df4c8e7d 100644 --- a/include/rfl/json/read.hpp +++ b/include/rfl/json/read.hpp @@ -9,9 +9,11 @@ #include #include +#include #include "../Processors.hpp" #include "../internal/wrap_in_rfl_array_t.hpp" +#include "../parsing/Parser_base.hpp" #include "Parser.hpp" #include "Reader.hpp" @@ -75,6 +77,63 @@ auto read(std::istream& _stream, const yyjson_read_flag _flag = 0) { return read(json_str, _flag); } +/// Overlays a JSON var onto an existing object, preserving missing fields and +/// recursively overlaying nested structs. Atomic on error. +/// @tparam Ps Processors to apply during parsing +/// @tparam T The type to overlay onto (deduced from `_base`) +/// @param _base The base object to overlay onto +/// @param _obj The JSON variant object to overlay from +/// @return Result containing either the overlaid object or an error +template +Result read_into(T _base, const InputVarType& _obj) { + const auto r = Reader(); + return parsing::read_into_or_read>( + r, _obj, std::move(_base)); +} + +/// Overlays a JSON string onto an existing object, preserving missing fields +/// and recursively overlaying nested structs. Atomic on error. +/// @tparam Ps Processors to apply during parsing +/// @tparam T The type to overlay onto (deduced from `_base`) +/// @param _base The base object to overlay onto +/// @param _json_str The JSON string to overlay +/// @param _flag Optional yyjson flags for parsing (default: 0). Note: YYJSON_READ_INSITU is not supported. +/// @return Result containing either the overlaid object or an error message +template +Result read_into(T _base, const std::string_view _json_str, + const yyjson_read_flag _flag = 0) { + if (_flag & YYJSON_READ_INSITU) { + return error("YYJSON_READ_INSITU is not supported"); + } + yyjson_read_err err; + yyjson_doc* doc = yyjson_read_opts(const_cast(_json_str.data()), + _json_str.size(), _flag, NULL, &err); + if (!doc) { + return error("Could not parse document: " + std::string(err.msg)); + } + yyjson_val* root = yyjson_doc_get_root(doc); + const auto r = Reader(); + auto res = parsing::read_into_or_read>( + r, InputVarType(root), std::move(_base)); + yyjson_doc_free(doc); + return res; +} + +/// Overlays JSON from an input stream onto an existing object. Atomic on error. +/// @tparam Ps Processors to apply during parsing +/// @tparam T The type to overlay onto (deduced from `_base`) +/// @param _base The base object to overlay onto +/// @param _stream The input stream containing JSON data +/// @param _flag Optional yyjson flags for parsing (default: 0) +/// @return Result containing either the overlaid object or an error message +template +Result read_into(T _base, std::istream& _stream, + const yyjson_read_flag _flag = 0) { + const auto json_str = std::string(std::istreambuf_iterator(_stream), + std::istreambuf_iterator()); + return read_into(std::move(_base), json_str, _flag); +} + } // namespace json } // namespace rfl diff --git a/include/rfl/parsing/NamedTupleParser.hpp b/include/rfl/parsing/NamedTupleParser.hpp index 90b062edb..5bd3ebd5e 100644 --- a/include/rfl/parsing/NamedTupleParser.hpp +++ b/include/rfl/parsing/NamedTupleParser.hpp @@ -99,6 +99,12 @@ struct NamedTupleParser { ProcessorsType>, ViewReaderWithDefault>; + using ViewReaderOverlayType = std::conditional_t< + _no_field_names, + ViewReaderWithDefaultAndStrippedFieldNames, + ViewReaderWithDefault>; + using InputObjectOrArrayType = std::conditional_t<_no_field_names, typename R::InputArrayType, typename R::InputObjectType>; @@ -207,6 +213,55 @@ struct NamedTupleParser { } } + /** + * @brief Overlays input data onto an existing named tuple, preserving + * fields that are absent from the input. + * + * @param _r The reader to use. + * @param _var The input variable to read from. + * @param _base The base named tuple to overlay onto. + * @return A Result containing the overlaid named tuple or an error. + */ + static Result> read_into( + const R& _r, const InputVarType& _var, + NamedTuple _base) noexcept { + auto view = rfl::to_view(_base); + using ViewType = std::remove_cvref_t; + auto err = Parser::read_view_into(_r, _var, + &view); + if (err) [[unlikely]] { + return error(std::move(*err)); + } + return _base; + } + + /** + * @brief Overlays input data into a view, preserving missing fields and + * recursively overlaying nested structs. + * + * @param _r The reader to use. + * @param _var The input variable to read from. + * @param _view The view to overlay into. + * @return An optional error. + */ + static std::optional read_view_into( + const R& _r, const InputVarType& _var, + NamedTuple* _view) noexcept { + if constexpr (_no_field_names) { + auto arr = _r.to_array(_var); + if (!arr) [[unlikely]] { + return arr.error(); + } + return read_object_or_array_into(_r, *arr, _view); + } else { + auto obj = _r.to_object(_var); + if (!obj) [[unlikely]] { + return obj.error(); + } + return read_object_or_array_into(_r, *obj, _view); + } + } + /** * @brief Writes a named tuple to the output. * @@ -531,6 +586,32 @@ struct NamedTupleParser { return std::nullopt; } } + + static std::optional read_object_or_array_into( + const R& _r, const InputObjectOrArrayType& _obj_or_arr, + NamedTupleType* _view) noexcept { + FieldErrors errors; + const auto reader = ViewReaderOverlayType(&_r, _view, &errors); + if constexpr (_no_field_names) { + auto err = _r.read_array(reader, _obj_or_arr); + if (err) [[unlikely]] { + return err; + } + } else { + auto err = _r.read_object(reader, _obj_or_arr); + if (err) [[unlikely]] { + return err; + } + } + if constexpr (internal::fail_fast_v) { + return std::move(errors).error(); + } else { + if (errors.size() != 0) [[unlikely]] { + return to_single_error(std::move(errors)); + } + return std::nullopt; + } + } }; } // namespace rfl::parsing diff --git a/include/rfl/parsing/ParserBox.hpp b/include/rfl/parsing/ParserBox.hpp index 2daf57608..aa1bc64d6 100644 --- a/include/rfl/parsing/ParserBox.hpp +++ b/include/rfl/parsing/ParserBox.hpp @@ -66,6 +66,28 @@ struct ParserBox { } } + /** + * @brief Overlays a Box from the input onto an existing Box. + * + * @param _r The reader to use. + * @param _var The input variable to read from. + * @param _base The existing Box. + * @return A Result containing the overlaid Box or an error. + */ + static Result> read_into(const R& _r, const InputVarType& _var, + Box _base) noexcept { + if constexpr (atomic::is_atomic_v) { + return read(_r, _var); + } else { + const auto to_box = [](auto&& _t) { + return Box::make(std::forward(_t)); + }; + return read_into_or_read, ProcessorsType>( + _r, _var, std::move(*_base)) + .transform(to_box); + } + } + /** * @brief Writes a Box to the output. * diff --git a/include/rfl/parsing/ParserCommented.hpp b/include/rfl/parsing/ParserCommented.hpp index 48f31f33a..d05dd16ad 100644 --- a/include/rfl/parsing/ParserCommented.hpp +++ b/include/rfl/parsing/ParserCommented.hpp @@ -45,6 +45,26 @@ struct ParserCommented { }); } + /** + * @brief Overlays a Commented value from the input onto an existing value, + * preserving any comment attached to `_base`. + * + * @param _r The reader to use. + * @param _var The input variable to read from. + * @param _base The existing Commented value. + * @return A Result containing the overlaid Commented value or an error. + */ + static Result> read_into(const R& _r, const InputVarType& _var, + Commented _base) noexcept { + auto comment = std::move(_base.comment_); + return read_into_or_read, ProcessorsType>( + _r, _var, std::move(_base.value())) + .transform([&comment](auto&& _t) { + return Commented(std::forward(_t), + std::move(comment)); + }); + } + /** * @brief Writes a Commented value to the output. * diff --git a/include/rfl/parsing/ParserDefaultVal.hpp b/include/rfl/parsing/ParserDefaultVal.hpp index 9f11fea44..d067e1c66 100644 --- a/include/rfl/parsing/ParserDefaultVal.hpp +++ b/include/rfl/parsing/ParserDefaultVal.hpp @@ -43,6 +43,22 @@ struct ParserDefaultVal { }); } + /** + * @brief Overlays a DefaultVal from the input onto an existing DefaultVal. + * @param _r The reader to use. + * @param _var The input variable to read from. + * @param _base The existing DefaultVal. + * @return A Result containing the overlaid DefaultVal or an error. + */ + static Result> read_into(const R& _r, const InputVarType& _var, + DefaultVal _base) noexcept { + return read_into_or_read, ProcessorsType>( + _r, _var, std::move(_base.value())) + .transform([](auto&& _t) { + return DefaultVal(std::forward(_t)); + }); + } + /** * @brief Writes a DefaultVal to the output. * @tparam P The type of the parent. diff --git a/include/rfl/parsing/ParserOptional.hpp b/include/rfl/parsing/ParserOptional.hpp index 6ee5eb17e..78a124ac0 100644 --- a/include/rfl/parsing/ParserOptional.hpp +++ b/include/rfl/parsing/ParserOptional.hpp @@ -61,6 +61,40 @@ struct ParserOptional { } } + /** + * @brief Overlays an optional value from the input onto an existing optional. + * + * If the input is null/empty, resets to `std::nullopt`. If the base holds a + * value, recursively overlays onto it; otherwise parses a fresh value. + * + * @param _r The reader to use. + * @param _var The input variable to read from. + * @param _base The existing optional value. + * @return A Result containing the overlaid optional value or an error. + */ + static Result> read_into( + const R& _r, const InputVarType& _var, + std::optional _base) noexcept { + if constexpr (schemaful::IsSchemafulReader) { + return read(_r, _var); + } else { + if (_r.is_empty(_var)) { + return std::optional(); + } + const auto to_opt = [](auto&& _t) { + return std::make_optional(std::forward(_t)); + }; + if (_base.has_value()) { + return read_into_or_read, ProcessorsType>( + _r, _var, std::move(*_base)) + .transform(to_opt); + } + return Parser, ProcessorsType>::read(_r, + _var) + .transform(to_opt); + } + } + /** * @brief Writes an optional value to the output. * diff --git a/include/rfl/parsing/ParserPositional.hpp b/include/rfl/parsing/ParserPositional.hpp index 3b0389752..6899c856a 100644 --- a/include/rfl/parsing/ParserPositional.hpp +++ b/include/rfl/parsing/ParserPositional.hpp @@ -41,6 +41,24 @@ struct ParserPositional { .transform(to_positional); } + /** + * @brief Overlays a Positional value from the input onto an existing value. + * + * @param _r The reader to use. + * @param _var The input variable to read from. + * @param _base The existing Positional value. + * @return A Result containing the overlaid Positional value or an error. + */ + static Result> read_into(const R& _r, const InputVarType& _var, + Positional _base) noexcept { + const auto to_positional = [](auto&& _t) { + return Positional(std::forward(_t)); + }; + return read_into_or_read, ProcessorsType>( + _r, _var, std::move(_base.value())) + .transform(to_positional); + } + /** * @brief Writes a Positional value to the output. * diff --git a/include/rfl/parsing/ParserRef.hpp b/include/rfl/parsing/ParserRef.hpp index 4b5e8152d..4b7080ade 100644 --- a/include/rfl/parsing/ParserRef.hpp +++ b/include/rfl/parsing/ParserRef.hpp @@ -65,6 +65,35 @@ struct ParserRef { } } + /** + * @brief Overlays a Ref from the input onto an existing Ref without mutating + * the shared pointee in place. + * + * @param _r The reader to use. + * @param _var The input variable to read from. + * @param _base The existing Ref. + * @return A Result containing the overlaid Ref or an error. + */ + static Result> read_into(const R& _r, const InputVarType& _var, + Ref _base) noexcept { + if constexpr (atomic::is_atomic_v) { + return read(_r, _var); + } else { + const auto to_ref = [](auto&& _t) { + return Ref::make(std::forward(_t)); + }; + if constexpr (std::is_copy_constructible_v>) { + return read_into_or_read, ProcessorsType>( + _r, _var, std::remove_cvref_t(*_base)) + .transform(to_ref); + } else { + return Parser, ProcessorsType>::read(_r, + _var) + .transform(to_ref); + } + } + } + /** * @brief Writes a Ref to the output. * diff --git a/include/rfl/parsing/ParserRename.hpp b/include/rfl/parsing/ParserRename.hpp index e93e2e7d0..7068cc507 100644 --- a/include/rfl/parsing/ParserRename.hpp +++ b/include/rfl/parsing/ParserRename.hpp @@ -45,6 +45,25 @@ struct ParserRename { .transform(to_rename); } + /** + * @brief Overlays a renamed value from the input onto an existing value. + * + * @param _r The reader to use. + * @param _var The input variable to read from. + * @param _base The existing renamed value. + * @return A Result containing the overlaid value or an error. + */ + static Result> read_into(const R& _r, + const InputVarType& _var, + Rename _base) noexcept { + const auto to_rename = [](auto&& _t) { + return Rename(std::forward(_t)); + }; + return read_into_or_read, ProcessorsType>( + _r, _var, std::move(_base.value())) + .transform(to_rename); + } + /** * @brief Writes a renamed value to the output. * diff --git a/include/rfl/parsing/ParserSharedPtr.hpp b/include/rfl/parsing/ParserSharedPtr.hpp index 50acf14d0..9da2b4f7d 100644 --- a/include/rfl/parsing/ParserSharedPtr.hpp +++ b/include/rfl/parsing/ParserSharedPtr.hpp @@ -82,6 +82,41 @@ struct ParserSharedPtr { } } + /** + * @brief Overlays a shared_ptr from the input onto an existing shared_ptr + * without mutating the shared pointee in place. + * + * @param _r The reader to use. + * @param _var The input variable to read from. + * @param _base The existing shared_ptr. + * @return A Result containing the overlaid shared_ptr or an error. + */ + static Result> read_into( + const R& _r, const InputVarType& _var, + std::shared_ptr _base) noexcept { + if constexpr (atomic::is_atomic_v || schemaful::IsSchemafulReader) { + return read(_r, _var); + } else { + if (_r.is_empty(_var)) { + return std::shared_ptr(); + } + const auto to_shared = [](auto&& _t) { + return std::make_shared(std::forward(_t)); + }; + if constexpr (std::is_copy_constructible_v>) { + if (_base) { + return read_into_or_read, + ProcessorsType>( + _r, _var, std::remove_cvref_t(*_base)) + .transform(to_shared); + } + } + return Parser, ProcessorsType>::read(_r, + _var) + .transform(to_shared); + } + } + /** * @brief Writes a shared_ptr to the output. * diff --git a/include/rfl/parsing/ParserShort.hpp b/include/rfl/parsing/ParserShort.hpp index 691a15bf0..01db2d726 100644 --- a/include/rfl/parsing/ParserShort.hpp +++ b/include/rfl/parsing/ParserShort.hpp @@ -48,6 +48,25 @@ struct ParserShort, ProcessorsType> { .transform(to_short); } + /** + * @brief Overlays a short value from the input onto an existing value. + * + * @param _r The reader to use. + * @param _var The input variable to read from. + * @param _base The existing short value. + * @return A Result containing the overlaid value or an error. + */ + static Result> read_into(const R& _r, + const InputVarType& _var, + Short<_name, T> _base) noexcept { + const auto to_short = [](auto&& _t) { + return Short<_name, T>(std::forward(_t)); + }; + return read_into_or_read, ProcessorsType>( + _r, _var, std::move(_base.value())) + .transform(to_short); + } + /** * @brief Writes a short value to the output. * diff --git a/include/rfl/parsing/ParserSkip.hpp b/include/rfl/parsing/ParserSkip.hpp index 5b31767f6..cbb3db97d 100644 --- a/include/rfl/parsing/ParserSkip.hpp +++ b/include/rfl/parsing/ParserSkip.hpp @@ -59,6 +59,33 @@ struct ParserSkip { } } + /** + * @brief Overlays a Skip value, preserving the base when deserialization is + * skipped. + * + * @param _r The reader to use. + * @param _var The input variable to read from. + * @param _base The existing Skip value. + * @return A Result containing the overlaid or preserved value or an error. + */ + static Result> + read_into( + const R& _r, const InputVarType& _var, + internal::Skip _base) + noexcept { + if constexpr (_skip_deserialization) { + return _base; + } else { + const auto to_skip = [](auto&& _t) { + return internal::Skip( + std::forward(_t)); + }; + return read_into_or_read, ProcessorsType>( + _r, _var, std::move(_base.value())) + .transform(to_skip); + } + } + /** * @brief Writes a value and skips it if required. * diff --git a/include/rfl/parsing/ParserUniquePtr.hpp b/include/rfl/parsing/ParserUniquePtr.hpp index 8eed47a91..12c16cdb8 100644 --- a/include/rfl/parsing/ParserUniquePtr.hpp +++ b/include/rfl/parsing/ParserUniquePtr.hpp @@ -82,6 +82,37 @@ struct ParserUniquePtr { } } + /** + * @brief Overlays a unique_ptr from the input onto an existing unique_ptr. + * + * @param _r The reader to use. + * @param _var The input variable to read from. + * @param _base The existing unique_ptr. + * @return A Result containing the overlaid unique_ptr or an error. + */ + static Result> read_into( + const R& _r, const InputVarType& _var, + std::unique_ptr _base) noexcept { + if constexpr (atomic::is_atomic_v || schemaful::IsSchemafulReader) { + return read(_r, _var); + } else { + if (_r.is_empty(_var)) { + return std::unique_ptr(); + } + const auto to_unique = [](auto&& _t) { + return std::make_unique(std::forward(_t)); + }; + if (_base) { + return read_into_or_read, ProcessorsType>( + _r, _var, std::move(*_base)) + .transform(to_unique); + } + return Parser, ProcessorsType>::read(_r, + _var) + .transform(to_unique); + } + } + /** * @brief Writes a unique_ptr to the output. * diff --git a/include/rfl/parsing/Parser_base.hpp b/include/rfl/parsing/Parser_base.hpp index bb78c9386..85230c56e 100644 --- a/include/rfl/parsing/Parser_base.hpp +++ b/include/rfl/parsing/Parser_base.hpp @@ -1,6 +1,9 @@ #ifndef RFL_PARSING_PARSER_BASE_HPP_ #define RFL_PARSING_PARSER_BASE_HPP_ +#include +#include + #include "AreReaderAndWriter.hpp" namespace rfl::parsing { @@ -17,6 +20,25 @@ template requires AreReaderAndWriter struct Parser; +/** + * @brief Overlays input into an existing value when the parser supports + * `read_into`, otherwise parses a fresh replacement via `read`. + */ +template +auto read_into_or_read(const R& _r, const typename R::InputVarType& _var, + T&& _base) { + using U = std::remove_cvref_t; + if constexpr (requires { + Parser::read_into( + _r, _var, std::forward(_base)); + }) { + return Parser::read_into(_r, _var, + std::forward(_base)); + } else { + return Parser::read(_r, _var); + } +} + } // namespace rfl::parsing #endif diff --git a/include/rfl/parsing/Parser_default.hpp b/include/rfl/parsing/Parser_default.hpp index 80d98b31a..df79f2894 100644 --- a/include/rfl/parsing/Parser_default.hpp +++ b/include/rfl/parsing/Parser_default.hpp @@ -15,6 +15,7 @@ #include "../internal/has_reflection_method_v.hpp" #include "../internal/has_reflection_type_v.hpp" #include "../internal/has_reflector.hpp" +#include "../internal/is_attribute.hpp" #include "../internal/is_basic_type.hpp" #include "../internal/is_deprecated.hpp" #include "../internal/is_description.hpp" @@ -277,6 +278,170 @@ struct Parser { } } + /** + * @brief Overlays input data onto an existing base value. + * + * For structs and transparent wrappers, fields absent from the input preserve + * their values from `_base`, nested structs are overlaid recursively, and + * leaf/container values present in the input replace `_base`. + * + * @param _r The reader to use. + * @param _var The input variable to read from. + * @param _base The base value to overlay onto. + * @return A Result containing the overlaid value or an error. + */ + static RFL_ALWAYS_INLINE auto read_into(const R& _r, const InputVarType& _var, + [[maybe_unused]] T _base) + requires(!std::is_array_v) + { + if constexpr (internal::is_basic_type_v || is_bytestring_v || + is_vectorstring_v || is_string_map_v || + is_vector_like_v) { + return read(_r, _var); + + } else if constexpr (is_shared_ptr_v) { + return ParserSharedPtr::read_into(_r, _var, + std::move(_base)); + + } else if constexpr (is_unique_ptr_v) { + return ParserUniquePtr::read_into(_r, _var, + std::move(_base)); + + } else if constexpr (is_optional_v) { + return ParserOptional::value_type, + ProcessorsType>::read_into(_r, _var, + std::move(_base)); + + } else if constexpr (is_box_v) { + using IsBox = is_box>; + return ParserBox::read_into(_r, _var, std::move(_base)); + + } else if constexpr (is_ref_v) { + using IsRef = is_ref>; + return ParserRef::read_into(_r, _var, std::move(_base)); + + } else if constexpr (is_variant_v || is_rfl_variant_v || + is_tagged_union_v) { + return read(_r, _var); + + } else if constexpr (is_rename_v) { + return ParserRename::read_into(_r, _var, + std::move(_base)); + + } else if constexpr (is_result_v || is_expected_v || + is_duration_v || is_filepath_v) { + return read(_r, _var); + + } else if constexpr (is_skip_v) { + using U = std::remove_cvref_t; + return ParserSkip::read_into(_r, _var, std::move(_base)); + + } else if constexpr (is_span_v || is_time_point_v) { + return read(_r, _var); + + } else if constexpr (is_default_val_v) { + return ParserDefaultVal::read_into( + _r, _var, std::move(_base)); + + } else if constexpr (is_short_v) { + return ParserShort::read_into(_r, _var, + std::move(_base)); + + } else if constexpr (is_positional_v) { + return ParserPositional::Type, + ProcessorsType>::read_into(_r, _var, + std::move(_base)); + + } else if constexpr (is_reference_wrapper_v || is_array_v || + is_rfl_array_v || is_tuple_v || + is_rfl_tuple_v || is_pair_v || + std::is_enum_v || is_wstring_v || + is_string_view_v) { + return read(_r, _var); + + } else if constexpr (is_commented_v) { + return ParserCommented::read_into( + _r, _var, std::move(_base)); + + } else if constexpr (std::is_pointer_v || is_c_array_v) { + return read(_r, _var); + + } else if constexpr (internal::has_read_reflector) { + if constexpr (internal::has_write_reflector) { + const auto wrap_in_t = [](auto&& _named_tuple) -> Result { + try { + using NT = decltype(_named_tuple); + return Reflector::to(std::forward(_named_tuple)); + } catch (std::exception& e) { + return error(e.what()); + } + }; + try { + return read_into_or_read::ReflType, + ProcessorsType>(_r, _var, + Reflector::from(_base)) + .and_then(wrap_in_t); + } catch (std::exception& e) { + return error(e.what()); + } + } else { + return read(_r, _var); + } + + } else if constexpr ((schemaful::IsSchemafulReader && + internal::is_literal_v) || + R::template has_custom_constructor) { + return read(_r, _var); + + } else if constexpr (internal::has_reflection_type_v) { + if constexpr (internal::is_literal_v) { + return read(_r, _var); + } else { + using ReflectionType = std::remove_cvref_t; + const auto wrap_in_t = [](auto&& _named_tuple) -> Result { + try { + using NT = decltype(_named_tuple); + if constexpr (internal::HasFromReflectionMethod) { + return T::from_reflection(std::forward(_named_tuple)); + } else if constexpr (internal::is_validator_v) { + return T::from_value(std::forward(_named_tuple)); + } else { + return T{std::forward(_named_tuple)}; + } + } catch (std::exception& e) { + return error(e.what()); + } + }; + if constexpr (internal::is_description_v || + internal::is_deprecated_v || + internal::is_attribute_v || + internal::is_validator_v) { + return read_into_or_read( + _r, _var, std::move(_base.value())) + .and_then(wrap_in_t); + } else if constexpr (internal::has_reflection_method_v && + std::is_constructible_v< + ReflectionType, + decltype(_base.reflection())>) { + return read_into_or_read( + _r, _var, ReflectionType(_base.reflection())) + .and_then(wrap_in_t); + } else { + return read(_r, _var); + } + } + + } else { + return read_struct_into(_r, _var, std::move(_base)); + } + } + /** * @brief Writes a value to the output. * @@ -758,6 +923,24 @@ struct Parser { } } + /// Overlays input data onto an existing struct instance, preserving any + /// fields not present in the input and recursively overlaying nested structs. + static Result read_struct_into(const R& _r, const InputVarType& _var, + T _base) { + try { + auto view = ProcessorsType::template process(to_view(_base)); + using ViewType = std::remove_cvref_t; + auto err = Parser::read_view_into( + _r, _var, &view); + if (err) [[unlikely]] { + return error(std::move(*err)); + } + return _base; + } catch (std::exception& e) { + return error(e.what()); + } + } + /// The error returned by read_struct_with_default when T{} throws. On its /// own, the exception reads as if the input was wrong, so we name the struct /// and explain why it was default-constructed. diff --git a/include/rfl/parsing/ViewReaderWithDefault.hpp b/include/rfl/parsing/ViewReaderWithDefault.hpp index c2e034322..f35eb5856 100644 --- a/include/rfl/parsing/ViewReaderWithDefault.hpp +++ b/include/rfl/parsing/ViewReaderWithDefault.hpp @@ -18,7 +18,8 @@ namespace rfl::parsing { -template +template class ViewReaderWithDefault { public: using InputVarType = typename R::InputVarType; @@ -83,15 +84,63 @@ class ViewReaderWithDefault { _current_name == name) { std::get(*_found) = true; *_already_assigned = true; - auto res = Parser::read(_r, _var); - if (!res) { - _errors->emplace_back(wrap_field_error(name, std::move(res).error())); - return; - } - if constexpr (std::is_pointer_v) { - move_to(rfl::get(*_view), &(*res)); + if constexpr (_overlay) { + if constexpr (std::is_pointer_v) { + using Target = std::remove_pointer_t; + if constexpr (std::is_array_v) { + auto res = Parser::read(_r, _var); + if (!res) { + _errors->emplace_back( + wrap_field_error(name, std::move(res).error())); + return; + } + move_to(rfl::get(*_view), &(*res)); + } else if constexpr (std::is_const_v) { + auto res = [&]() { + if constexpr (std::is_copy_constructible_v) { + return read_into_or_read( + _r, _var, T(*rfl::get(*_view))); + } else { + return Parser::read(_r, _var); + } + }(); + if (!res) { + _errors->emplace_back( + wrap_field_error(name, std::move(res).error())); + return; + } + move_to(rfl::get(*_view), &(*res)); + } else { + auto res = read_into_or_read( + _r, _var, std::move(*rfl::get(*_view))); + if (!res) { + _errors->emplace_back( + wrap_field_error(name, std::move(res).error())); + return; + } + move_to(rfl::get(*_view), &(*res)); + } + } else { + auto res = read_into_or_read( + _r, _var, std::move(rfl::get(*_view))); + if (!res) { + _errors->emplace_back( + wrap_field_error(name, std::move(res).error())); + return; + } + rfl::get(*_view) = std::move(*res); + } } else { - rfl::get(*_view) = std::move(*res); + auto res = Parser::read(_r, _var); + if (!res) { + _errors->emplace_back(wrap_field_error(name, std::move(res).error())); + return; + } + if constexpr (std::is_pointer_v) { + move_to(rfl::get(*_view), &(*res)); + } else { + rfl::get(*_view) = std::move(*res); + } } } } @@ -106,6 +155,21 @@ class ViewReaderWithDefault { std::remove_cvref_t>; using T = std::remove_cvref_t< std::remove_pointer_t>; + if constexpr (_overlay) { + for (auto& [k, v] : *extra_fields) { + if (k == _current_name) { + auto res = read_into_or_read(_r, _var, + std::move(v)); + if (!res) { + _errors->emplace_back( + wrap_field_error(_current_name, std::move(res).error())); + return; + } + v = std::move(*res); + return; + } + } + } auto res = Parser::read(_r, _var); if (!res) { _errors->emplace_back( diff --git a/include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp b/include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp index 72512ff66..2122db58c 100644 --- a/include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp +++ b/include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp @@ -17,7 +17,8 @@ namespace rfl::parsing { -template +template class ViewReaderWithDefaultAndStrippedFieldNames { public: using InputVarType = typename R::InputVarType; @@ -86,15 +87,63 @@ class ViewReaderWithDefaultAndStrippedFieldNames { std::remove_cvref_t>; constexpr auto name = FieldType::name(); if (_i == i) { - auto res = Parser::read(_r, _var); - if (!res) { - _errors->emplace_back(wrap_field_error(name, std::move(res).error())); - return; - } - if constexpr (std::is_pointer_v) { - move_to(rfl::get(*_view), &(*res)); + if constexpr (_overlay) { + if constexpr (std::is_pointer_v) { + using Target = std::remove_pointer_t; + if constexpr (std::is_array_v) { + auto res = Parser::read(_r, _var); + if (!res) { + _errors->emplace_back( + wrap_field_error(name, std::move(res).error())); + return; + } + move_to(rfl::get(*_view), &(*res)); + } else if constexpr (std::is_const_v) { + auto res = [&]() { + if constexpr (std::is_copy_constructible_v) { + return read_into_or_read( + _r, _var, T(*rfl::get(*_view))); + } else { + return Parser::read(_r, _var); + } + }(); + if (!res) { + _errors->emplace_back( + wrap_field_error(name, std::move(res).error())); + return; + } + move_to(rfl::get(*_view), &(*res)); + } else { + auto res = read_into_or_read( + _r, _var, std::move(*rfl::get(*_view))); + if (!res) { + _errors->emplace_back( + wrap_field_error(name, std::move(res).error())); + return; + } + move_to(rfl::get(*_view), &(*res)); + } + } else { + auto res = read_into_or_read( + _r, _var, std::move(rfl::get(*_view))); + if (!res) { + _errors->emplace_back( + wrap_field_error(name, std::move(res).error())); + return; + } + rfl::get(*_view) = std::move(*res); + } } else { - rfl::get(*_view) = std::move(*res); + auto res = Parser::read(_r, _var); + if (!res) { + _errors->emplace_back(wrap_field_error(name, std::move(res).error())); + return; + } + if constexpr (std::is_pointer_v) { + move_to(rfl::get(*_view), &(*res)); + } else { + rfl::get(*_view) = std::move(*res); + } } } } diff --git a/include/rfl/yaml/load.hpp b/include/rfl/yaml/load.hpp index db4b358f4..7d3eb8ef7 100644 --- a/include/rfl/yaml/load.hpp +++ b/include/rfl/yaml/load.hpp @@ -1,6 +1,8 @@ #ifndef RFL_YAML_LOAD_HPP_ #define RFL_YAML_LOAD_HPP_ +#include + #include "../Result.hpp" #include "../io/load_string.hpp" #include "read.hpp" @@ -22,6 +24,22 @@ Result load(const std::string& _fname) { return rfl::io::load_string(_fname).and_then(read_string); } +/// Loads a YAML file from disk and overlays it onto an existing object. +/// Missing fields preserve values from `_base`; atomic on error. +/// @tparam Ps Processors to apply during parsing +/// @tparam T The type to overlay onto (deduced from `_base`) +/// @param _base The base object to overlay onto +/// @param _fname The filename/path of the YAML file to load +/// @return Result containing either the overlaid object or an error message +template +Result load_into(T _base, const std::string& _fname) { + auto str = rfl::io::load_string(_fname); + if (!str) { + return error(std::move(str).error()); + } + return read_into(std::move(_base), std::string_view(*str)); +} + } // namespace yaml } // namespace rfl diff --git a/include/rfl/yaml/read.hpp b/include/rfl/yaml/read.hpp index f8b1b3385..2a659d905 100644 --- a/include/rfl/yaml/read.hpp +++ b/include/rfl/yaml/read.hpp @@ -6,10 +6,12 @@ #include #include #include +#include #include "../Processors.hpp" #include "../internal/no_field_names_v.hpp" #include "../internal/wrap_in_rfl_array_t.hpp" +#include "../parsing/Parser_base.hpp" #include "Parser.hpp" #include "Reader.hpp" @@ -75,6 +77,57 @@ auto read(std::istream& _stream) { return read(yaml_str); } +/// Overlays a YAML var onto an existing object, preserving missing fields and +/// recursively overlaying nested structs. Atomic on error. +/// @tparam Ps Processors to apply during parsing +/// @tparam T The type to overlay onto (deduced from `_base`) +/// @param _base The base object to overlay onto +/// @param _var The YAML variant object to overlay from +/// @param _yaml_str The original YAML string (used for error context) +/// @return Result containing either the overlaid object or an error +template +Result read_into(T _base, const InputVarType& _var, + const std::string& _yaml_str) { + const auto r = Reader(_yaml_str); + using ProcessorsType = Processors; + static_assert(!internal::no_field_names_v, + "The NoFieldNames processor is not supported for BSON, XML, " + "TOML, or YAML."); + return parsing::read_into_or_read( + r, _var, std::move(_base)); +} + +/// Overlays a YAML string onto an existing object, preserving missing fields +/// and recursively overlaying nested structs. Atomic on error. +/// @tparam Ps Processors to apply during parsing +/// @tparam T The type to overlay onto (deduced from `_base`) +/// @param _base The base object to overlay onto +/// @param _yaml_str The YAML string to overlay +/// @return Result containing either the overlaid object or an error message +template +Result read_into(T _base, const std::string_view _yaml_str) { + try { + const auto yaml_str = std::string(_yaml_str); + const auto var = InputVarType(YAML::Load(yaml_str)); + return read_into(std::move(_base), var, yaml_str); + } catch (std::exception& e) { + return error(e.what()); + } +} + +/// Overlays YAML from an input stream onto an existing object. Atomic on error. +/// @tparam Ps Processors to apply during parsing +/// @tparam T The type to overlay onto (deduced from `_base`) +/// @param _base The base object to overlay onto +/// @param _stream The input stream containing YAML data +/// @return Result containing either the overlaid object or an error message +template +Result read_into(T _base, std::istream& _stream) { + const auto yaml_str = std::string(std::istreambuf_iterator(_stream), + std::istreambuf_iterator()); + return read_into(std::move(_base), std::string_view(yaml_str)); +} + } // namespace yaml } // namespace rfl diff --git a/tests/generic/test_read_into.cpp b/tests/generic/test_read_into.cpp new file mode 100644 index 000000000..100c945b4 --- /dev/null +++ b/tests/generic/test_read_into.cpp @@ -0,0 +1,130 @@ +#include + +#include +#include +#include +#include + +namespace test_generic_read_into { + +struct Inner { + int a = 1; + int b = 2; +}; + +struct Outer { + std::string name = "base"; + Inner inner; + std::optional opt_inner; +}; + +TEST(generic, from_generic_into_recursive_and_optionals) { + Outer base{ + .name = "workspace", + .inner = Inner{.a = 10, .b = 20}, + .opt_inner = Inner{.a = 100, .b = 200}, + }; + + auto inner_patch = rfl::Generic::Object(); + inner_patch["b"] = 99; + + auto opt_patch = rfl::Generic::Object(); + opt_patch["a"] = 555; + + auto layer1 = rfl::Generic::Object(); + layer1["inner"] = inner_patch; + layer1["opt_inner"] = opt_patch; + + auto layer2 = rfl::Generic::Object(); + layer2["name"] = "local"; + + const auto merged = + rfl::from_generic_into(base, layer1) + .and_then([&](Outer o) { + return rfl::from_generic_into(std::move(o), layer2); + }) + .value(); + + // Original base untouched + EXPECT_EQ(base.name, "workspace"); + EXPECT_EQ(base.inner.b, 20); + EXPECT_EQ(base.opt_inner->a, 100); + + // Merged result has all layers applied + EXPECT_EQ(merged.name, "local"); + EXPECT_EQ(merged.inner.a, 10); + EXPECT_EQ(merged.inner.b, 99); + ASSERT_TRUE(merged.opt_inner.has_value()); + EXPECT_EQ(merged.opt_inner->a, 555); + EXPECT_EQ(merged.opt_inner->b, 200); + + // Explicit null clears optional + auto clear_opt = rfl::Generic::Object(); + clear_opt["opt_inner"] = std::nullopt; + const auto cleared = rfl::from_generic_into(merged, clear_opt).value(); + EXPECT_FALSE(cleared.opt_inner.has_value()); + EXPECT_EQ(cleared.inner.b, 99); +} + +struct ProcessorConfig { + rfl::Validator> max_items = 10; + rfl::Rename<"customKey", std::string> key = "init"; + rfl::Skip skipped = 42; +}; + +TEST(generic, from_generic_into_validators_processors_and_atomicity) { + ProcessorConfig base; + base.skipped = 77; + + auto valid_obj = rfl::Generic::Object(); + valid_obj["maxItems"] = 25; + valid_obj["customKey"] = "hello"; + valid_obj["skipped"] = 999; + + const auto merged = + rfl::from_generic_into( + base, valid_obj) + .value(); + + EXPECT_EQ(merged.max_items.value(), 25); + EXPECT_EQ(merged.key.value(), "hello"); + EXPECT_EQ(merged.skipped.value(), 77); + + // Validator error leaves base untouched + auto invalid_val = rfl::Generic::Object(); + invalid_val["customKey"] = "mutated"; + invalid_val["maxItems"] = 0; + const auto res_invalid = + rfl::from_generic_into(base, invalid_val); + EXPECT_FALSE(res_invalid.has_value()); + EXPECT_EQ(base.key.value(), "init"); + EXPECT_EQ(base.max_items.value(), 10); + + // Extra field rejected under NoExtraFields + auto extra_obj = rfl::Generic::Object(); + extra_obj["unknown"] = 1; + const auto res_extra = + rfl::from_generic_into(base, extra_obj); + EXPECT_FALSE(res_extra.has_value()); +} + +struct MoveOnly { + std::unique_ptr inner; +}; + +TEST(generic, from_generic_into_move_only) { + MoveOnly base{.inner = std::make_unique(Inner{.a = 3, .b = 4})}; + + auto inner_obj = rfl::Generic::Object(); + inner_obj["b"] = 40; + auto root = rfl::Generic::Object(); + root["inner"] = inner_obj; + + const auto merged = + rfl::generic::read_into(std::move(base), root).value(); + ASSERT_NE(merged.inner, nullptr); + EXPECT_EQ(merged.inner->a, 3); + EXPECT_EQ(merged.inner->b, 40); +} + +} // namespace test_generic_read_into diff --git a/tests/json/test_read_into.cpp b/tests/json/test_read_into.cpp new file mode 100644 index 000000000..477e67fbd --- /dev/null +++ b/tests/json/test_read_into.cpp @@ -0,0 +1,420 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace test_read_into { + +struct TlsConfig { + bool enabled = false; + std::string cert_path = "/etc/ssl/default.pem"; + int min_version = 12; +}; + +struct ServerConfig { + std::string host = "127.0.0.1"; + int port = 8080; + TlsConfig tls; +}; + +struct AppConfig { + std::string name = "app"; + int workers = 4; + ServerConfig server; + std::vector tags = {"default"}; + std::map limits = {{"max_conn", 100}}; +}; + +TEST(json, read_into_layered_config_and_then) { + const std::string workspace_json = R"({ + "name": "slang-server", + "server": { + "host": "0.0.0.0", + "tls": { "enabled": true } + }, + "tags": ["workspace", "ci"] + })"; + + const std::string user_json = R"({ + "workers": 16, + "server": { + "port": 9090, + "tls": { "cert_path": "/home/user/cert.pem" } + } + })"; + + const std::string local_json = R"({ + "server": { + "tls": { "min_version": 13 } + }, + "limits": { "max_conn": 500 } + })"; + + const auto cfg = + rfl::json::read_into(AppConfig{}, workspace_json) + .and_then([&](AppConfig c) { + return rfl::json::read_into(std::move(c), user_json); + }) + .and_then([&](AppConfig c) { + return rfl::json::read_into(std::move(c), local_json); + }) + .value(); + + EXPECT_EQ(cfg.name, "slang-server"); + EXPECT_EQ(cfg.workers, 16); + EXPECT_EQ(cfg.server.host, "0.0.0.0"); + EXPECT_EQ(cfg.server.port, 9090); + EXPECT_TRUE(cfg.server.tls.enabled); + EXPECT_EQ(cfg.server.tls.cert_path, "/home/user/cert.pem"); + EXPECT_EQ(cfg.server.tls.min_version, 13); + EXPECT_EQ(cfg.tags, (std::vector{"workspace", "ci"})); + EXPECT_EQ(cfg.limits, (std::map{{"max_conn", 500}})); +} + +TEST(json, read_into_empty_object_preserves_base) { + AppConfig base; + base.name = "custom"; + base.workers = 8; + base.server.port = 1234; + + const auto merged = rfl::json::read_into(base, "{}").value(); + EXPECT_EQ(merged.name, "custom"); + EXPECT_EQ(merged.workers, 8); + EXPECT_EQ(merged.server.port, 1234); + EXPECT_EQ(merged.server.tls.cert_path, "/etc/ssl/default.pem"); +} + +struct SubWithRequired { + std::string label; + int count; +}; + +struct OptionalHolder { + std::optional threshold; + std::optional sub; +}; + +TEST(json, read_into_optionals) { + OptionalHolder base{ + .threshold = 42, + .sub = SubWithRequired{.label = "initial", .count = 10}, + }; + + // Absent preserves both optionals. + { + const auto res = rfl::json::read_into(base, "{}").value(); + ASSERT_TRUE(res.threshold.has_value()); + EXPECT_EQ(*res.threshold, 42); + ASSERT_TRUE(res.sub.has_value()); + EXPECT_EQ(res.sub->label, "initial"); + EXPECT_EQ(res.sub->count, 10); + } + + // Present object overlays existing optional nested struct. + { + const auto res = + rfl::json::read_into(base, R"({"sub":{"count":99}})").value(); + ASSERT_TRUE(res.threshold.has_value()); + EXPECT_EQ(*res.threshold, 42); + ASSERT_TRUE(res.sub.has_value()); + EXPECT_EQ(res.sub->label, "initial"); + EXPECT_EQ(res.sub->count, 99); + } + + // Explicit null clears optional values to nullopt. + { + const auto res = + rfl::json::read_into(base, R"({"threshold":null,"sub":null})").value(); + EXPECT_FALSE(res.threshold.has_value()); + EXPECT_FALSE(res.sub.has_value()); + } + + // nullopt base + present full object parses fresh nested struct. + { + OptionalHolder empty_base{}; + const auto res = + rfl::json::read_into( + empty_base, R"({"threshold":7,"sub":{"label":"fresh","count":3}})") + .value(); + ASSERT_TRUE(res.threshold.has_value()); + EXPECT_EQ(*res.threshold, 7); + ASSERT_TRUE(res.sub.has_value()); + EXPECT_EQ(res.sub->label, "fresh"); + EXPECT_EQ(res.sub->count, 3); + } + + // nullopt base + incomplete nested object fails cleanly (no base to inherit). + { + OptionalHolder empty_base{}; + const auto res = + rfl::json::read_into(empty_base, R"({"sub":{"count":3}})"); + EXPECT_FALSE(res.has_value()); + EXPECT_FALSE(empty_base.sub.has_value()); + } +} + +struct ValidatedConfig { + rfl::Validator, rfl::Maximum<65535>> port = 8080; + std::string host = "localhost"; +}; + +TEST(json, read_into_validator_and_atomicity) { + ValidatedConfig base{.port = 443, .host = "example.com"}; + + // Missing validated field preserves base. + { + const auto res = + rfl::json::read_into(base, R"({"host":"api.example.com"})").value(); + EXPECT_EQ(res.port.value(), 443); + EXPECT_EQ(res.host, "api.example.com"); + } + + // Present valid field updates value. + { + const auto res = rfl::json::read_into(base, R"({"port":8443})").value(); + EXPECT_EQ(res.port.value(), 8443); + EXPECT_EQ(res.host, "example.com"); + } + + // Present invalid field fails atomically, leaving base untouched even when + // an earlier field ("host") succeeded. + { + const auto res = rfl::json::read_into( + base, R"({"host":"mutated.example.com","port":70000})"); + EXPECT_FALSE(res.has_value()); + EXPECT_EQ(base.port.value(), 443); + EXPECT_EQ(base.host, "example.com"); + } +} + +TEST(json, read_into_no_extra_fields_and_error_atomicity) { + AppConfig base; + base.name = "original"; + base.workers = 4; + base.server.port = 8080; + + // Unknown top-level field rejected under NoExtraFields. + { + const auto res = rfl::json::read_into( + base, R"({"name":"changed","unknown_key":123})"); + EXPECT_FALSE(res.has_value()); + EXPECT_EQ(base.name, "original"); + } + + // Unknown nested field rejected under NoExtraFields. + { + const auto res = rfl::json::read_into( + base, R"({"server":{"port":9999,"bogus":true}})"); + EXPECT_FALSE(res.has_value()); + EXPECT_EQ(base.server.port, 8080); + } + + // Syntax error leaves base untouched. + { + const auto res = rfl::json::read_into(base, R"({"name":"changed", )"); + EXPECT_FALSE(res.has_value()); + EXPECT_EQ(base.name, "original"); + } + + // Type mismatch mid-overlay leaves base untouched. + { + const auto res = + rfl::json::read_into(base, R"({"name":"changed","workers":"not_int"})"); + EXPECT_FALSE(res.has_value()); + EXPECT_EQ(base.name, "original"); + EXPECT_EQ(base.workers, 4); + } +} + +struct NamingInner { + int max_retries = 3; + std::string endpoint_url = "https://default"; +}; + +struct NamingConfig { + int request_timeout = 30; + rfl::Rename<"customName", std::string> display_name = "init"; + rfl::Rename<"innerCfg", NamingInner> inner; + rfl::Description<"Number of threads", int> thread_count = 2; + rfl::DefaultVal batch_size = 64; + rfl::Skip runtime_token = "secret-token"; + rfl::SkipDeserialization internal_id = 777; + rfl::SkipSerialization write_only_override = 1; +}; + +TEST(json, read_into_processors_rename_and_skip) { + NamingConfig base; + base.runtime_token = "keep-me"; + base.internal_id = 999; + + const std::string overlay = R"({ + "requestTimeout": 60, + "customName": "overridden", + "innerCfg": { "maxRetries": 5 }, + "threadCount": 8, + "runtimeToken": "should-be-ignored", + "internalId": 12345, + "writeOnlyOverride": 42 + })"; + + const auto merged = + rfl::json::read_into(base, overlay).value(); + + EXPECT_EQ(merged.request_timeout, 60); + EXPECT_EQ(merged.display_name.value(), "overridden"); + EXPECT_EQ(merged.inner.value().max_retries, 5); + EXPECT_EQ(merged.inner.value().endpoint_url, "https://default"); + EXPECT_EQ(merged.thread_count.value(), 8); + EXPECT_EQ(merged.batch_size.value(), 64); + EXPECT_EQ(merged.runtime_token.value(), "keep-me"); + EXPECT_EQ(merged.internal_id.value(), 999); + EXPECT_EQ(merged.write_only_override.value(), 42); +} + +struct MoveOnlySub { + std::unique_ptr a; + std::unique_ptr b; +}; + +struct MoveOnlyConfig { + std::string name; + std::unique_ptr sub; + rfl::Box tls; +}; + +TEST(json, read_into_move_only_struct) { + MoveOnlyConfig base{ + .name = "init", + .sub = std::make_unique(MoveOnlySub{ + .a = std::make_unique(10), + .b = std::make_unique(20), + }), + .tls = rfl::Box::make(TlsConfig{ + .enabled = true, + .cert_path = "/base.pem", + .min_version = 12, + }), + }; + + const auto merged = + rfl::json::read_into( + std::move(base), + R"({"sub":{"b":99},"tls":{"min_version":13}})") + .value(); + + EXPECT_EQ(merged.name, "init"); + ASSERT_NE(merged.sub, nullptr); + ASSERT_NE(merged.sub->a, nullptr); + ASSERT_NE(merged.sub->b, nullptr); + EXPECT_EQ(*merged.sub->a, 10); + EXPECT_EQ(*merged.sub->b, 99); + EXPECT_TRUE(merged.tls->enabled); + EXPECT_EQ(merged.tls->cert_path, "/base.pem"); + EXPECT_EQ(merged.tls->min_version, 13); +} + +struct SharedConfig { + std::shared_ptr tls; + rfl::Ref server; +}; + +TEST(json, read_into_shared_ptr_and_ref_do_not_mutate_original) { + SharedConfig base{ + .tls = std::make_shared( + TlsConfig{.enabled = false, .cert_path = "/orig.pem", .min_version = 12}), + .server = rfl::Ref::make(ServerConfig{.host = "orig", .port = 80}), + }; + + // Even on success, original shared pointees remain unmodified. + const auto merged = + rfl::json::read_into( + base, R"({"tls":{"enabled":true},"server":{"port":443}})") + .value(); + + EXPECT_FALSE(base.tls->enabled); + EXPECT_EQ(base.server->port, 80); + + EXPECT_TRUE(merged.tls->enabled); + EXPECT_EQ(merged.tls->cert_path, "/orig.pem"); + EXPECT_EQ(merged.server->host, "orig"); + EXPECT_EQ(merged.server->port, 443); + + // On failure, original shared pointees remain unmodified. + const auto failed = rfl::json::read_into( + base, R"({"tls":{"enabled":true},"server":{"port":"bad"}})"); + EXPECT_FALSE(failed.has_value()); + EXPECT_FALSE(base.tls->enabled); + EXPECT_EQ(base.server->port, 80); +} + +struct ExtraFieldsConfig { + std::string name = "base"; + rfl::ExtraFields extras; +}; + +TEST(json, read_into_extra_fields_updates_existing_and_preserves_rest) { + ExtraFieldsConfig base; + base.extras["a"] = 1; + base.extras["b"] = 2; + + const auto merged = + rfl::json::read_into(base, R"({"b":20,"c":30})").value(); + + EXPECT_EQ(merged.name, "base"); + EXPECT_EQ(merged.extras.size(), 3u); + EXPECT_EQ(merged.extras.at("a"), 1); + EXPECT_EQ(merged.extras.at("b"), 20); + EXPECT_EQ(merged.extras.at("c"), 30); +} + +TEST(json, read_into_istream_flags_and_load_into) { + AppConfig base; + base.name = "from-base"; + base.workers = 2; + + // istream + yyjson flags (comments and trailing commas) + std::istringstream iss(R"({ + // override workers + "workers": 12, + })"); + const auto from_stream = + rfl::json::read_into( + base, iss, + YYJSON_READ_ALLOW_COMMENTS | YYJSON_READ_ALLOW_TRAILING_COMMAS) + .value(); + EXPECT_EQ(from_stream.name, "from-base"); + EXPECT_EQ(from_stream.workers, 12); + + // load_into from a temporary file + const auto tmp_path = std::filesystem::temp_directory_path() / + "rfl_test_read_into_overlay.json"; + { + std::ofstream ofs(tmp_path); + ofs << R"({"server":{"host":"10.0.0.1"}})"; + } + const auto from_file = + rfl::json::load_into(from_stream, tmp_path.string()).value(); + std::filesystem::remove(tmp_path); + + EXPECT_EQ(from_file.name, "from-base"); + EXPECT_EQ(from_file.workers, 12); + EXPECT_EQ(from_file.server.host, "10.0.0.1"); + EXPECT_EQ(from_file.server.port, 8080); + + // load_into missing file returns error without touching base + const auto missing = + rfl::json::load_into(base, "/nonexistent/path/rfl_overlay_missing.json"); + EXPECT_FALSE(missing.has_value()); + EXPECT_EQ(base.workers, 2); +} + +} // namespace test_read_into diff --git a/tests/yaml/test_read_into.cpp b/tests/yaml/test_read_into.cpp new file mode 100644 index 000000000..fba158fea --- /dev/null +++ b/tests/yaml/test_read_into.cpp @@ -0,0 +1,218 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace test_yaml_read_into { + +struct TlsConfig { + bool enabled = false; + std::string cert_path = "/etc/ssl/default.pem"; + int min_version = 12; +}; + +struct ServerConfig { + std::string host = "127.0.0.1"; + int port = 8080; + TlsConfig tls; +}; + +struct AppConfig { + std::string name = "app"; + int workers = 4; + ServerConfig server; + std::vector tags = {"default"}; +}; + +TEST(yaml, read_into_layered_config_and_then) { + const std::string workspace_yaml = R"( +name: slang-server +server: + host: 0.0.0.0 + tls: + enabled: true +tags: + - workspace + - ci +)"; + + const std::string user_yaml = R"( +workers: 16 +server: + port: 9090 + tls: + cert_path: /home/user/cert.pem +)"; + + const std::string local_yaml = R"( +server: + tls: + min_version: 13 +)"; + + const auto cfg = + rfl::yaml::read_into(AppConfig{}, workspace_yaml) + .and_then([&](AppConfig c) { + return rfl::yaml::read_into(std::move(c), user_yaml); + }) + .and_then([&](AppConfig c) { + return rfl::yaml::read_into(std::move(c), local_yaml); + }) + .value(); + + EXPECT_EQ(cfg.name, "slang-server"); + EXPECT_EQ(cfg.workers, 16); + EXPECT_EQ(cfg.server.host, "0.0.0.0"); + EXPECT_EQ(cfg.server.port, 9090); + EXPECT_TRUE(cfg.server.tls.enabled); + EXPECT_EQ(cfg.server.tls.cert_path, "/home/user/cert.pem"); + EXPECT_EQ(cfg.server.tls.min_version, 13); + EXPECT_EQ(cfg.tags, (std::vector{"workspace", "ci"})); +} + +struct SubWithRequired { + std::string label; + int count; +}; + +struct OptionalHolder { + std::optional threshold; + std::optional sub; +}; + +TEST(yaml, read_into_optionals) { + OptionalHolder base{ + .threshold = 42, + .sub = SubWithRequired{.label = "initial", .count = 10}, + }; + + // Present mapping overlays existing optional struct. + { + const auto res = + rfl::yaml::read_into(base, "sub:\n count: 99\n").value(); + ASSERT_TRUE(res.threshold.has_value()); + EXPECT_EQ(*res.threshold, 42); + ASSERT_TRUE(res.sub.has_value()); + EXPECT_EQ(res.sub->label, "initial"); + EXPECT_EQ(res.sub->count, 99); + } + + // Explicit null clears optional values to nullopt. + { + const auto res = + rfl::yaml::read_into(base, "threshold: null\nsub: null\n").value(); + EXPECT_FALSE(res.threshold.has_value()); + EXPECT_FALSE(res.sub.has_value()); + } + + // nullopt base + complete mapping parses fresh nested struct. + { + OptionalHolder empty_base{}; + const auto res = + rfl::yaml::read_into(empty_base, + "threshold: 7\nsub:\n label: fresh\n count: 3\n") + .value(); + ASSERT_TRUE(res.threshold.has_value()); + EXPECT_EQ(*res.threshold, 7); + ASSERT_TRUE(res.sub.has_value()); + EXPECT_EQ(res.sub->label, "fresh"); + EXPECT_EQ(res.sub->count, 3); + } +} + +struct ValidatedConfig { + rfl::Validator, rfl::Maximum<65535>> port = 8080; + std::string host = "localhost"; + rfl::Rename<"displayName", std::string> name = "init"; + rfl::Skip token = "keep"; +}; + +TEST(yaml, read_into_validators_processors_and_atomicity) { + ValidatedConfig base; + base.port = 443; + base.host = "example.com"; + base.token = "secret"; + + // Naming processor + Rename + Skip preservation + { + const auto merged = + rfl::yaml::read_into( + base, "displayName: updated\ntoken: ignored\n") + .value(); + EXPECT_EQ(merged.port.value(), 443); + EXPECT_EQ(merged.host, "example.com"); + EXPECT_EQ(merged.name.value(), "updated"); + EXPECT_EQ(merged.token.value(), "secret"); + } + + // Validator failure leaves base untouched + { + const auto res = + rfl::yaml::read_into(base, "host: mutated\nport: 0\n"); + EXPECT_FALSE(res.has_value()); + EXPECT_EQ(base.host, "example.com"); + EXPECT_EQ(base.port.value(), 443); + } + + // Unknown key rejected under NoExtraFields, leaving base untouched + { + const auto res = rfl::yaml::read_into( + base, "host: mutated\nunknown_field: 1\n"); + EXPECT_FALSE(res.has_value()); + EXPECT_EQ(base.host, "example.com"); + } + + // Syntax error leaves base untouched + { + const auto res = rfl::yaml::read_into(base, "host: [unclosed"); + EXPECT_FALSE(res.has_value()); + EXPECT_EQ(base.host, "example.com"); + } +} + +struct MoveOnlyConfig { + std::string name; + std::unique_ptr server; +}; + +TEST(yaml, read_into_move_only_and_stream_and_load_into) { + MoveOnlyConfig base{ + .name = "svc", + .server = std::make_unique(ServerConfig{ + .host = "127.0.0.1", + .port = 8080, + .tls = TlsConfig{.enabled = true, .cert_path = "/base.pem", .min_version = 12}, + }), + }; + + std::istringstream iss("server:\n port: 9000\n"); + auto merged = rfl::yaml::read_into(std::move(base), iss).value(); + EXPECT_EQ(merged.name, "svc"); + ASSERT_NE(merged.server, nullptr); + EXPECT_EQ(merged.server->host, "127.0.0.1"); + EXPECT_EQ(merged.server->port, 9000); + EXPECT_TRUE(merged.server->tls.enabled); + EXPECT_EQ(merged.server->tls.cert_path, "/base.pem"); + + const auto tmp_path = std::filesystem::temp_directory_path() / + "rfl_test_read_into_overlay.yaml"; + { + std::ofstream ofs(tmp_path); + ofs << "server:\n tls:\n min_version: 13\n"; + } + const auto from_file = + rfl::yaml::load_into(std::move(merged), tmp_path.string()).value(); + std::filesystem::remove(tmp_path); + + EXPECT_EQ(from_file.server->port, 9000); + EXPECT_EQ(from_file.server->tls.min_version, 13); +} + +} // namespace test_yaml_read_into From 19812a11ea0c7c404a48ed8f8faf2bca2f3ac750 Mon Sep 17 00:00:00 2001 From: clockblocker Date: Fri, 27 Nov 2026 14:15:22 +0100 Subject: [PATCH 2/5] Fix read_into review blockers (throw safety, const/nested fields, Generic fast-path, tests) and add rfl::toml::read_into --- README.md | 6 + docs/content/generic.md | 2 +- docs/content/supported_formats/json.md | 3 +- docs/content/supported_formats/toml.md | 13 + docs/content/supported_formats/yaml.md | 2 +- include/rfl/json/read.hpp | 8 +- include/rfl/parsing/ParserRef.hpp | 12 +- include/rfl/parsing/ParserSharedPtr.hpp | 13 +- include/rfl/parsing/Parser_default.hpp | 34 ++- include/rfl/parsing/ViewReaderWithDefault.hpp | 58 +++- ...ReaderWithDefaultAndStrippedFieldNames.hpp | 58 +++- include/rfl/toml/load.hpp | 18 ++ include/rfl/toml/read.hpp | 58 ++++ tests/generic/test_read_into.cpp | 42 +++ tests/json/test_read_into.cpp | 277 ++++++++++++++++++ tests/toml/test_read_into.cpp | 106 +++++++ tests/yaml/test_read_into.cpp | 22 ++ 17 files changed, 677 insertions(+), 55 deletions(-) create mode 100644 tests/toml/test_read_into.cpp diff --git a/README.md b/README.md index 9cfdfa223..25706ec0b 100644 --- a/README.md +++ b/README.md @@ -614,6 +614,12 @@ const auto c = C{.f1 = "C++", .f2 = "is", .f4 = "great"}; const auto c2 = rfl::replace(c, a); ``` +For layered configuration, you can also overlay partial JSON, YAML, TOML, or `rfl::Generic` documents directly onto an existing struct with `rfl::json::read_into` / `load_into`, `rfl::yaml::read_into` / `load_into`, `rfl::toml::read_into` / `load_into`, and `rfl::from_generic_into`: + +```cpp +const auto merged = rfl::json::read_into(base_config, R"({"port": 9090})"); +``` + ### Support for containers #### C++ standard library diff --git a/docs/content/generic.md b/docs/content/generic.md index 901302e74..157f049bf 100644 --- a/docs/content/generic.md +++ b/docs/content/generic.md @@ -155,5 +155,5 @@ const auto updated = rfl::from_generic_into(person, patch).value(); // updated.first_name == "Bart", updated.last_name == "Simpson", updated.age == 11 ``` -Missing fields preserve their values from the base struct, nested structs are overlaid recursively, and processors can be passed as template arguments (`rfl::from_generic_into(base, patch)`). Errors leave an lvalue base untouched. +Missing fields preserve their values from the base struct, nested structs and `rfl::ExtraFields` merge keys recursively while containers (`std::vector`, `std::map`, etc.) replace the base value wholesale when present (so an empty object clears a map), `const` fields require copy-constructible types, and processors can be passed as template arguments (`rfl::from_generic_into(base, patch)`). Errors leave an lvalue base untouched. diff --git a/docs/content/supported_formats/json.md b/docs/content/supported_formats/json.md index 46a7eb74b..3680b9f43 100644 --- a/docs/content/supported_formats/json.md +++ b/docs/content/supported_formats/json.md @@ -91,9 +91,10 @@ const auto config = - Fields absent from the JSON preserve their values from the base struct. - Nested structs (including inside `std::optional` when engaged) are overlaid recursively; an explicit `null` clears `std::optional` to `std::nullopt`. -- Leaf values and containers (`std::vector`, `std::map`, etc.) replace the base value when present. +- Leaf values and containers (`std::vector`, `std::map`, `std::unordered_map`, etc.) replace the base value wholesale when present (so `{}` clears a map); use a struct or `rfl::ExtraFields` when key-level merging is desired. - Processors such as `rfl::NoExtraFields` and `rfl::SnakeCaseToCamelCase` are supported as template arguments (`rfl::json::read_into(base, json_str)`). - Atomic on error: `_base` is taken by value and returned inside `rfl::Result`, so an lvalue base is never mutated if parsing or validation fails. +- `const` fields are supported as long as their value type is copy-constructible (checked at compile time). ## Custom constructors diff --git a/docs/content/supported_formats/toml.md b/docs/content/supported_formats/toml.md index c5656b966..d5bb5230b 100644 --- a/docs/content/supported_formats/toml.md +++ b/docs/content/supported_formats/toml.md @@ -63,6 +63,19 @@ Note that `std::cout` is also an ostream, so this works as well: rfl::toml::write(person, std::cout) << std::endl; ``` +## Overlaying onto an existing struct (`read_into` / `load_into`) + +For layered configuration, you can overlay partial TOML onto an existing base struct with `rfl::toml::read_into` and `rfl::toml::load_into`: + +```cpp +const auto config = + rfl::toml::load_into(Config{}, "workspace.toml") + .and_then([](Config c) { return rfl::toml::load_into(std::move(c), "user.toml"); }) + .and_then([](Config c) { return rfl::toml::load_into(std::move(c), "local.toml"); }); +``` + +Missing fields (including empty or comment-only `.toml` files) preserve their values from the base struct, nested structs and `rfl::ExtraFields` merge keys recursively while containers (`std::vector`, `std::map`, etc.) replace the base value wholesale when present, processors (such as `rfl::NoExtraFields` or `rfl::SnakeCaseToCamelCase`) work as template parameters, `const` fields require copy-constructible types, and errors leave an lvalue base untouched. Note that TOML has no `null` value, so an engaged `std::optional` cannot be cleared back to `std::nullopt` via a TOML overlay. + ## Custom constructors One of the great things about C++ is that it gives you control over diff --git a/docs/content/supported_formats/yaml.md b/docs/content/supported_formats/yaml.md index c06d00738..b7c75da89 100644 --- a/docs/content/supported_formats/yaml.md +++ b/docs/content/supported_formats/yaml.md @@ -74,7 +74,7 @@ const auto config = .and_then([](Config c) { return rfl::yaml::load_into(std::move(c), "local.yaml"); }); ``` -Missing fields preserve their values from the base struct, nested structs are overlaid recursively, explicit `null` clears `std::optional`, processors (such as `rfl::NoExtraFields` or `rfl::SnakeCaseToCamelCase`) work as template parameters, and errors leave an lvalue base untouched. +Missing fields preserve their values from the base struct, nested structs and `rfl::ExtraFields` merge keys recursively while containers (`std::vector`, `std::map`, etc.) replace the base value wholesale when present (so `{}` clears a map), explicit `null` clears `std::optional`, processors (such as `rfl::NoExtraFields` or `rfl::SnakeCaseToCamelCase`) work as template parameters, `const` fields require copy-constructible types, and errors leave an lvalue base untouched. Note that an empty YAML document (`""`) loads as a null YAML node and fails to cast to a mapping; pass `"{}"` for an empty overlay mapping. ## Custom constructors diff --git a/include/rfl/json/read.hpp b/include/rfl/json/read.hpp index 6df4c8e7d..943fba9a7 100644 --- a/include/rfl/json/read.hpp +++ b/include/rfl/json/read.hpp @@ -111,12 +111,14 @@ Result read_into(T _base, const std::string_view _json_str, if (!doc) { return error("Could not parse document: " + std::string(err.msg)); } + struct DocGuard { + yyjson_doc* doc_; + ~DocGuard() { yyjson_doc_free(doc_); } + } guard{doc}; yyjson_val* root = yyjson_doc_get_root(doc); const auto r = Reader(); - auto res = parsing::read_into_or_read>( + return parsing::read_into_or_read>( r, InputVarType(root), std::move(_base)); - yyjson_doc_free(doc); - return res; } /// Overlays JSON from an input stream onto an existing object. Atomic on error. diff --git a/include/rfl/parsing/ParserRef.hpp b/include/rfl/parsing/ParserRef.hpp index 4b7080ade..f4a5dbdcc 100644 --- a/include/rfl/parsing/ParserRef.hpp +++ b/include/rfl/parsing/ParserRef.hpp @@ -1,6 +1,7 @@ #ifndef RFL_PARSING_PARSER_REF_HPP_ #define RFL_PARSING_PARSER_REF_HPP_ +#include #include #include @@ -83,9 +84,14 @@ struct ParserRef { return Ref::make(std::forward(_t)); }; if constexpr (std::is_copy_constructible_v>) { - return read_into_or_read, ProcessorsType>( - _r, _var, std::remove_cvref_t(*_base)) - .transform(to_ref); + try { + return read_into_or_read, + ProcessorsType>( + _r, _var, std::remove_cvref_t(*_base)) + .transform(to_ref); + } catch (std::exception& e) { + return error(e.what()); + } } else { return Parser, ProcessorsType>::read(_r, _var) diff --git a/include/rfl/parsing/ParserSharedPtr.hpp b/include/rfl/parsing/ParserSharedPtr.hpp index 9da2b4f7d..8e91d6101 100644 --- a/include/rfl/parsing/ParserSharedPtr.hpp +++ b/include/rfl/parsing/ParserSharedPtr.hpp @@ -1,6 +1,7 @@ #ifndef RFL_PARSING_PARSER_SHARED_PTR_HPP_ #define RFL_PARSING_PARSER_SHARED_PTR_HPP_ +#include #include #include #include @@ -105,10 +106,14 @@ struct ParserSharedPtr { }; if constexpr (std::is_copy_constructible_v>) { if (_base) { - return read_into_or_read, - ProcessorsType>( - _r, _var, std::remove_cvref_t(*_base)) - .transform(to_shared); + try { + return read_into_or_read, + ProcessorsType>( + _r, _var, std::remove_cvref_t(*_base)) + .transform(to_shared); + } catch (std::exception& e) { + return error(e.what()); + } } } return Parser, ProcessorsType>::read(_r, diff --git a/include/rfl/parsing/Parser_default.hpp b/include/rfl/parsing/Parser_default.hpp index df79f2894..f3a71bcaa 100644 --- a/include/rfl/parsing/Parser_default.hpp +++ b/include/rfl/parsing/Parser_default.hpp @@ -1,10 +1,12 @@ #ifndef RFL_PARSING_PARSER_DEFAULT_HPP_ #define RFL_PARSING_PARSER_DEFAULT_HPP_ +#include #include #include #include +#include "../Generic.hpp" #include "../Result.hpp" #include "../always_false.hpp" #include "../internal/HasFromReflectionMethod.hpp" @@ -290,13 +292,15 @@ struct Parser { * @param _base The base value to overlay onto. * @return A Result containing the overlaid value or an error. */ - static RFL_ALWAYS_INLINE auto read_into(const R& _r, const InputVarType& _var, - [[maybe_unused]] T _base) + static RFL_ALWAYS_INLINE Result read_into(const R& _r, + const InputVarType& _var, + [[maybe_unused]] T _base) requires(!std::is_array_v) { if constexpr (internal::is_basic_type_v || is_bytestring_v || is_vectorstring_v || is_string_map_v || - is_vector_like_v) { + is_vector_like_v || + std::is_same_v, Generic>) { return read(_r, _var); } else if constexpr (is_shared_ptr_v) { @@ -383,9 +387,10 @@ struct Parser { } }; try { - return read_into_or_read::ReflType, - ProcessorsType>(_r, _var, - Reflector::from(_base)) + using ReflType = + std::remove_cvref_t::ReflType>; + return read_into_or_read( + _r, _var, ReflType(Reflector::from(_base))) .and_then(wrap_in_t); } catch (std::exception& e) { return error(e.what()); @@ -429,9 +434,13 @@ struct Parser { std::is_constructible_v< ReflectionType, decltype(_base.reflection())>) { - return read_into_or_read( - _r, _var, ReflectionType(_base.reflection())) - .and_then(wrap_in_t); + try { + return read_into_or_read( + _r, _var, ReflectionType(_base.reflection())) + .and_then(wrap_in_t); + } catch (std::exception& e) { + return error(e.what()); + } } else { return read(_r, _var); } @@ -935,7 +944,12 @@ struct Parser { if (err) [[unlikely]] { return error(std::move(*err)); } - return _base; + if constexpr (!std::is_nothrow_move_constructible_v && + std::is_copy_constructible_v) { + return Result(static_cast(_base)); + } else { + return _base; + } } catch (std::exception& e) { return error(e.what()); } diff --git a/include/rfl/parsing/ViewReaderWithDefault.hpp b/include/rfl/parsing/ViewReaderWithDefault.hpp index f35eb5856..8ba1beb0b 100644 --- a/include/rfl/parsing/ViewReaderWithDefault.hpp +++ b/include/rfl/parsing/ViewReaderWithDefault.hpp @@ -2,6 +2,7 @@ #define RFL_PARSING_VIEWREADERWITHDEFAULT_HPP_ #include +#include #include #include #include @@ -96,12 +97,15 @@ class ViewReaderWithDefault { } move_to(rfl::get(*_view), &(*res)); } else if constexpr (std::is_const_v) { - auto res = [&]() { - if constexpr (std::is_copy_constructible_v) { + static_assert( + std::is_copy_constructible_v, + "read_into requires const fields to be copy-constructible."); + auto res = [&]() -> Result { + try { return read_into_or_read( _r, _var, T(*rfl::get(*_view))); - } else { - return Parser::read(_r, _var); + } catch (std::exception& e) { + return error(e.what()); } }(); if (!res) { @@ -121,14 +125,34 @@ class ViewReaderWithDefault { move_to(rfl::get(*_view), &(*res)); } } else { - auto res = read_into_or_read( - _r, _var, std::move(rfl::get(*_view))); - if (!res) { - _errors->emplace_back( - wrap_field_error(name, std::move(res).error())); - return; + if constexpr (std::is_const_v) { + static_assert( + std::is_copy_constructible_v, + "read_into requires const fields to be copy-constructible."); + auto res = [&]() -> Result { + try { + return read_into_or_read( + _r, _var, T(rfl::get(*_view))); + } catch (std::exception& e) { + return error(e.what()); + } + }(); + if (!res) { + _errors->emplace_back( + wrap_field_error(name, std::move(res).error())); + return; + } + move_to(&rfl::get(*_view), &(*res)); + } else { + auto res = read_into_or_read( + _r, _var, std::move(rfl::get(*_view))); + if (!res) { + _errors->emplace_back( + wrap_field_error(name, std::move(res).error())); + return; + } + move_to(&rfl::get(*_view), &(*res)); } - rfl::get(*_view) = std::move(*res); } } else { auto res = Parser::read(_r, _var); @@ -212,11 +236,13 @@ class ViewReaderWithDefault { static void move_to(Target* _t, Source* _s) { if constexpr (!rfl::internal::is_array_v && !std::is_array_v) { - if constexpr (std::is_const_v) { - // The struct was default-constructed, so *_t is a live const object - // and must not be assigned to. Re-create it in place instead. If the - // constructor throws, we are inside a noexcept function, so it cannot - // be destroyed twice. + if constexpr (std::is_const_v || + !std::is_move_assignable_v) { + // The struct was default-constructed (or overlaid), so *_t is a live + // const / non-move-assignable object (e.g. a nested struct with a + // const member) and must not be assigned to. Re-create it in place + // instead. If the constructor throws, we are inside a noexcept + // function, so it cannot be destroyed twice. using NonConstTarget = std::remove_const_t; auto* const ptr = const_cast(_t); std::destroy_at(ptr); diff --git a/include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp b/include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp index 2122db58c..be33752d2 100644 --- a/include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp +++ b/include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp @@ -2,6 +2,7 @@ #define RFL_PARSING_VIEWREADERWITHDEFAULTANDSTRIPPEDFIELDNAMES_HPP_ #include +#include #include #include #include @@ -99,12 +100,15 @@ class ViewReaderWithDefaultAndStrippedFieldNames { } move_to(rfl::get(*_view), &(*res)); } else if constexpr (std::is_const_v) { - auto res = [&]() { - if constexpr (std::is_copy_constructible_v) { + static_assert( + std::is_copy_constructible_v, + "read_into requires const fields to be copy-constructible."); + auto res = [&]() -> Result { + try { return read_into_or_read( _r, _var, T(*rfl::get(*_view))); - } else { - return Parser::read(_r, _var); + } catch (std::exception& e) { + return error(e.what()); } }(); if (!res) { @@ -124,14 +128,34 @@ class ViewReaderWithDefaultAndStrippedFieldNames { move_to(rfl::get(*_view), &(*res)); } } else { - auto res = read_into_or_read( - _r, _var, std::move(rfl::get(*_view))); - if (!res) { - _errors->emplace_back( - wrap_field_error(name, std::move(res).error())); - return; + if constexpr (std::is_const_v) { + static_assert( + std::is_copy_constructible_v, + "read_into requires const fields to be copy-constructible."); + auto res = [&]() -> Result { + try { + return read_into_or_read( + _r, _var, T(rfl::get(*_view))); + } catch (std::exception& e) { + return error(e.what()); + } + }(); + if (!res) { + _errors->emplace_back( + wrap_field_error(name, std::move(res).error())); + return; + } + move_to(&rfl::get(*_view), &(*res)); + } else { + auto res = read_into_or_read( + _r, _var, std::move(rfl::get(*_view))); + if (!res) { + _errors->emplace_back( + wrap_field_error(name, std::move(res).error())); + return; + } + move_to(&rfl::get(*_view), &(*res)); } - rfl::get(*_view) = std::move(*res); } } else { auto res = Parser::read(_r, _var); @@ -167,11 +191,13 @@ class ViewReaderWithDefaultAndStrippedFieldNames { static void move_to(Target* _t, Source* _s) { if constexpr (!rfl::internal::is_array_v && !std::is_array_v) { - if constexpr (std::is_const_v) { - // The struct was default-constructed, so *_t is a live const object - // and must not be assigned to. Re-create it in place instead. If the - // constructor throws, we are inside a noexcept function, so it cannot - // be destroyed twice. + if constexpr (std::is_const_v || + !std::is_move_assignable_v) { + // The struct was default-constructed (or overlaid), so *_t is a live + // const / non-move-assignable object (e.g. a nested struct with a + // const member) and must not be assigned to. Re-create it in place + // instead. If the constructor throws, we are inside a noexcept + // function, so it cannot be destroyed twice. using NonConstTarget = std::remove_const_t; auto* const ptr = const_cast(_t); std::destroy_at(ptr); diff --git a/include/rfl/toml/load.hpp b/include/rfl/toml/load.hpp index 326506a39..0834d07e0 100644 --- a/include/rfl/toml/load.hpp +++ b/include/rfl/toml/load.hpp @@ -1,6 +1,8 @@ #ifndef RFL_TOML_LOAD_HPP_ #define RFL_TOML_LOAD_HPP_ +#include + #include "../Result.hpp" #include "../io/load_string.hpp" #include "read.hpp" @@ -21,6 +23,22 @@ Result load(const std::string& _fname) { return rfl::io::load_string(_fname).and_then(read_string); } +/// Loads a TOML file from disk and overlays it onto an existing object. +/// Missing fields preserve values from `_base`; atomic on error. +/// @tparam Ps Processors to apply during parsing +/// @tparam T The type to overlay onto (deduced from `_base`) +/// @param _base The base object to overlay onto +/// @param _fname The filename/path of the TOML file to load +/// @return Result containing either the overlaid object or an error message +template +Result load_into(T _base, const std::string& _fname) { + auto str = rfl::io::load_string(_fname); + if (!str) { + return error(std::move(str).error()); + } + return read_into(std::move(_base), std::string_view(*str)); +} + } // namespace rfl::toml #endif diff --git a/include/rfl/toml/read.hpp b/include/rfl/toml/read.hpp index e83468795..11ef3ebe6 100644 --- a/include/rfl/toml/read.hpp +++ b/include/rfl/toml/read.hpp @@ -5,10 +5,12 @@ #include #include #include +#include #include "../Processors.hpp" #include "../internal/no_field_names_v.hpp" #include "../internal/wrap_in_rfl_array_t.hpp" +#include "../parsing/Parser_base.hpp" #include "Parser.hpp" #include "Reader.hpp" @@ -70,6 +72,62 @@ auto read(std::istream& _stream) { return read(toml_str); } +/// Overlays a TOML var onto an existing object, preserving missing fields and +/// recursively overlaying nested structs. Atomic on error. +/// @tparam Ps Processors to apply during parsing +/// @tparam T The type to overlay onto (deduced from `_base`) +/// @param _base The base object to overlay onto +/// @param _var The TOML variant object to overlay from +/// @return Result containing either the overlaid object or an error +template +Result read_into(T _base, InputVarType _var) { + const auto r = Reader(); + using ProcessorsType = Processors; + static_assert(!internal::no_field_names_v, + "The NoFieldNames processor is not supported for BSON, XML, " + "TOML, or YAML."); + return parsing::read_into_or_read( + r, _var, std::move(_base)); +} + +/// Overlays a TOML string onto an existing object, preserving missing fields +/// and recursively overlaying nested structs. Atomic on error. +/// @tparam Ps Processors to apply during parsing +/// @tparam T The type to overlay onto (deduced from `_base`) +/// @param _base The base object to overlay onto +/// @param _toml_str The TOML string to overlay +/// @return Result containing either the overlaid object or an error message +template +Result read_into(T _base, const std::string_view _toml_str) { +#if TOML_EXCEPTIONS + try { + auto table = ::toml::parse(_toml_str); + return read_into(std::move(_base), &table); + } catch (const std::exception& e) { + return error(e.what()); + } +#else + auto result = ::toml::parse(_toml_str); + if (!result) { + return error(std::string(result.error().description())); + } + return read_into(std::move(_base), &result.table()); +#endif +} + +/// Overlays TOML from an input stream onto an existing object. Atomic on error. +/// @tparam Ps Processors to apply during parsing +/// @tparam T The type to overlay onto (deduced from `_base`) +/// @param _base The base object to overlay onto +/// @param _stream The input stream containing TOML data +/// @return Result containing either the overlaid object or an error message +template +Result read_into(T _base, std::istream& _stream) { + const auto toml_str = std::string(std::istreambuf_iterator(_stream), + std::istreambuf_iterator()); + return read_into(std::move(_base), std::string_view(toml_str)); +} + } // namespace rfl::toml #endif diff --git a/tests/generic/test_read_into.cpp b/tests/generic/test_read_into.cpp index 100c945b4..8c8627398 100644 --- a/tests/generic/test_read_into.cpp +++ b/tests/generic/test_read_into.cpp @@ -127,4 +127,46 @@ TEST(generic, from_generic_into_move_only) { EXPECT_EQ(merged.inner->b, 40); } +struct NonDefaultInner { + int a; + std::string tag; + NonDefaultInner() = delete; + NonDefaultInner(int _a, std::string _tag) : a(_a), tag(std::move(_tag)) {} +}; + +struct NonDefaultOuter { + NonDefaultInner inner; + int count; + NonDefaultOuter() = delete; + NonDefaultOuter(NonDefaultInner _inner, int _count) + : inner(std::move(_inner)), count(_count) {} +}; + +TEST(generic, read_into_non_default_constructible_and_no_field_names) { + const NonDefaultOuter base(NonDefaultInner(10, "base"), 1); + + auto inner_patch = rfl::Generic::Object(); + inner_patch["a"] = 25; + auto patch = rfl::Generic::Object(); + patch["inner"] = inner_patch; + + const auto merged = rfl::from_generic_into(base, patch); + ASSERT_TRUE(merged.has_value()) << merged.error().what(); + EXPECT_EQ(merged->inner.a, 25); + EXPECT_EQ(merged->inner.tag, "base"); + EXPECT_EQ(merged->count, 1); + + // rfl::NoFieldNames positional array overlay: only first element provided. + auto arr = rfl::Generic::Array(); + auto inner_arr = rfl::Generic::Array(); + inner_arr.push_back(99); + arr.push_back(inner_arr); + const auto positional = + rfl::from_generic_into(base, arr); + ASSERT_TRUE(positional.has_value()) << positional.error().what(); + EXPECT_EQ(positional->inner.a, 99); + EXPECT_EQ(positional->inner.tag, "base"); + EXPECT_EQ(positional->count, 1); +} + } // namespace test_generic_read_into diff --git a/tests/json/test_read_into.cpp b/tests/json/test_read_into.cpp index 477e67fbd..6c35b90cd 100644 --- a/tests/json/test_read_into.cpp +++ b/tests/json/test_read_into.cpp @@ -7,8 +7,10 @@ #include #include #include +#include #include #include +#include #include #include @@ -417,4 +419,279 @@ TEST(json, read_into_istream_flags_and_load_into) { EXPECT_EQ(base.workers, 2); } +struct NonDefaultInner { + int a; + std::string label; + NonDefaultInner() = delete; + NonDefaultInner(int _a, std::string _label) + : a(_a), label(std::move(_label)) {} +}; + +struct NonDefaultOuter { + NonDefaultInner inner; + int port; + NonDefaultOuter() = delete; + NonDefaultOuter(NonDefaultInner _inner, int _port) + : inner(std::move(_inner)), port(_port) {} +}; + +struct FlattenedMeta { + std::string env = "prod"; + int version = 1; +}; + +struct WithFlattenedAndWrappers { + rfl::Flatten meta; + rfl::Commented timeout = 30; + rfl::Deprecated<"use new_port", "old port", int> legacy_port = 8000; + rfl::Attribute id = std::string("a1"); + rfl::Generic raw_extra; +}; + +struct ReflectedEndpoint { + std::string host; + int port; +}; + +struct ReadOnlyReflected { + int x; +}; + +struct CustomReflectionObj { + struct Repr { + std::string host = "h"; + int port = 80; + }; + using ReflectionType = Repr; + + std::string host; + int port; + bool throw_on_reflect = false; + + CustomReflectionObj(const Repr& _r) : host(_r.host), port(_r.port) {} + CustomReflectionObj(std::string _h, int _p, bool _throw = false) + : host(std::move(_h)), port(_p), throw_on_reflect(_throw) {} + + Repr reflection() const { + if (throw_on_reflect) { + throw std::runtime_error("reflection() threw"); + } + return Repr{.host = host, .port = port}; + } +}; + +struct ThrowingCopyPayload { + int value = 1; + bool fail_copy = false; + mutable int copy_budget = 0; + + ThrowingCopyPayload() = default; + ThrowingCopyPayload(int _v, bool _fail, int _budget = 0) + : value(_v), fail_copy(_fail), copy_budget(_budget) {} + ThrowingCopyPayload(const ThrowingCopyPayload& _o) + : value(_o.value), fail_copy(_o.fail_copy), copy_budget(_o.copy_budget) { + if (_o.fail_copy) { + if (_o.copy_budget <= 0) { + throw std::runtime_error("copy ctor threw"); + } + --_o.copy_budget; + copy_budget = _o.copy_budget; + } + } + ThrowingCopyPayload(ThrowingCopyPayload&&) noexcept = default; + ThrowingCopyPayload& operator=(const ThrowingCopyPayload&) = default; + ThrowingCopyPayload& operator=(ThrowingCopyPayload&&) noexcept = default; +}; + +} // namespace test_read_into + +namespace rfl { + +template <> +struct Reflector { + struct ReflType { + std::string host; + int port; + }; + static test_read_into::ReflectedEndpoint to(const ReflType& _v) { + return test_read_into::ReflectedEndpoint{.host = _v.host, .port = _v.port}; + } + static ReflType from(const test_read_into::ReflectedEndpoint& _v) { + if (_v.host == "THROW_FROM") { + throw std::runtime_error("Reflector::from threw"); + } + return ReflType{.host = _v.host, .port = _v.port}; + } +}; + +template <> +struct Reflector { + struct ReflType { + int x; + }; + static test_read_into::ReadOnlyReflected to(const ReflType& _v) { + return test_read_into::ReadOnlyReflected{.x = _v.x}; + } +}; + +} // namespace rfl + +namespace test_read_into { + +TEST(json, read_into_non_default_no_field_names_named_tuple_fail_fast) { + // Non-default-constructible nested struct + const NonDefaultOuter base(NonDefaultInner(10, "base"), 8080); + const auto merged = + rfl::json::read_into(base, R"({"inner":{"a":42}})"); + ASSERT_TRUE(merged.has_value()) << merged.error().what(); + EXPECT_EQ(merged->inner.a, 42); + EXPECT_EQ(merged->inner.label, "base"); + EXPECT_EQ(merged->port, 8080); + + // rfl::NoFieldNames positional array overlay (prefix overrides only) + const auto positional = + rfl::json::read_into(base, R"([[77]])"); + ASSERT_TRUE(positional.has_value()) << positional.error().what(); + EXPECT_EQ(positional->inner.a, 77); + EXPECT_EQ(positional->inner.label, "base"); + EXPECT_EQ(positional->port, 8080); + + // rfl::NamedTuple overlay + using NT = rfl::NamedTuple, rfl::Field<"b", std::string>>; + const NT nt_base(1, std::string("keep")); + const auto nt_merged = rfl::json::read_into(nt_base, R"({"a":9})"); + ASSERT_TRUE(nt_merged.has_value()) << nt_merged.error().what(); + EXPECT_EQ(nt_merged->get<"a">(), 9); + EXPECT_EQ(nt_merged->get<"b">(), "keep"); + + // rfl::FailFast stops at first field error and leaves base untouched + const ServerConfig srv; + const auto ff = rfl::json::read_into( + srv, R"({"port":"bad","host":123})"); + EXPECT_FALSE(ff.has_value()); + EXPECT_EQ(srv.port, 8080); + EXPECT_EQ(srv.host, "127.0.0.1"); +} + +TEST(json, read_into_flatten_wrappers_generic_reflector_and_throw_safety) { + // Flatten + Commented + Deprecated + Attribute + Generic fast-path + WithFlattenedAndWrappers w; + w.raw_extra = rfl::Generic(std::string("old_raw")); + const auto w_merged = rfl::json::read_into( + w, R"({"version":2,"timeout":60,"raw_extra":{"k":1}})"); + ASSERT_TRUE(w_merged.has_value()) << w_merged.error().what(); + EXPECT_EQ(w_merged->meta.value().env, "prod"); + EXPECT_EQ(w_merged->meta.value().version, 2); + EXPECT_EQ(w_merged->timeout.value(), 60); + EXPECT_EQ(w_merged->legacy_port.value(), 8000); + EXPECT_EQ(w_merged->id.value(), "a1"); + EXPECT_TRUE(w_merged->raw_extra.to_object().has_value()); + + // Reflector (read+write): partial overlay preserves untouched field + const ReflectedEndpoint ep{.host = "alpha", .port = 8080}; + const auto ep_merged = rfl::json::read_into(ep, R"({"port":9090})"); + ASSERT_TRUE(ep_merged.has_value()) << ep_merged.error().what(); + EXPECT_EQ(ep_merged->host, "alpha"); + EXPECT_EQ(ep_merged->port, 9090); + + // Reflector::from throwing returns Error instead of std::terminate() + const ReflectedEndpoint bad_ep{.host = "THROW_FROM", .port = 8080}; + const auto bad_ep_res = rfl::json::read_into(bad_ep, R"({"port":9090})"); + EXPECT_FALSE(bad_ep_res.has_value()); + + // Read-only Reflector falls back to read() + const ReadOnlyReflected ro{.x = 5}; + const auto ro_res = rfl::json::read_into(ro, R"({"x":12})"); + ASSERT_TRUE(ro_res.has_value()) << ro_res.error().what(); + EXPECT_EQ(ro_res->x, 12); + + // Custom ReflectionType: partial overlay + throwing reflection() safety + const CustomReflectionObj cr("db.local", 5432, false); + const auto cr_merged = rfl::json::read_into(cr, R"({"port":5433})"); + ASSERT_TRUE(cr_merged.has_value()) << cr_merged.error().what(); + EXPECT_EQ(cr_merged->host, "db.local"); + EXPECT_EQ(cr_merged->port, 5433); + + const CustomReflectionObj bad_cr("db.local", 5432, true); + const auto bad_cr_res = rfl::json::read_into(bad_cr, R"({"port":5433})"); + EXPECT_FALSE(bad_cr_res.has_value()); + + // Throwing copy in Ref and std::shared_ptr returns Error (no terminate) + const auto bad_ref = rfl::Ref::make(7, true); + const auto bad_ref_res = rfl::json::read_into(bad_ref, R"({"value":9})"); + EXPECT_FALSE(bad_ref_res.has_value()); + + const auto bad_sp = std::make_shared(7, true); + const auto bad_sp_res = rfl::json::read_into(bad_sp, R"({"value":9})"); + EXPECT_FALSE(bad_sp_res.has_value()); +} + +struct InnerWithConst { + const int id; + int port; +}; + +struct OuterWithConstFields { + const std::string tag; + InnerWithConst inner; +}; + +struct WithThrowingConstField { + const ThrowingCopyPayload payload; +}; + +TEST(json, read_into_top_level_and_nested_const_fields) { + const OuterWithConstFields base{ + .tag = "v1", + .inner = InnerWithConst{.id = 100, .port = 8080}, + }; + + // Overlay only inner.port -> preserves top-level const tag and inner const id + const auto merged1 = + rfl::json::read_into(base, R"({"inner":{"port":9090}})"); + ASSERT_TRUE(merged1.has_value()) << merged1.error().what(); + EXPECT_EQ(merged1->tag, "v1"); + EXPECT_EQ(merged1->inner.id, 100); + EXPECT_EQ(merged1->inner.port, 9090); + + // Overlay top-level const tag AND inner const id -> both updated cleanly, + // while original lvalue base remains untouched. + const auto merged2 = rfl::json::read_into( + base, R"({"tag":"v2","inner":{"id":200}})"); + ASSERT_TRUE(merged2.has_value()) << merged2.error().what(); + EXPECT_EQ(merged2->tag, "v2"); + EXPECT_EQ(merged2->inner.id, 200); + EXPECT_EQ(merged2->inner.port, 8080); + EXPECT_EQ(base.tag, "v1"); + EXPECT_EQ(base.inner.id, 100); + + // Positional NoFieldNames overlay on struct with nested const field. + const auto pos = rfl::json::read_into( + base, R"(["v3",[300]])"); + ASSERT_TRUE(pos.has_value()) << pos.error().what(); + EXPECT_EQ(pos->tag, "v3"); + EXPECT_EQ(pos->inner.id, 300); + EXPECT_EQ(pos->inner.port, 8080); + + // Throwing copy on a const field inside ViewReaderWithDefault returns an + // Error instead of calling std::terminate(). Sweep copy_budget across every + // copy hop so the copy inside ViewReaderWithDefault is guaranteed to throw. + bool caught_as_result_error = false; + for (int budget = 0; budget <= 8; ++budget) { + try { + const auto res = rfl::json::read_into( + WithThrowingConstField{ + .payload = ThrowingCopyPayload(5, true, budget)}, + R"({"payload":{"value":9}})"); + if (!res.has_value()) { + caught_as_result_error = true; + } + } catch (const std::runtime_error&) { + // Thrown in non-noexcept caller parameter copy before entering + // ViewReaderWithDefault. + } + } + EXPECT_TRUE(caught_as_result_error); +} + } // namespace test_read_into diff --git a/tests/toml/test_read_into.cpp b/tests/toml/test_read_into.cpp new file mode 100644 index 000000000..275cccb00 --- /dev/null +++ b/tests/toml/test_read_into.cpp @@ -0,0 +1,106 @@ +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace test_toml_read_into { + +struct TlsConfig { + bool enabled = false; + std::string cert_path = "/etc/ssl/default.pem"; + int min_version = 12; +}; + +struct ServerConfig { + std::string host = "127.0.0.1"; + int port = 8080; + std::optional label; + TlsConfig tls; +}; + +TEST(toml, read_into_partial_nested_and_empty_documents) { + const ServerConfig base{ + .host = "127.0.0.1", + .port = 8080, + .label = "primary", + .tls = TlsConfig{.enabled = true, + .cert_path = "/base.pem", + .min_version = 12}, + }; + + // Empty and comment-only TOML documents parse as empty tables and preserve + // every base field. + const auto empty_res = rfl::toml::read_into(base, ""); + ASSERT_TRUE(empty_res.has_value()) << empty_res.error().what(); + EXPECT_EQ(empty_res->host, "127.0.0.1"); + EXPECT_EQ(empty_res->port, 8080); + EXPECT_EQ(empty_res->label, "primary"); + EXPECT_TRUE(empty_res->tls.enabled); + + const auto comment_res = rfl::toml::read_into(base, "# just a comment\n"); + ASSERT_TRUE(comment_res.has_value()) << comment_res.error().what(); + EXPECT_EQ(comment_res->port, 8080); + + // Partial nested table overlay preserves untouched fields & optional value. + const auto merged = rfl::toml::read_into( + base, "port = 9090\n[tls]\nmin_version = 13\n"); + ASSERT_TRUE(merged.has_value()) << merged.error().what(); + EXPECT_EQ(merged->host, "127.0.0.1"); + EXPECT_EQ(merged->port, 9090); + EXPECT_EQ(merged->label, "primary"); + EXPECT_TRUE(merged->tls.enabled); + EXPECT_EQ(merged->tls.cert_path, "/base.pem"); + EXPECT_EQ(merged->tls.min_version, 13); + + // Unknown key and syntax errors leave lvalue base untouched. + EXPECT_FALSE( + rfl::toml::read_into(base, "unknown_key = 1\n") + .has_value()); + EXPECT_FALSE(rfl::toml::read_into(base, "port = [unclosed").has_value()); + EXPECT_EQ(base.port, 8080); +} + +TEST(toml, read_into_stream_and_load_into) { + const ServerConfig base{ + .host = "localhost", + .port = 8000, + .label = std::nullopt, + .tls = TlsConfig{.enabled = false, + .cert_path = "/default.pem", + .min_version = 12}, + }; + + std::istringstream iss("label = \"from-stream\"\n"); + const auto from_stream = rfl::toml::read_into(base, iss).value(); + EXPECT_EQ(from_stream.host, "localhost"); + EXPECT_EQ(from_stream.label, "from-stream"); + + const auto tmp_path = + std::filesystem::temp_directory_path() / "rfl_test_read_into_overlay.toml"; + { + std::ofstream ofs(tmp_path); + ofs << "port = 8443\n[tls]\nenabled = true\n"; + } + const auto from_file = + rfl::toml::load_into(from_stream, tmp_path.string()).value(); + std::filesystem::remove(tmp_path); + + EXPECT_EQ(from_file.host, "localhost"); + EXPECT_EQ(from_file.port, 8443); + EXPECT_EQ(from_file.label, "from-stream"); + EXPECT_TRUE(from_file.tls.enabled); + EXPECT_EQ(from_file.tls.cert_path, "/default.pem"); + + // Missing file leaves base untouched. + const auto missing = rfl::toml::load_into( + base, "/nonexistent/path/rfl_overlay_missing.toml"); + EXPECT_FALSE(missing.has_value()); + EXPECT_EQ(base.port, 8000); +} + +} // namespace test_toml_read_into diff --git a/tests/yaml/test_read_into.cpp b/tests/yaml/test_read_into.cpp index fba158fea..e85a420a9 100644 --- a/tests/yaml/test_read_into.cpp +++ b/tests/yaml/test_read_into.cpp @@ -215,4 +215,26 @@ TEST(yaml, read_into_move_only_and_stream_and_load_into) { EXPECT_EQ(from_file.server->tls.min_version, 13); } +TEST(yaml, read_into_empty_document_vs_empty_mapping) { + const ServerConfig base{ + .host = "localhost", + .port = 8080, + .tls = TlsConfig{.enabled = true, .cert_path = "/a.pem", .min_version = 12}, + }; + + // Empty YAML document ("") parses as a null node and fails cleanly without + // mutating the base struct. + const auto empty_doc = rfl::yaml::read_into(base, ""); + EXPECT_FALSE(empty_doc.has_value()); + EXPECT_EQ(base.host, "localhost"); + EXPECT_EQ(base.port, 8080); + + // Explicit empty mapping ("{}") preserves all base fields. + const auto empty_map = rfl::yaml::read_into(base, "{}"); + ASSERT_TRUE(empty_map.has_value()) << empty_map.error().what(); + EXPECT_EQ(empty_map->host, "localhost"); + EXPECT_EQ(empty_map->port, 8080); + EXPECT_TRUE(empty_map->tls.enabled); +} + } // namespace test_yaml_read_into From 14c68e2a3210e05430cead2605a68718bb2380bb Mon Sep 17 00:00:00 2001 From: clockblocker Date: Fri, 27 Nov 2026 14:34:26 +0100 Subject: [PATCH 3/5] Eliminate remaining noexcept throw gaps in read_into with in-place overlay and try/catch guards --- include/rfl/parsing/NamedTupleParser.hpp | 32 ++++-- include/rfl/parsing/ParserBox.hpp | 17 ++-- include/rfl/parsing/ParserCommented.hpp | 20 ++-- include/rfl/parsing/ParserDefaultVal.hpp | 17 +++- include/rfl/parsing/ParserOptional.hpp | 75 ++++++++++++-- include/rfl/parsing/ParserPositional.hpp | 18 ++-- include/rfl/parsing/ParserRename.hpp | 18 ++-- include/rfl/parsing/ParserShort.hpp | 18 ++-- include/rfl/parsing/ParserSkip.hpp | 26 +++-- include/rfl/parsing/ParserUniquePtr.hpp | 23 +++-- include/rfl/parsing/Parser_base.hpp | 17 ++++ include/rfl/parsing/Parser_default.hpp | 95 +++++++++++++++++- include/rfl/parsing/ViewReaderWithDefault.hpp | 98 +++++++++++++++---- ...ReaderWithDefaultAndStrippedFieldNames.hpp | 64 +++++++++--- tests/json/test_read_into.cpp | 47 +++++++++ 15 files changed, 474 insertions(+), 111 deletions(-) diff --git a/include/rfl/parsing/NamedTupleParser.hpp b/include/rfl/parsing/NamedTupleParser.hpp index 5bd3ebd5e..4ce774340 100644 --- a/include/rfl/parsing/NamedTupleParser.hpp +++ b/include/rfl/parsing/NamedTupleParser.hpp @@ -225,14 +225,32 @@ struct NamedTupleParser { static Result> read_into( const R& _r, const InputVarType& _var, NamedTuple _base) noexcept { - auto view = rfl::to_view(_base); - using ViewType = std::remove_cvref_t; - auto err = Parser::read_view_into(_r, _var, - &view); - if (err) [[unlikely]] { - return error(std::move(*err)); + try { + auto view = rfl::to_view(_base); + using ViewType = std::remove_cvref_t; + auto err = Parser::read_view_into( + _r, _var, &view); + if (err) [[unlikely]] { + return error(std::move(*err)); + } + return make_result_safe>>( + std::move(_base)); + } catch (std::exception& e) { + return error(e.what()); + } + } + + static std::optional read_into_in_place( + const R& _r, const InputVarType& _var, + NamedTuple* _base) noexcept { + try { + auto view = rfl::to_view(*_base); + using ViewType = std::remove_cvref_t; + return Parser::read_view_into(_r, _var, + &view); + } catch (std::exception& e) { + return Error(e.what()); } - return _base; } /** diff --git a/include/rfl/parsing/ParserBox.hpp b/include/rfl/parsing/ParserBox.hpp index aa1bc64d6..268730c7c 100644 --- a/include/rfl/parsing/ParserBox.hpp +++ b/include/rfl/parsing/ParserBox.hpp @@ -79,12 +79,17 @@ struct ParserBox { if constexpr (atomic::is_atomic_v) { return read(_r, _var); } else { - const auto to_box = [](auto&& _t) { - return Box::make(std::forward(_t)); - }; - return read_into_or_read, ProcessorsType>( - _r, _var, std::move(*_base)) - .transform(to_box); + try { + auto res = + read_into_or_read, ProcessorsType>( + _r, _var, std::move(*_base)); + if (!res) { + return error(std::move(res).error()); + } + return Box::make(std::move(*res)); + } catch (std::exception& e) { + return error(e.what()); + } } } diff --git a/include/rfl/parsing/ParserCommented.hpp b/include/rfl/parsing/ParserCommented.hpp index d05dd16ad..cda068635 100644 --- a/include/rfl/parsing/ParserCommented.hpp +++ b/include/rfl/parsing/ParserCommented.hpp @@ -56,13 +56,19 @@ struct ParserCommented { */ static Result> read_into(const R& _r, const InputVarType& _var, Commented _base) noexcept { - auto comment = std::move(_base.comment_); - return read_into_or_read, ProcessorsType>( - _r, _var, std::move(_base.value())) - .transform([&comment](auto&& _t) { - return Commented(std::forward(_t), - std::move(comment)); - }); + try { + auto comment = std::move(_base.comment_); + auto res = + read_into_or_read, ProcessorsType>( + _r, _var, std::move(_base.value())); + if (!res) { + return error(std::move(res).error()); + } + return make_result_safe>>( + Commented(std::move(*res), std::move(comment))); + } catch (std::exception& e) { + return error(e.what()); + } } /** diff --git a/include/rfl/parsing/ParserDefaultVal.hpp b/include/rfl/parsing/ParserDefaultVal.hpp index d067e1c66..879c478d4 100644 --- a/include/rfl/parsing/ParserDefaultVal.hpp +++ b/include/rfl/parsing/ParserDefaultVal.hpp @@ -52,11 +52,18 @@ struct ParserDefaultVal { */ static Result> read_into(const R& _r, const InputVarType& _var, DefaultVal _base) noexcept { - return read_into_or_read, ProcessorsType>( - _r, _var, std::move(_base.value())) - .transform([](auto&& _t) { - return DefaultVal(std::forward(_t)); - }); + try { + auto res = + read_into_or_read, ProcessorsType>( + _r, _var, std::move(_base.value())); + if (!res) { + return error(std::move(res).error()); + } + return make_result_safe>>( + DefaultVal(std::move(*res))); + } catch (std::exception& e) { + return error(e.what()); + } } /** diff --git a/include/rfl/parsing/ParserOptional.hpp b/include/rfl/parsing/ParserOptional.hpp index 78a124ac0..49d95f392 100644 --- a/include/rfl/parsing/ParserOptional.hpp +++ b/include/rfl/parsing/ParserOptional.hpp @@ -81,17 +81,72 @@ struct ParserOptional { if (_r.is_empty(_var)) { return std::optional(); } - const auto to_opt = [](auto&& _t) { - return std::make_optional(std::forward(_t)); - }; - if (_base.has_value()) { - return read_into_or_read, ProcessorsType>( - _r, _var, std::move(*_base)) - .transform(to_opt); + try { + auto res = + _base.has_value() + ? read_into_or_read, + ProcessorsType>(_r, _var, std::move(*_base)) + : Parser, ProcessorsType>::read( + _r, _var); + if (!res) { + return error(std::move(res).error()); + } + return make_result_safe>>( + std::make_optional(std::move(*res))); + } catch (std::exception& e) { + return error(e.what()); + } + } + } + + static std::optional read_into_in_place( + const R& _r, const InputVarType& _var, std::optional* _base) noexcept { + using CleanT = std::remove_cvref_t; + if constexpr (schemaful::IsSchemafulReader) { + auto res = read(_r, _var); + if (!res) { + return std::move(res).error(); + } + try { + *_base = std::move(*res); + return std::nullopt; + } catch (std::exception& e) { + _base->reset(); + return Error(e.what()); + } + } else { + if (_r.is_empty(_var)) { + _base->reset(); + return std::nullopt; + } + try { + if (_base->has_value()) { + if constexpr (requires(CleanT* _p) { + Parser:: + read_into_in_place(_r, _var, _p); + }) { + return Parser::read_into_in_place( + _r, _var, &(**_base)); + } else { + auto res = read_into_or_read( + _r, _var, std::move(**_base)); + if (!res) { + return std::move(res).error(); + } + _base->emplace(std::move(*res)); + return std::nullopt; + } + } + auto res = Parser::read(_r, _var); + if (!res) { + return std::move(res).error(); + } + _base->emplace(std::move(*res)); + return std::nullopt; + } catch (std::exception& e) { + _base->reset(); + return Error(e.what()); } - return Parser, ProcessorsType>::read(_r, - _var) - .transform(to_opt); } } diff --git a/include/rfl/parsing/ParserPositional.hpp b/include/rfl/parsing/ParserPositional.hpp index 6899c856a..ce8c600d3 100644 --- a/include/rfl/parsing/ParserPositional.hpp +++ b/include/rfl/parsing/ParserPositional.hpp @@ -51,12 +51,18 @@ struct ParserPositional { */ static Result> read_into(const R& _r, const InputVarType& _var, Positional _base) noexcept { - const auto to_positional = [](auto&& _t) { - return Positional(std::forward(_t)); - }; - return read_into_or_read, ProcessorsType>( - _r, _var, std::move(_base.value())) - .transform(to_positional); + try { + auto res = + read_into_or_read, ProcessorsType>( + _r, _var, std::move(_base.value())); + if (!res) { + return error(std::move(res).error()); + } + return make_result_safe>>( + Positional(std::move(*res))); + } catch (std::exception& e) { + return error(e.what()); + } } /** diff --git a/include/rfl/parsing/ParserRename.hpp b/include/rfl/parsing/ParserRename.hpp index 7068cc507..da63397b2 100644 --- a/include/rfl/parsing/ParserRename.hpp +++ b/include/rfl/parsing/ParserRename.hpp @@ -56,12 +56,18 @@ struct ParserRename { static Result> read_into(const R& _r, const InputVarType& _var, Rename _base) noexcept { - const auto to_rename = [](auto&& _t) { - return Rename(std::forward(_t)); - }; - return read_into_or_read, ProcessorsType>( - _r, _var, std::move(_base.value())) - .transform(to_rename); + try { + auto res = + read_into_or_read, ProcessorsType>( + _r, _var, std::move(_base.value())); + if (!res) { + return error(std::move(res).error()); + } + return make_result_safe>>( + Rename(std::move(*res))); + } catch (std::exception& e) { + return error(e.what()); + } } /** diff --git a/include/rfl/parsing/ParserShort.hpp b/include/rfl/parsing/ParserShort.hpp index 01db2d726..a8a7dc5fb 100644 --- a/include/rfl/parsing/ParserShort.hpp +++ b/include/rfl/parsing/ParserShort.hpp @@ -59,12 +59,18 @@ struct ParserShort, ProcessorsType> { static Result> read_into(const R& _r, const InputVarType& _var, Short<_name, T> _base) noexcept { - const auto to_short = [](auto&& _t) { - return Short<_name, T>(std::forward(_t)); - }; - return read_into_or_read, ProcessorsType>( - _r, _var, std::move(_base.value())) - .transform(to_short); + try { + auto res = + read_into_or_read, ProcessorsType>( + _r, _var, std::move(_base.value())); + if (!res) { + return error(std::move(res).error()); + } + return make_result_safe>>( + Short<_name, T>(std::move(*res))); + } catch (std::exception& e) { + return error(e.what()); + } } /** diff --git a/include/rfl/parsing/ParserSkip.hpp b/include/rfl/parsing/ParserSkip.hpp index cbb3db97d..edc85084f 100644 --- a/include/rfl/parsing/ParserSkip.hpp +++ b/include/rfl/parsing/ParserSkip.hpp @@ -73,16 +73,22 @@ struct ParserSkip { const R& _r, const InputVarType& _var, internal::Skip _base) noexcept { - if constexpr (_skip_deserialization) { - return _base; - } else { - const auto to_skip = [](auto&& _t) { - return internal::Skip( - std::forward(_t)); - }; - return read_into_or_read, ProcessorsType>( - _r, _var, std::move(_base.value())) - .transform(to_skip); + using SkipType = + internal::Skip; + try { + if constexpr (_skip_deserialization) { + return make_result_safe>(std::move(_base)); + } else { + auto res = + read_into_or_read, ProcessorsType>( + _r, _var, std::move(_base.value())); + if (!res) { + return error(std::move(res).error()); + } + return make_result_safe>(SkipType(std::move(*res))); + } + } catch (std::exception& e) { + return error(e.what()); } } diff --git a/include/rfl/parsing/ParserUniquePtr.hpp b/include/rfl/parsing/ParserUniquePtr.hpp index 12c16cdb8..5615d4454 100644 --- a/include/rfl/parsing/ParserUniquePtr.hpp +++ b/include/rfl/parsing/ParserUniquePtr.hpp @@ -99,17 +99,20 @@ struct ParserUniquePtr { if (_r.is_empty(_var)) { return std::unique_ptr(); } - const auto to_unique = [](auto&& _t) { - return std::make_unique(std::forward(_t)); - }; - if (_base) { - return read_into_or_read, ProcessorsType>( - _r, _var, std::move(*_base)) - .transform(to_unique); + try { + auto res = + _base + ? read_into_or_read, + ProcessorsType>(_r, _var, std::move(*_base)) + : Parser, ProcessorsType>::read( + _r, _var); + if (!res) { + return error(std::move(res).error()); + } + return std::make_unique(std::move(*res)); + } catch (std::exception& e) { + return error(e.what()); } - return Parser, ProcessorsType>::read(_r, - _var) - .transform(to_unique); } } diff --git a/include/rfl/parsing/Parser_base.hpp b/include/rfl/parsing/Parser_base.hpp index 85230c56e..b05f619d2 100644 --- a/include/rfl/parsing/Parser_base.hpp +++ b/include/rfl/parsing/Parser_base.hpp @@ -20,6 +20,23 @@ template requires AreReaderAndWriter struct Parser; +/** + * @brief Constructs a Result without calling the noexcept rvalue constructor + * when moving V may throw (e.g., structs containing const members with + * a throwing copy constructor), so callers inside try/catch can convert + * exceptions into rfl::Error instead of calling std::terminate(). + */ +template +ResultType make_result_safe(U&& _u) { + using V = std::remove_cvref_t; + if constexpr (!std::is_nothrow_move_constructible_v && + std::is_copy_constructible_v) { + return ResultType(static_cast(_u)); + } else { + return ResultType(std::forward(_u)); + } +} + /** * @brief Overlays input into an existing value when the parser supports * `read_into`, otherwise parses a fresh replacement via `read`. diff --git a/include/rfl/parsing/Parser_default.hpp b/include/rfl/parsing/Parser_default.hpp index f3a71bcaa..d71bbb16d 100644 --- a/include/rfl/parsing/Parser_default.hpp +++ b/include/rfl/parsing/Parser_default.hpp @@ -427,9 +427,13 @@ struct Parser { internal::is_deprecated_v || internal::is_attribute_v || internal::is_validator_v) { - return read_into_or_read( - _r, _var, std::move(_base.value())) - .and_then(wrap_in_t); + try { + return read_into_or_read( + _r, _var, std::move(_base.value())) + .and_then(wrap_in_t); + } catch (std::exception& e) { + return error(e.what()); + } } else if constexpr (internal::has_reflection_method_v && std::is_constructible_v< ReflectionType, @@ -451,6 +455,91 @@ struct Parser { } } + static constexpr bool is_in_place_overlayable() { + if constexpr (std::is_array_v || internal::is_basic_type_v || + is_bytestring_v || is_vectorstring_v || + is_string_map_v || is_vector_like_v || + std::is_same_v, Generic> || + is_shared_ptr_v || is_unique_ptr_v || is_box_v || + is_ref_v || is_variant_v || is_rfl_variant_v || + is_tagged_union_v || is_result_v || is_expected_v || + is_duration_v || is_filepath_v || is_span_v || + is_time_point_v || is_reference_wrapper_v || + is_array_v || is_rfl_array_v || is_tuple_v || + is_rfl_tuple_v || is_pair_v || std::is_enum_v || + is_wstring_v || is_string_view_v || + std::is_pointer_v || is_c_array_v || is_atomic_v || + is_atomic_flag_v || internal::has_read_reflector || + (schemaful::IsSchemafulReader && + internal::is_literal_v) || + R::template has_custom_constructor || + internal::has_reflection_type_v) { + return false; + } else if constexpr (is_optional_v) { + return !schemaful::IsSchemafulReader; + } else if constexpr (is_skip_v) { + using U = std::remove_cvref_t; + if constexpr (U::skip_deserialization_) { + return true; + } else { + using Inner = std::remove_cvref_t; + return requires(const R& _r, const InputVarType& _var, Inner* _p) { + Parser::read_into_in_place(_r, _var, _p); + }; + } + } else if constexpr (is_rename_v || is_default_val_v || + is_short_v || is_positional_v || + is_commented_v) { + using Inner = std::remove_cvref_t::Type>; + return requires(const R& _r, const InputVarType& _var, Inner* _p) { + Parser::read_into_in_place(_r, _var, _p); + }; + } else { + return true; + } + } + + /** + * @brief Overlays input directly into an existing non-const instance in + * place (plain structs, std::optional, and value-preserving wrappers) + * to avoid unnecessary copies and move_to reconstruction. + */ + static std::optional read_into_in_place(const R& _r, + const InputVarType& _var, + T* _base) noexcept + requires(is_in_place_overlayable()) + { + if constexpr (is_optional_v) { + return ParserOptional::value_type, + ProcessorsType>::read_into_in_place(_r, _var, + _base); + } else if constexpr (is_skip_v) { + using U = std::remove_cvref_t; + if constexpr (U::skip_deserialization_) { + return std::nullopt; + } else { + using Inner = std::remove_cvref_t; + return Parser::read_into_in_place( + _r, _var, &_base->value()); + } + } else if constexpr (is_rename_v || is_default_val_v || + is_short_v || is_positional_v || + is_commented_v) { + using Inner = std::remove_cvref_t::Type>; + return Parser::read_into_in_place( + _r, _var, &_base->value()); + } else { + try { + auto view = ProcessorsType::template process(to_view(*_base)); + using ViewType = std::remove_cvref_t; + return Parser::read_view_into(_r, _var, + &view); + } catch (std::exception& e) { + return Error(e.what()); + } + } + } + /** * @brief Writes a value to the output. * diff --git a/include/rfl/parsing/ViewReaderWithDefault.hpp b/include/rfl/parsing/ViewReaderWithDefault.hpp index 8ba1beb0b..4d2302440 100644 --- a/include/rfl/parsing/ViewReaderWithDefault.hpp +++ b/include/rfl/parsing/ViewReaderWithDefault.hpp @@ -115,14 +115,32 @@ class ViewReaderWithDefault { } move_to(rfl::get(*_view), &(*res)); } else { - auto res = read_into_or_read( - _r, _var, std::move(*rfl::get(*_view))); - if (!res) { - _errors->emplace_back( - wrap_field_error(name, std::move(res).error())); - return; + if constexpr (requires { + Parser::read_into_in_place( + _r, _var, rfl::get(*_view)); + }) { + auto err = Parser::read_into_in_place( + _r, _var, rfl::get(*_view)); + if (err) { + _errors->emplace_back(wrap_field_error(name, std::move(*err))); + return; + } + } else { + auto res = [&]() -> Result { + try { + return read_into_or_read( + _r, _var, std::move(*rfl::get(*_view))); + } catch (std::exception& e) { + return error(e.what()); + } + }(); + if (!res) { + _errors->emplace_back( + wrap_field_error(name, std::move(res).error())); + return; + } + move_to(rfl::get(*_view), &(*res)); } - move_to(rfl::get(*_view), &(*res)); } } else { if constexpr (std::is_const_v) { @@ -144,14 +162,32 @@ class ViewReaderWithDefault { } move_to(&rfl::get(*_view), &(*res)); } else { - auto res = read_into_or_read( - _r, _var, std::move(rfl::get(*_view))); - if (!res) { - _errors->emplace_back( - wrap_field_error(name, std::move(res).error())); - return; + if constexpr (requires { + Parser::read_into_in_place( + _r, _var, &rfl::get(*_view)); + }) { + auto err = Parser::read_into_in_place( + _r, _var, &rfl::get(*_view)); + if (err) { + _errors->emplace_back(wrap_field_error(name, std::move(*err))); + return; + } + } else { + auto res = [&]() -> Result { + try { + return read_into_or_read( + _r, _var, std::move(rfl::get(*_view))); + } catch (std::exception& e) { + return error(e.what()); + } + }(); + if (!res) { + _errors->emplace_back( + wrap_field_error(name, std::move(res).error())); + return; + } + move_to(&rfl::get(*_view), &(*res)); } - move_to(&rfl::get(*_view), &(*res)); } } } else { @@ -182,15 +218,35 @@ class ViewReaderWithDefault { if constexpr (_overlay) { for (auto& [k, v] : *extra_fields) { if (k == _current_name) { - auto res = read_into_or_read(_r, _var, - std::move(v)); - if (!res) { - _errors->emplace_back( - wrap_field_error(_current_name, std::move(res).error())); + if constexpr (requires { + Parser::read_into_in_place( + _r, _var, &v); + }) { + auto err = Parser::read_into_in_place( + _r, _var, &v); + if (err) { + _errors->emplace_back( + wrap_field_error(_current_name, std::move(*err))); + return; + } + return; + } else { + auto res = [&]() -> Result { + try { + return read_into_or_read(_r, _var, + std::move(v)); + } catch (std::exception& e) { + return error(e.what()); + } + }(); + if (!res) { + _errors->emplace_back( + wrap_field_error(_current_name, std::move(res).error())); + return; + } + move_to(&v, &(*res)); return; } - v = std::move(*res); - return; } } } diff --git a/include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp b/include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp index be33752d2..56be1647d 100644 --- a/include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp +++ b/include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp @@ -118,14 +118,32 @@ class ViewReaderWithDefaultAndStrippedFieldNames { } move_to(rfl::get(*_view), &(*res)); } else { - auto res = read_into_or_read( - _r, _var, std::move(*rfl::get(*_view))); - if (!res) { - _errors->emplace_back( - wrap_field_error(name, std::move(res).error())); - return; + if constexpr (requires { + Parser::read_into_in_place( + _r, _var, rfl::get(*_view)); + }) { + auto err = Parser::read_into_in_place( + _r, _var, rfl::get(*_view)); + if (err) { + _errors->emplace_back(wrap_field_error(name, std::move(*err))); + return; + } + } else { + auto res = [&]() -> Result { + try { + return read_into_or_read( + _r, _var, std::move(*rfl::get(*_view))); + } catch (std::exception& e) { + return error(e.what()); + } + }(); + if (!res) { + _errors->emplace_back( + wrap_field_error(name, std::move(res).error())); + return; + } + move_to(rfl::get(*_view), &(*res)); } - move_to(rfl::get(*_view), &(*res)); } } else { if constexpr (std::is_const_v) { @@ -147,14 +165,32 @@ class ViewReaderWithDefaultAndStrippedFieldNames { } move_to(&rfl::get(*_view), &(*res)); } else { - auto res = read_into_or_read( - _r, _var, std::move(rfl::get(*_view))); - if (!res) { - _errors->emplace_back( - wrap_field_error(name, std::move(res).error())); - return; + if constexpr (requires { + Parser::read_into_in_place( + _r, _var, &rfl::get(*_view)); + }) { + auto err = Parser::read_into_in_place( + _r, _var, &rfl::get(*_view)); + if (err) { + _errors->emplace_back(wrap_field_error(name, std::move(*err))); + return; + } + } else { + auto res = [&]() -> Result { + try { + return read_into_or_read( + _r, _var, std::move(rfl::get(*_view))); + } catch (std::exception& e) { + return error(e.what()); + } + }(); + if (!res) { + _errors->emplace_back( + wrap_field_error(name, std::move(res).error())); + return; + } + move_to(&rfl::get(*_view), &(*res)); } - move_to(&rfl::get(*_view), &(*res)); } } } else { diff --git a/tests/json/test_read_into.cpp b/tests/json/test_read_into.cpp index 6c35b90cd..d3ee1a52a 100644 --- a/tests/json/test_read_into.cpp +++ b/tests/json/test_read_into.cpp @@ -694,4 +694,51 @@ TEST(json, read_into_top_level_and_nested_const_fields) { EXPECT_TRUE(caught_as_result_error); } +struct OuterWithThrowingInner { + WithThrowingConstField inner; +}; + +struct OuterWithOptionalThrowingInner { + std::optional inner; +}; + +TEST(json, read_into_nested_and_optional_throwing_const_fields) { + // Non-const nested struct containing a throwing const field must convert + // copy exceptions into Result::error rather than calling std::terminate(). + bool nested_caught_as_error = false; + for (int budget = 0; budget <= 12; ++budget) { + try { + const auto res = rfl::json::read_into( + OuterWithThrowingInner{ + .inner = WithThrowingConstField{ + .payload = ThrowingCopyPayload(5, true, budget)}}, + R"({"inner":{"payload":{"value":9}}})"); + if (!res.has_value()) { + nested_caught_as_error = true; + } + } catch (const std::runtime_error&) { + // Thrown in non-noexcept caller parameter copy before entering parser. + } + } + EXPECT_TRUE(nested_caught_as_error); + + // std::optional must also never std::terminate(). + bool opt_caught_as_error = false; + for (int budget = 0; budget <= 12; ++budget) { + try { + const auto res = rfl::json::read_into( + OuterWithOptionalThrowingInner{ + .inner = WithThrowingConstField{ + .payload = ThrowingCopyPayload(5, true, budget)}}, + R"({"inner":{"payload":{"value":9}}})"); + if (!res.has_value()) { + opt_caught_as_error = true; + } + } catch (const std::runtime_error&) { + // Thrown in non-noexcept caller parameter copy before entering parser. + } + } + EXPECT_TRUE(opt_caught_as_error); +} + } // namespace test_read_into From d440e688bc2e185994a3a64c4f7b89b6c808910e Mon Sep 17 00:00:00 2001 From: clockblocker Date: Fri, 27 Nov 2026 14:47:50 +0100 Subject: [PATCH 4/5] Exclude rfl::ExtraFields from Parser::is_in_place_overlayable --- include/rfl/parsing/Parser_default.hpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/include/rfl/parsing/Parser_default.hpp b/include/rfl/parsing/Parser_default.hpp index d71bbb16d..bf6eaf490 100644 --- a/include/rfl/parsing/Parser_default.hpp +++ b/include/rfl/parsing/Parser_default.hpp @@ -21,6 +21,7 @@ #include "../internal/is_basic_type.hpp" #include "../internal/is_deprecated.hpp" #include "../internal/is_description.hpp" +#include "../internal/is_extra_fields.hpp" #include "../internal/is_literal.hpp" #include "../internal/is_validator.hpp" #include "../internal/processed_t.hpp" @@ -460,6 +461,7 @@ struct Parser { is_bytestring_v || is_vectorstring_v || is_string_map_v || is_vector_like_v || std::is_same_v, Generic> || + internal::is_extra_fields_v || is_shared_ptr_v || is_unique_ptr_v || is_box_v || is_ref_v || is_variant_v || is_rfl_variant_v || is_tagged_union_v || is_result_v || is_expected_v || From 1a43bb94bb48932b98392881a5df0b9637647d2a Mon Sep 17 00:00:00 2001 From: clockblocker Date: Fri, 27 Nov 2026 14:55:47 +0100 Subject: [PATCH 5/5] Guard const-wrapped in-place overlays, safe wrapper reconstruction, and remaining noexcept throw boundaries --- include/rfl/parsing/ParserBox.hpp | 1 + include/rfl/parsing/ParserCommented.hpp | 1 + include/rfl/parsing/ParserDefaultVal.hpp | 1 + include/rfl/parsing/ParserOptional.hpp | 1 + include/rfl/parsing/ParserPositional.hpp | 1 + include/rfl/parsing/ParserRef.hpp | 13 ++++- include/rfl/parsing/ParserRename.hpp | 1 + include/rfl/parsing/ParserSharedPtr.hpp | 13 ++++- include/rfl/parsing/ParserShort.hpp | 1 + include/rfl/parsing/ParserUniquePtr.hpp | 1 + include/rfl/parsing/Parser_base.hpp | 38 +++++++++++-- include/rfl/parsing/Parser_default.hpp | 57 +++++++++++++++---- include/rfl/parsing/ViewReaderWithDefault.hpp | 3 +- ...ReaderWithDefaultAndStrippedFieldNames.hpp | 3 +- tests/json/test_read_into.cpp | 50 ++++++++++++++++ 15 files changed, 160 insertions(+), 25 deletions(-) diff --git a/include/rfl/parsing/ParserBox.hpp b/include/rfl/parsing/ParserBox.hpp index 268730c7c..a3b486e6a 100644 --- a/include/rfl/parsing/ParserBox.hpp +++ b/include/rfl/parsing/ParserBox.hpp @@ -1,6 +1,7 @@ #ifndef RFL_PARSING_PARSER_BOX_HPP_ #define RFL_PARSING_PARSER_BOX_HPP_ +#include #include #include diff --git a/include/rfl/parsing/ParserCommented.hpp b/include/rfl/parsing/ParserCommented.hpp index cda068635..b699b7d83 100644 --- a/include/rfl/parsing/ParserCommented.hpp +++ b/include/rfl/parsing/ParserCommented.hpp @@ -1,6 +1,7 @@ #ifndef RFL_PARSING_PARSER_COMMENTED_HPP_ #define RFL_PARSING_PARSER_COMMENTED_HPP_ +#include #include #include diff --git a/include/rfl/parsing/ParserDefaultVal.hpp b/include/rfl/parsing/ParserDefaultVal.hpp index 879c478d4..69602eb4b 100644 --- a/include/rfl/parsing/ParserDefaultVal.hpp +++ b/include/rfl/parsing/ParserDefaultVal.hpp @@ -1,6 +1,7 @@ #ifndef RFL_PARSING_PARSER_DEFAULTVAL_HPP_ #define RFL_PARSING_PARSER_DEFAULTVAL_HPP_ +#include #include #include diff --git a/include/rfl/parsing/ParserOptional.hpp b/include/rfl/parsing/ParserOptional.hpp index 49d95f392..6f230a193 100644 --- a/include/rfl/parsing/ParserOptional.hpp +++ b/include/rfl/parsing/ParserOptional.hpp @@ -1,6 +1,7 @@ #ifndef RFL_PARSING_PARSER_OPTIONAL_HPP_ #define RFL_PARSING_PARSER_OPTIONAL_HPP_ +#include #include #include #include diff --git a/include/rfl/parsing/ParserPositional.hpp b/include/rfl/parsing/ParserPositional.hpp index ce8c600d3..ead7fbc2f 100644 --- a/include/rfl/parsing/ParserPositional.hpp +++ b/include/rfl/parsing/ParserPositional.hpp @@ -1,6 +1,7 @@ #ifndef RFL_PARSING_PARSER_POSITIONAL_HPP_ #define RFL_PARSING_PARSER_POSITIONAL_HPP_ +#include #include #include diff --git a/include/rfl/parsing/ParserRef.hpp b/include/rfl/parsing/ParserRef.hpp index f4a5dbdcc..b5dee35e7 100644 --- a/include/rfl/parsing/ParserRef.hpp +++ b/include/rfl/parsing/ParserRef.hpp @@ -93,9 +93,16 @@ struct ParserRef { return error(e.what()); } } else { - return Parser, ProcessorsType>::read(_r, - _var) - .transform(to_ref); + try { + auto res = Parser, ProcessorsType>::read( + _r, _var); + if (!res) { + return error(std::move(res).error()); + } + return Ref::make(std::move(*res)); + } catch (std::exception& e) { + return error(e.what()); + } } } } diff --git a/include/rfl/parsing/ParserRename.hpp b/include/rfl/parsing/ParserRename.hpp index da63397b2..b77dcc72b 100644 --- a/include/rfl/parsing/ParserRename.hpp +++ b/include/rfl/parsing/ParserRename.hpp @@ -1,6 +1,7 @@ #ifndef RFL_PARSING_PARSER_RENAME_HPP_ #define RFL_PARSING_PARSER_RENAME_HPP_ +#include #include #include diff --git a/include/rfl/parsing/ParserSharedPtr.hpp b/include/rfl/parsing/ParserSharedPtr.hpp index 8e91d6101..72bc1872e 100644 --- a/include/rfl/parsing/ParserSharedPtr.hpp +++ b/include/rfl/parsing/ParserSharedPtr.hpp @@ -116,9 +116,16 @@ struct ParserSharedPtr { } } } - return Parser, ProcessorsType>::read(_r, - _var) - .transform(to_shared); + try { + auto res = Parser, ProcessorsType>::read( + _r, _var); + if (!res) { + return error(std::move(res).error()); + } + return std::make_shared(std::move(*res)); + } catch (std::exception& e) { + return error(e.what()); + } } } diff --git a/include/rfl/parsing/ParserShort.hpp b/include/rfl/parsing/ParserShort.hpp index a8a7dc5fb..9b9937d1b 100644 --- a/include/rfl/parsing/ParserShort.hpp +++ b/include/rfl/parsing/ParserShort.hpp @@ -1,6 +1,7 @@ #ifndef RFL_PARSING_PARSER_SHORT_HPP_ #define RFL_PARSING_PARSER_SHORT_HPP_ +#include #include #include diff --git a/include/rfl/parsing/ParserUniquePtr.hpp b/include/rfl/parsing/ParserUniquePtr.hpp index 5615d4454..bf7f29ca3 100644 --- a/include/rfl/parsing/ParserUniquePtr.hpp +++ b/include/rfl/parsing/ParserUniquePtr.hpp @@ -1,6 +1,7 @@ #ifndef RFL_PARSING_PARSER_UNIQUE_PTR_HPP_ #define RFL_PARSING_PARSER_UNIQUE_PTR_HPP_ +#include #include #include #include diff --git a/include/rfl/parsing/Parser_base.hpp b/include/rfl/parsing/Parser_base.hpp index b05f619d2..87d978a6f 100644 --- a/include/rfl/parsing/Parser_base.hpp +++ b/include/rfl/parsing/Parser_base.hpp @@ -37,20 +37,48 @@ ResultType make_result_safe(U&& _u) { } } +/** + * @brief Checks whether replacing an existing live object of type U requires + * in-place destroy + placement-move rather than assignment. Unwraps + * wrapper types that expose `::Type` before testing + * `std::is_move_assignable_v`, avoiding hard errors in unconstrained + * template `operator=` overloads on wrappers like Rename / Description. + */ +template +consteval bool needs_in_place_reconstruct() { + if constexpr (std::is_const_v) { + return true; + } else if constexpr (requires { typename std::remove_cvref_t::Type; }) { + using Inner = typename std::remove_cvref_t::Type; + if constexpr (!std::is_same_v, + std::remove_cvref_t>) { + if constexpr (needs_in_place_reconstruct()) { + return true; + } else { + return !std::is_move_assignable_v; + } + } else { + return !std::is_move_assignable_v; + } + } else { + return !std::is_move_assignable_v; + } +} + /** * @brief Overlays input into an existing value when the parser supports * `read_into`, otherwise parses a fresh replacement via `read`. */ -template +template auto read_into_or_read(const R& _r, const typename R::InputVarType& _var, - T&& _base) { + Base&& _base) { using U = std::remove_cvref_t; if constexpr (requires { Parser::read_into( - _r, _var, std::forward(_base)); + _r, _var, U(std::forward(_base))); }) { - return Parser::read_into(_r, _var, - std::forward(_base)); + return Parser::read_into( + _r, _var, U(std::forward(_base))); } else { return Parser::read(_r, _var); } diff --git a/include/rfl/parsing/Parser_default.hpp b/include/rfl/parsing/Parser_default.hpp index bf6eaf490..d0ff4b2bf 100644 --- a/include/rfl/parsing/Parser_default.hpp +++ b/include/rfl/parsing/Parser_default.hpp @@ -3,6 +3,7 @@ #include #include +#include #include #include @@ -382,7 +383,12 @@ struct Parser { const auto wrap_in_t = [](auto&& _named_tuple) -> Result { try { using NT = decltype(_named_tuple); - return Reflector::to(std::forward(_named_tuple)); + auto res = Reflector::to(std::forward(_named_tuple)); + if constexpr (is_result_v) { + return res; + } else { + return make_result_safe>(std::move(res)); + } } catch (std::exception& e) { return error(e.what()); } @@ -414,11 +420,17 @@ struct Parser { try { using NT = decltype(_named_tuple); if constexpr (internal::HasFromReflectionMethod) { - return T::from_reflection(std::forward(_named_tuple)); + auto res = T::from_reflection(std::forward(_named_tuple)); + if constexpr (is_result_v) { + return res; + } else { + return make_result_safe>(std::move(res)); + } } else if constexpr (internal::is_validator_v) { return T::from_value(std::forward(_named_tuple)); } else { - return T{std::forward(_named_tuple)}; + return make_result_safe>( + T{std::forward(_named_tuple)}); } } catch (std::exception& e) { return error(e.what()); @@ -474,15 +486,33 @@ struct Parser { is_atomic_flag_v || internal::has_read_reflector || (schemaful::IsSchemafulReader && internal::is_literal_v) || - R::template has_custom_constructor || - internal::has_reflection_type_v) { + R::template has_custom_constructor) { return false; + } else if constexpr (internal::has_reflection_type_v) { + if constexpr (internal::is_description_v || + internal::is_deprecated_v || + internal::is_attribute_v) { + using RawInner = typename std::remove_cvref_t::Type; + if constexpr (std::is_const_v) { + return false; + } else { + using Inner = std::remove_cvref_t; + return requires(const R& _r, const InputVarType& _var, Inner* _p) { + Parser::read_into_in_place(_r, _var, + _p); + }; + } + } else { + return false; + } } else if constexpr (is_optional_v) { return !schemaful::IsSchemafulReader; } else if constexpr (is_skip_v) { using U = std::remove_cvref_t; if constexpr (U::skip_deserialization_) { return true; + } else if constexpr (std::is_const_v) { + return false; } else { using Inner = std::remove_cvref_t; return requires(const R& _r, const InputVarType& _var, Inner* _p) { @@ -492,10 +522,15 @@ struct Parser { } else if constexpr (is_rename_v || is_default_val_v || is_short_v || is_positional_v || is_commented_v) { - using Inner = std::remove_cvref_t::Type>; - return requires(const R& _r, const InputVarType& _var, Inner* _p) { - Parser::read_into_in_place(_r, _var, _p); - }; + using RawInner = typename std::remove_cvref_t::Type; + if constexpr (std::is_const_v) { + return false; + } else { + using Inner = std::remove_cvref_t; + return requires(const R& _r, const InputVarType& _var, Inner* _p) { + Parser::read_into_in_place(_r, _var, _p); + }; + } } else { return true; } @@ -526,7 +561,9 @@ struct Parser { } } else if constexpr (is_rename_v || is_default_val_v || is_short_v || is_positional_v || - is_commented_v) { + is_commented_v || internal::is_description_v || + internal::is_deprecated_v || + internal::is_attribute_v) { using Inner = std::remove_cvref_t::Type>; return Parser::read_into_in_place( _r, _var, &_base->value()); diff --git a/include/rfl/parsing/ViewReaderWithDefault.hpp b/include/rfl/parsing/ViewReaderWithDefault.hpp index 4d2302440..be8524316 100644 --- a/include/rfl/parsing/ViewReaderWithDefault.hpp +++ b/include/rfl/parsing/ViewReaderWithDefault.hpp @@ -292,8 +292,7 @@ class ViewReaderWithDefault { static void move_to(Target* _t, Source* _s) { if constexpr (!rfl::internal::is_array_v && !std::is_array_v) { - if constexpr (std::is_const_v || - !std::is_move_assignable_v) { + if constexpr (needs_in_place_reconstruct()) { // The struct was default-constructed (or overlaid), so *_t is a live // const / non-move-assignable object (e.g. a nested struct with a // const member) and must not be assigned to. Re-create it in place diff --git a/include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp b/include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp index 56be1647d..2ff0d6d54 100644 --- a/include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp +++ b/include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp @@ -227,8 +227,7 @@ class ViewReaderWithDefaultAndStrippedFieldNames { static void move_to(Target* _t, Source* _s) { if constexpr (!rfl::internal::is_array_v && !std::is_array_v) { - if constexpr (std::is_const_v || - !std::is_move_assignable_v) { + if constexpr (needs_in_place_reconstruct()) { // The struct was default-constructed (or overlaid), so *_t is a live // const / non-move-assignable object (e.g. a nested struct with a // const member) and must not be assigned to. Re-create it in place diff --git a/tests/json/test_read_into.cpp b/tests/json/test_read_into.cpp index d3ee1a52a..7a1110f91 100644 --- a/tests/json/test_read_into.cpp +++ b/tests/json/test_read_into.cpp @@ -741,4 +741,54 @@ TEST(json, read_into_nested_and_optional_throwing_const_fields) { EXPECT_TRUE(opt_caught_as_error); } +struct OuterWithConstWrappedStruct { + rfl::Rename<"cfg", const InnerWithConst> cfg; + rfl::Description<"desc", InnerWithConst> described; +}; + +struct ThrowingConstReflWrapper { + using ReflectionType = WithThrowingConstField; + const ThrowingCopyPayload payload; + + ThrowingConstReflWrapper(const ThrowingConstReflWrapper&) = default; + explicit ThrowingConstReflWrapper(const WithThrowingConstField& _r) + : payload(_r.payload) {} + + WithThrowingConstField reflection() const { + return WithThrowingConstField{.payload = payload}; + } +}; + +TEST(json, read_into_wrapper_over_const_struct_and_refl_throw_safety) { + const OuterWithConstWrappedStruct base{ + .cfg = InnerWithConst{.id = 10, .port = 8080}, + .described = InnerWithConst{.id = 20, .port = 7070}, + }; + const auto merged = rfl::json::read_into( + base, R"({"cfg":{"port":9090},"described":{"port":6060}})"); + ASSERT_TRUE(merged.has_value()) << merged.error().what(); + EXPECT_EQ(merged->cfg.value().id, 10); + EXPECT_EQ(merged->cfg.value().port, 9090); + EXPECT_EQ(merged->described.value().id, 20); + EXPECT_EQ(merged->described.value().port, 6060); + + // ReflectionType wrapper whose move ctor is non-noexcept (copies const + // ThrowingCopyPayload) must convert exceptions in wrap_in_t into Error + // rather than calling std::terminate(). + bool refl_caught = false; + for (int budget = 0; budget <= 12; ++budget) { + try { + const auto res = rfl::json::read_into( + ThrowingConstReflWrapper(WithThrowingConstField{ + .payload = ThrowingCopyPayload(7, true, budget)}), + R"({"payload":{"value":99}})"); + if (!res.has_value()) { + refl_caught = true; + } + } catch (const std::runtime_error&) { + } + } + EXPECT_TRUE(refl_caught); +} + } // namespace test_read_into