diff --git a/include/rfl.hpp b/include/rfl.hpp index 8b5083c2..684e57b4 100644 --- a/include/rfl.hpp +++ b/include/rfl.hpp @@ -22,6 +22,7 @@ #include "rfl/make_named_tuple.hpp" #include "rfl/name_t.hpp" #include "rfl/named_tuple_t.hpp" +#include "rfl/parsing/CustomParser.hpp" #include "rfl/remove_fields.hpp" #include "rfl/replace.hpp" #include "rfl/to_named_tuple.hpp" diff --git a/include/rfl/parsing/CustomParser.hpp b/include/rfl/parsing/CustomParser.hpp new file mode 100644 index 00000000..b7db81dc --- /dev/null +++ b/include/rfl/parsing/CustomParser.hpp @@ -0,0 +1,36 @@ +#ifndef RFL_PARSING_CUSTOMPARSER_HPP_ +#define RFL_PARSING_CUSTOMPARSER_HPP_ + +#include + +#include "rfl/parsing/Parser.hpp" + +namespace rfl { +namespace parsing { + +template +struct CustomParser { + static Result read(const ReaderType& _r, + auto* _var) noexcept { + const auto to_class = [](const auto& _h) -> Result { + try { + return _h.to_class(); + } catch (std::exception& e) { + return Error(e.what()); + } + }; + return Parser::read(_r, _var) + .and_then(to_class); + } + + static auto write(const WriterType& _w, const OriginalClass& _p) noexcept { + return Parser::write( + _w, HelperStruct::from_class(_p)); + } +}; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/tests/test_custom_class3.hpp b/tests/test_custom_class3.hpp index 6c3ff175..5ba99bb7 100644 --- a/tests/test_custom_class3.hpp +++ b/tests/test_custom_class3.hpp @@ -31,15 +31,13 @@ struct PersonImpl { rfl::Field<"lastName", std::string> last_name; rfl::Field<"age", int> age; - static PersonImpl from_person(const Person& _p) { + static PersonImpl from_class(const Person& _p) noexcept { return PersonImpl{.first_name = _p.first_name(), .last_name = _p.last_name(), .age = _p.age()}; } - Person to_person() const { - return Person(first_name(), last_name(), age()); - } + Person to_class() const { return Person(first_name(), last_name(), age()); } }; } // namespace tcc3 @@ -48,19 +46,9 @@ namespace rfl { namespace parsing { template -struct Parser { - static Result read(const ReaderType& _r, - auto* _var) noexcept { - const auto to_person = [](const auto& _p) { return _p.to_person(); }; - return Parser::read(_r, _var) - .transform(to_person); - } - - static auto write(const WriterType& _w, const tcc3::Person& _p) noexcept { - return Parser::write( - _w, tcc3::PersonImpl::from_person(_p)); - } -}; +struct Parser + : public CustomParser {}; } // namespace parsing } // namespace rfl