From 54c2a84650b787cb5d710ceab7e5fefb3ae94f9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dr=2E=20Patrick=20Urbanke=20=28=E5=8A=89=E8=87=AA=E6=88=90?= =?UTF-8?q?=29?= Date: Sun, 15 Sep 2024 19:38:33 +0200 Subject: [PATCH] Add rfl::DefaultIfMissing; fixes #163, #167, #185 (#189) --- docs/optional_fields.md | 2 + docs/processors.md | 43 +++++- include/rfl.hpp | 1 + include/rfl/DefaultIfMissing.hpp | 19 +++ include/rfl/Processors.hpp | 6 + .../rfl/internal/is_default_if_missing_v.hpp | 29 ++++ include/rfl/parsing/NamedTupleParser.hpp | 49 ++++++- include/rfl/parsing/Parser_default.hpp | 24 ++- include/rfl/parsing/ViewReaderWithDefault.hpp | 137 ++++++++++++++++++ ...ReaderWithDefaultAndStrippedFieldNames.hpp | 111 ++++++++++++++ tests/json/test_default_if_missing.cpp | 26 ++++ ...test_default_if_missing_no_field_names.cpp | 27 ++++ 12 files changed, 471 insertions(+), 3 deletions(-) create mode 100644 include/rfl/DefaultIfMissing.hpp create mode 100644 include/rfl/internal/is_default_if_missing_v.hpp create mode 100644 include/rfl/parsing/ViewReaderWithDefault.hpp create mode 100644 include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp create mode 100644 tests/json/test_default_if_missing.cpp create mode 100644 tests/json/test_default_if_missing_no_field_names.cpp diff --git a/docs/optional_fields.md b/docs/optional_fields.md index fcad5e8f..d298b578 100644 --- a/docs/optional_fields.md +++ b/docs/optional_fields.md @@ -44,3 +44,5 @@ Now, the field "children" is missing for Bart, Lisa and Maggie: ```json {"firstName":"Homer","lastName":"Simpson","children":[{"firstName":"Bart","lastName":"Simpson"},{"firstName":"Lisa","lastName":"Simpson"},{"firstName":"Maggie","lastName":"Simpson"}]} ``` + +**NOTE**: If you want to explicitly set default values for your fields and/or you want all fields to be optional, please consider using the `rfl::DefaultIfMissing` processor. You will find more information in the section on processors in this documentation. diff --git a/docs/processors.md b/docs/processors.md index 8d721db7..7df6cee1 100644 --- a/docs/processors.md +++ b/docs/processors.md @@ -34,6 +34,7 @@ The resulting JSON string looks like this: reflect-cpp currently supports the following processors: - `rfl::AddStructName` +- `rfl::DefaultIfMissing` - `rfl::NoFieldNames` - `rfl::NoOptionals` - `rfl::UnderlyingEnums` @@ -42,7 +43,7 @@ reflect-cpp currently supports the following processors: ### `rfl::AddStructName` -It is also possible to add the struct name as an addtional field, like this: +It is also possible to add the struct name as an additional field, like this: ```cpp const auto json_string = @@ -58,6 +59,46 @@ The resulting JSON string looks like this: {"type":"Person","first_name":"Homer","last_name":"Simpson","age":45} ``` +### `rfl::DefaultIfMissing` + +The `rfl::DefaultIfMissing` processor is only relevant for reading data. For writing data, it will make no difference. + +Usually, when fields are missing in the input data, this will lead to an error +(unless they are optional fields). +But if you pass the `rfl::DefaultIfMissing` processor, then missing fields will be +replaced by their default value. + +For instance, consider the following struct: + +```cpp +struct Person { + std::string first_name; + std::string last_name = "Simpson"; + std::string town; +}; +``` + +Suppose you are reading a JSON like this: + +```json +{"first_name":"Homer"} +``` + +```cpp +rfl::json::read(json_string); +``` + +Then the resulting struct will be equivalent to what you would +have gotten had you read the following JSON string: + +```json +{"first_name":"Homer","last_name":"Simpson","town":""} +``` + +`last_name` and `town` have been replaced by the default values. +Because you have not passed a default value to town, the default value +of the type is used instead. + ### `rfl::NoFieldNames` We can also remove the field names altogether: diff --git a/include/rfl.hpp b/include/rfl.hpp index 087d52a4..06b4d571 100644 --- a/include/rfl.hpp +++ b/include/rfl.hpp @@ -14,6 +14,7 @@ #include "rfl/Binary.hpp" #include "rfl/Box.hpp" #include "rfl/Bytestring.hpp" +#include "rfl/DefaultIfMissing.hpp" #include "rfl/Description.hpp" #include "rfl/ExtraFields.hpp" #include "rfl/Field.hpp" diff --git a/include/rfl/DefaultIfMissing.hpp b/include/rfl/DefaultIfMissing.hpp new file mode 100644 index 00000000..010d6260 --- /dev/null +++ b/include/rfl/DefaultIfMissing.hpp @@ -0,0 +1,19 @@ +#ifndef RFL_DEFAULTIFMISSING_HPP_ +#define RFL_DEFAULTIFMISSING_HPP_ + +namespace rfl { + +/// This is a "fake" processor - it doesn't do much in itself, but its +/// inclusion instructs the parsers to use the default values for missing +/// fields. +struct DefaultIfMissing { + public: + template + static auto process(auto&& _named_tuple) { + return _named_tuple; + } +}; + +} // namespace rfl + +#endif diff --git a/include/rfl/Processors.hpp b/include/rfl/Processors.hpp index 318635c2..4e7babba 100644 --- a/include/rfl/Processors.hpp +++ b/include/rfl/Processors.hpp @@ -3,6 +3,7 @@ #include +#include "internal/is_default_if_missing_v.hpp" #include "internal/is_no_field_names_v.hpp" #include "internal/is_no_optionals_v.hpp" #include "internal/is_underlying_enums_v.hpp" @@ -15,6 +16,7 @@ struct Processors; template <> struct Processors<> { static constexpr bool all_required_ = false; + static constexpr bool default_if_missing_ = false; static constexpr bool no_field_names_ = false; static constexpr bool underlying_enums_ = false; @@ -30,6 +32,10 @@ struct Processors { std::disjunction_v, internal::is_no_optionals...>; + static constexpr bool default_if_missing_ = + std::disjunction_v, + internal::is_default_if_missing...>; + static constexpr bool no_field_names_ = std::disjunction_v, internal::is_no_field_names...>; diff --git a/include/rfl/internal/is_default_if_missing_v.hpp b/include/rfl/internal/is_default_if_missing_v.hpp new file mode 100644 index 00000000..81639183 --- /dev/null +++ b/include/rfl/internal/is_default_if_missing_v.hpp @@ -0,0 +1,29 @@ +#ifndef RFL_INTERNAL_ISDEFAULTIFMISSING_HPP_ +#define RFL_INTERNAL_ISDEFAULTIFMISSING_HPP_ + +#include +#include +#include + +#include "../DefaultIfMissing.hpp" + +namespace rfl { +namespace internal { + +template +class is_default_if_missing; + +template +class is_default_if_missing : public std::false_type {}; + +template <> +class is_default_if_missing : public std::true_type {}; + +template +constexpr bool is_default_if_missing_v = + is_default_if_missing>>::value; + +} // namespace internal +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/NamedTupleParser.hpp b/include/rfl/parsing/NamedTupleParser.hpp index d943e442..5b9009bf 100644 --- a/include/rfl/parsing/NamedTupleParser.hpp +++ b/include/rfl/parsing/NamedTupleParser.hpp @@ -23,6 +23,8 @@ #include "Parent.hpp" #include "Parser_base.hpp" #include "ViewReader.hpp" +#include "ViewReaderWithDefault.hpp" +#include "ViewReaderWithDefaultAndStrippedFieldNames.hpp" #include "ViewReaderWithStrippedFieldNames.hpp" #include "is_empty.hpp" #include "is_required.hpp" @@ -48,6 +50,12 @@ struct NamedTupleParser { ViewReaderWithStrippedFieldNames, ViewReader>; + using ViewReaderWithDefaultType = std::conditional_t< + _no_field_names, + ViewReaderWithDefaultAndStrippedFieldNames, + ViewReaderWithDefault>; + using InputObjectOrArrayType = std::conditional_t<_no_field_names, typename R::InputArrayType, typename R::InputObjectType>; @@ -84,7 +92,7 @@ struct NamedTupleParser { return *ptr; } - /// Reads the data into a view. + /// Reads the data into a view assuming no default values. static std::optional read_view( const R& _r, const InputVarType& _var, NamedTuple* _view) noexcept { @@ -103,6 +111,25 @@ struct NamedTupleParser { } } + /// Reads the data into a view assuming default values. + static std::optional read_view_with_default( + 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_with_default(_r, *arr, _view); + } else { + auto obj = _r.to_object(_var); + if (!obj) [[unlikely]] { + return obj.error(); + } + return read_object_or_array_with_default(_r, *obj, _view); + } + } + template static void write(const W& _w, const NamedTuple& _tup, const P& _parent) noexcept { @@ -277,6 +304,26 @@ struct NamedTupleParser { } return std::nullopt; } + + static std::optional read_object_or_array_with_default( + const R& _r, const InputObjectOrArrayType& _obj_or_arr, + NamedTupleType* _view) noexcept { + std::vector errors; + const auto reader = ViewReaderWithDefaultType(&_r, _view, &errors); + std::optional err; + if constexpr (_no_field_names) { + err = _r.read_array(reader, _obj_or_arr); + } else { + err = _r.read_object(reader, _obj_or_arr); + } + if (err) { + return err; + } + if (errors.size() != 0) { + return to_single_error_message(errors); + } + return std::nullopt; + } }; } // namespace parsing diff --git a/include/rfl/parsing/Parser_default.hpp b/include/rfl/parsing/Parser_default.hpp index 0f4d6b77..5ab8f90b 100644 --- a/include/rfl/parsing/Parser_default.hpp +++ b/include/rfl/parsing/Parser_default.hpp @@ -68,7 +68,11 @@ struct Parser { return Parser::read(_r, _var) .and_then(wrap_in_t); } else if constexpr (std::is_class_v && std::is_aggregate_v) { - return read_struct(_r, _var); + if constexpr (ProcessorsType::default_if_missing_) { + return read_struct_with_default(_r, _var); + } else { + return read_struct(_r, _var); + } } else if constexpr (std::is_enum_v) { if constexpr (ProcessorsType::underlying_enums_) { return static_cast(*_r.template to_basic_type>(_var)); @@ -262,6 +266,24 @@ struct Parser { return std::move(*ptr); } + /// This is actually more straight-forward than the standard case - we just + /// allocate a struct and then fill it. But it is less efficient and it + /// assumes that all values on the struct have a default constructor, so we + /// only use it when the DefaultIfMissing preprocessor is added. + static Result read_struct_with_default(const R& _r, + const InputVarType& _var) { + auto t = T{}; + auto view = ProcessorsType::template process(to_view(t)); + using ViewType = std::remove_cvref_t; + const auto err = + Parser::read_view_with_default(_r, _var, + &view); + if (err) [[unlikely]] { + return *err; + } + return t; + } + static std::string replace_non_alphanumeric(std::string _str) { for (auto& ch : _str) { ch = std::isalnum(ch) ? ch : '_'; diff --git a/include/rfl/parsing/ViewReaderWithDefault.hpp b/include/rfl/parsing/ViewReaderWithDefault.hpp new file mode 100644 index 00000000..4fc00e0b --- /dev/null +++ b/include/rfl/parsing/ViewReaderWithDefault.hpp @@ -0,0 +1,137 @@ +#ifndef RFL_PARSING_VIEWREADERWITHDEFAULT_HPP_ +#define RFL_PARSING_VIEWREADERWITHDEFAULT_HPP_ + +#include +#include +#include +#include +#include + +#include "../Result.hpp" +#include "../Tuple.hpp" +#include "../internal/is_array.hpp" + +namespace rfl::parsing { + +template +class ViewReaderWithDefault { + private: + using InputVarType = typename R::InputVarType; + static constexpr size_t size_ = ViewType::size(); + + public: + ViewReaderWithDefault(const R* _r, ViewType* _view, + std::vector* _errors) + : r_(_r), view_(_view), errors_(_errors) {} + + ~ViewReaderWithDefault() = default; + + /// Assigns the parsed version of _var to the field signified by _name, if + /// such a field exists in the underlying view. + void read(const std::string_view& _name, const InputVarType& _var) const { + assign_to_matching_field(*r_, _name, _var, view_, errors_, + std::make_integer_sequence()); + } + + private: + template + static void assign_if_field_matches(const R& _r, + const std::string_view& _current_name, + const auto& _var, auto* _view, + auto* _errors, bool* _already_assigned) { + using FieldType = tuple_element_t; + using OriginalType = typename FieldType::Type; + using T = + std::remove_cvref_t>; + constexpr auto name = FieldType::name(); + if (!(*_already_assigned) && _current_name == name) { + *_already_assigned = true; + auto res = Parser::read(_r, _var); + if (!res) { + _errors->emplace_back(Error("Failed to parse field '" + + std::string(name) + + "': " + std::move(res.error()->what()))); + return; + } + if constexpr (std::is_pointer_v) { + move_to(rfl::get(*_view), &(*res)); + } else { + rfl::get(*_view) = std::move(*res); + } + } + } + + template + static void assign_to_extra_fields(const R& _r, + const std::string_view& _current_name, + const auto& _var, auto* _view, + auto* _errors) { + auto* extra_fields = _view->template get<_pos>(); + using ExtraFieldsType = + std::remove_cvref_t>; + using T = std::remove_cvref_t< + std::remove_pointer_t>; + auto res = Parser::read(_r, _var); + if (!res) { + _errors->emplace_back(Error("Failed to parse field '" + + std::string(_current_name) + + "': " + std::move(res.error()->what()))); + return; + } + extra_fields->emplace(std::string(_current_name), std::move(*res)); + } + + template + static void assign_to_matching_field(const R& _r, + const std::string_view& _current_name, + const auto& _var, auto* _view, + auto* _errors, + std::integer_sequence) { + bool already_assigned = false; + + (assign_if_field_matches(_r, _current_name, _var, _view, _errors, + &already_assigned), + ...); + + if constexpr (ViewType::pos_extra_fields() != -1) { + constexpr int pos = ViewType::pos_extra_fields(); + if (!already_assigned) { + assign_to_extra_fields(_r, _current_name, _var, _view, _errors); + } + } + } + + template + static void move_to(Target* _t, Source* _s) { + if constexpr (std::is_const_v) { + return move_to(const_cast*>(_t), _s); + } else if constexpr (!rfl::internal::is_array_v && + !std::is_array_v) { + *_t = Target(std::move(*_s)); + } else if constexpr (rfl::internal::is_array_v) { + static_assert(std::is_array_v, + "Expected target to be a c-array."); + for (size_t i = 0; i < _s->arr_.size(); ++i) { + move_to(&((*_t)[i]), &(_s->arr_[i])); + } + } else { + for (size_t i = 0; i < _s->size(); ++i) { + move_to(&((*_t)[i]), &((*_s)[i])); + } + } + } + + private: + /// The underlying reader. + const R* r_; + + /// The underlying view. + ViewType* view_; + + /// Collects any errors we may have come across. + std::vector* errors_; +}; + +} // namespace rfl::parsing + +#endif diff --git a/include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp b/include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp new file mode 100644 index 00000000..7fd72c9b --- /dev/null +++ b/include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp @@ -0,0 +1,111 @@ +#ifndef RFL_PARSING_VIEWREADERWITHDEFAULTANDSTRIPPEDFIELDNAMES_HPP_ +#define RFL_PARSING_VIEWREADERWITHDEFAULTANDSTRIPPEDFIELDNAMES_HPP_ + +#include +#include +#include +#include +#include + +#include "../Result.hpp" +#include "../Tuple.hpp" +#include "../internal/is_array.hpp" + +namespace rfl::parsing { + +template +class ViewReaderWithDefaultAndStrippedFieldNames { + private: + using InputVarType = typename R::InputVarType; + static constexpr size_t size_ = ViewType::size(); + + public: + ViewReaderWithDefaultAndStrippedFieldNames(const R* _r, ViewType* _view, + std::vector* _errors) + : i_(0), r_(_r), view_(_view), errors_(_errors) {} + + ~ViewReaderWithDefaultAndStrippedFieldNames() = default; + + /// Assigns the parsed version of _var to the field signified by i_, to be + /// used when the field names are stripped. + std::optional read(const InputVarType& _var) const { + if (i_ == size_) { + return Error("Expected a maximum of " + std::to_string(size_) + + " fields, but got at least one more."); + } + assign_to_field_i(*r_, _var, view_, errors_, i_, + std::make_integer_sequence()); + ++i_; + return std::nullopt; + } + + private: + template + static void assign_if_field_is_field_i(const R& _r, const auto& _var, + auto* _view, auto* _errors, int _i) { + using FieldType = tuple_element_t; + using OriginalType = typename FieldType::Type; + using T = + std::remove_cvref_t>; + constexpr auto name = FieldType::name(); + if (_i == i) { + auto res = Parser::read(_r, _var); + if (!res) { + _errors->emplace_back(Error("Failed to parse field '" + + std::string(name) + + "': " + std::move(res.error()->what()))); + return; + } + if constexpr (std::is_pointer_v) { + move_to(rfl::get(*_view), &(*res)); + } else { + rfl::get(*_view) = std::move(*res); + } + } + } + + template + static void assign_to_field_i(const R& _r, const auto& _var, auto* _view, + auto* _errors, int _i, + std::integer_sequence) { + (assign_if_field_is_field_i(_r, _var, _view, _errors, _i), ...); + } + + // TODO: Unnecessary code duplication. + template + static void move_to(Target* _t, Source* _s) { + if constexpr (std::is_const_v) { + return move_to(const_cast*>(_t), _s); + } else if constexpr (!rfl::internal::is_array_v && + !std::is_array_v) { + *_t = Target(std::move(*_s)); + } else if constexpr (rfl::internal::is_array_v) { + static_assert(std::is_array_v, + "Expected target to be a c-array."); + for (size_t i = 0; i < _s->arr_.size(); ++i) { + move_to(&((*_t)[i]), &(_s->arr_[i])); + } + } else { + for (size_t i = 0; i < _s->size(); ++i) { + move_to(&((*_t)[i]), &((*_s)[i])); + } + } + } + + private: + /// Indicates the current field. + mutable int i_; + + /// The underlying reader. + const R* r_; + + /// The underlying view. + ViewType* view_; + + /// Collects any errors we may have come across. + std::vector* errors_; +}; + +} // namespace rfl::parsing + +#endif diff --git a/tests/json/test_default_if_missing.cpp b/tests/json/test_default_if_missing.cpp new file mode 100644 index 00000000..d186b011 --- /dev/null +++ b/tests/json/test_default_if_missing.cpp @@ -0,0 +1,26 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_default_if_missing { + +struct Person { + std::string first_name; + std::string last_name = "Simpson"; + std::string town; +}; + +TEST(json, test_default_if_missing) { + auto homer = rfl::json::read( + R"({"first_name":"Homer"})") + .value(); + + EXPECT_EQ(homer.first_name, "Homer"); + EXPECT_EQ(homer.last_name, "Simpson"); + EXPECT_EQ(homer.town, ""); +} +} // namespace test_default_if_missing diff --git a/tests/json/test_default_if_missing_no_field_names.cpp b/tests/json/test_default_if_missing_no_field_names.cpp new file mode 100644 index 00000000..e90a53ed --- /dev/null +++ b/tests/json/test_default_if_missing_no_field_names.cpp @@ -0,0 +1,27 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_default_if_missing_no_field_names { + +struct Person { + std::string first_name; + std::string last_name = "Simpson"; + std::string town; +}; + +TEST(json, test_default_if_missing_no_field_names) { + auto homer = + rfl::json::read( + R"(["Homer"])") + .value(); + + EXPECT_EQ(homer.first_name, "Homer"); + EXPECT_EQ(homer.last_name, "Simpson"); + EXPECT_EQ(homer.town, ""); +} +} // namespace test_default_if_missing_no_field_names