Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 14 additions & 0 deletions docs/content/generic.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,3 +143,17 @@ bart["age"] = 10;
const auto person = rfl::from_generic<Person>(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 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<rfl::NoExtraFields>(base, patch)`). Errors leave an lvalue base untouched.

18 changes: 18 additions & 0 deletions docs/content/supported_formats/json.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,24 @@ 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<T>` when engaged) are overlaid recursively; an explicit `null` clears `std::optional<T>` to `std::nullopt`.
- 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<rfl::NoExtraFields>(base, json_str)`).
- Atomic on error: `_base` is taken by value and returned inside `rfl::Result<T>`, 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

One of the great things about C++ is that it gives you control over
Expand Down
13 changes: 13 additions & 0 deletions docs/content/supported_formats/toml.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>` 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
Expand Down
13 changes: 13 additions & 0 deletions docs/content/supported_formats/yaml.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 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<T>`, 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

One of the great things about C++ is that it gives you control over
Expand Down
10 changes: 10 additions & 0 deletions include/rfl/from_generic.hpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
#ifndef RFL_FROM_GENERIC_HPP_
#define RFL_FROM_GENERIC_HPP_

#include <utility>

#include "Generic.hpp"
#include "Result.hpp"
#include "generic/read.hpp"

namespace rfl {
Expand All @@ -12,6 +15,13 @@ auto from_generic(const Generic& _g) {
return rfl::generic::read<T, Ps...>(_g);
}

/// Overlays a Generic value onto an existing base object, preserving missing
/// fields and recursively overlaying nested structs. Atomic on error.
template <class... Ps, class T>
Result<T> from_generic_into(T _base, const Generic& _g) {
return rfl::generic::read_into<Ps...>(std::move(_base), _g);
}

} // namespace rfl

#endif
19 changes: 19 additions & 0 deletions include/rfl/generic/read.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@
#define GENERIC_READ_HPP_


#include <utility>

#include "../Generic.hpp"
#include "../Processors.hpp"
#include "../Result.hpp"
#include "../parsing/Parser_base.hpp"
#include "Parser.hpp"

namespace rfl {
Expand All @@ -22,6 +26,21 @@ auto read(const Generic& _g) {
return Parser<T, Processors<Ps...>>::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 <class... Ps, class T>
Result<T> read_into(T _base, const Generic& _g) {
const auto r = Reader();
return parsing::read_into_or_read<Reader, Writer, T, Processors<Ps...>>(
r, _g, std::move(_base));
}

} // namespace generic
} // namespace rfl

Expand Down
20 changes: 20 additions & 0 deletions include/rfl/json/load.hpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
#ifndef RFL_JSON_LOAD_HPP_
#define RFL_JSON_LOAD_HPP_

#include <utility>

#include "../Result.hpp"
#include "../io/load_string.hpp"
#include "read.hpp"
Expand All @@ -23,6 +25,24 @@ Result<T> 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 <class... Ps, class T>
Result<T> 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<Ps...>(std::move(_base), *str, _flag);
}

} // namespace json
} // namespace rfl

Expand Down
61 changes: 61 additions & 0 deletions include/rfl/json/read.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@

#include <istream>
#include <string_view>
#include <utility>

#include "../Processors.hpp"
#include "../internal/wrap_in_rfl_array_t.hpp"
#include "../parsing/Parser_base.hpp"
#include "Parser.hpp"
#include "Reader.hpp"

Expand Down Expand Up @@ -75,6 +77,65 @@ auto read(std::istream& _stream, const yyjson_read_flag _flag = 0) {
return read<T, Ps...>(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 <class... Ps, class T>
Result<T> read_into(T _base, const InputVarType& _obj) {
const auto r = Reader();
return parsing::read_into_or_read<Reader, Writer, T, Processors<Ps...>>(
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 <class... Ps, class T>
Result<T> 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<char*>(_json_str.data()),
_json_str.size(), _flag, NULL, &err);
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();
return parsing::read_into_or_read<Reader, Writer, T, Processors<Ps...>>(
r, InputVarType(root), std::move(_base));
}

/// 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 <class... Ps, class T>
Result<T> read_into(T _base, std::istream& _stream,
const yyjson_read_flag _flag = 0) {
const auto json_str = std::string(std::istreambuf_iterator<char>(_stream),
std::istreambuf_iterator<char>());
return read_into<Ps...>(std::move(_base), json_str, _flag);
}

} // namespace json
} // namespace rfl

Expand Down
99 changes: 99 additions & 0 deletions include/rfl/parsing/NamedTupleParser.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,12 @@ struct NamedTupleParser {
ProcessorsType>,
ViewReaderWithDefault<R, W, NamedTupleType, ProcessorsType>>;

using ViewReaderOverlayType = std::conditional_t<
_no_field_names,
ViewReaderWithDefaultAndStrippedFieldNames<R, W, NamedTupleType,
ProcessorsType, true>,
ViewReaderWithDefault<R, W, NamedTupleType, ProcessorsType, true>>;

using InputObjectOrArrayType =
std::conditional_t<_no_field_names, typename R::InputArrayType,
typename R::InputObjectType>;
Expand Down Expand Up @@ -207,6 +213,73 @@ 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<NamedTuple<FieldTypes...>> read_into(
const R& _r, const InputVarType& _var,
NamedTuple<FieldTypes...> _base) noexcept {
try {
auto view = rfl::to_view(_base);
using ViewType = std::remove_cvref_t<decltype(view)>;
auto err = Parser<R, W, ViewType, ProcessorsType>::read_view_into(
_r, _var, &view);
if (err) [[unlikely]] {
return error(std::move(*err));
}
return make_result_safe<Result<NamedTuple<FieldTypes...>>>(
std::move(_base));
} catch (std::exception& e) {
return error(e.what());
}
}

static std::optional<Error> read_into_in_place(
const R& _r, const InputVarType& _var,
NamedTuple<FieldTypes...>* _base) noexcept {
try {
auto view = rfl::to_view(*_base);
using ViewType = std::remove_cvref_t<decltype(view)>;
return Parser<R, W, ViewType, ProcessorsType>::read_view_into(_r, _var,
&view);
} catch (std::exception& e) {
return Error(e.what());
}
}

/**
* @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<Error> read_view_into(
const R& _r, const InputVarType& _var,
NamedTuple<FieldTypes...>* _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.
*
Expand Down Expand Up @@ -531,6 +604,32 @@ struct NamedTupleParser {
return std::nullopt;
}
}

static std::optional<Error> read_object_or_array_into(
const R& _r, const InputObjectOrArrayType& _obj_or_arr,
NamedTupleType* _view) noexcept {
FieldErrors<ProcessorsType> 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<ProcessorsType>) {
return std::move(errors).error();
} else {
if (errors.size() != 0) [[unlikely]] {
return to_single_error(std::move(errors));
}
return std::nullopt;
}
}
};

} // namespace rfl::parsing
Expand Down
Loading
Loading