Added a custom parser

This commit is contained in:
Patrick Urbanke
2023-10-03 16:01:46 +02:00
parent 98160988cb
commit a4bd3dbe4c
3 changed files with 42 additions and 17 deletions
+1
View File
@@ -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"
+36
View File
@@ -0,0 +1,36 @@
#ifndef RFL_PARSING_CUSTOMPARSER_HPP_
#define RFL_PARSING_CUSTOMPARSER_HPP_
#include <exception>
#include "rfl/parsing/Parser.hpp"
namespace rfl {
namespace parsing {
template <class ReaderType, class WriterType, class OriginalClass,
class HelperStruct>
struct CustomParser {
static Result<OriginalClass> read(const ReaderType& _r,
auto* _var) noexcept {
const auto to_class = [](const auto& _h) -> Result<OriginalClass> {
try {
return _h.to_class();
} catch (std::exception& e) {
return Error(e.what());
}
};
return Parser<ReaderType, WriterType, HelperStruct>::read(_r, _var)
.and_then(to_class);
}
static auto write(const WriterType& _w, const OriginalClass& _p) noexcept {
return Parser<ReaderType, WriterType, HelperStruct>::write(
_w, HelperStruct::from_class(_p));
}
};
} // namespace parsing
} // namespace rfl
#endif
+5 -17
View File
@@ -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 <class ReaderType, class WriterType>
struct Parser<ReaderType, WriterType, tcc3::Person> {
static Result<tcc3::Person> read(const ReaderType& _r,
auto* _var) noexcept {
const auto to_person = [](const auto& _p) { return _p.to_person(); };
return Parser<ReaderType, WriterType, tcc3::PersonImpl>::read(_r, _var)
.transform(to_person);
}
static auto write(const WriterType& _w, const tcc3::Person& _p) noexcept {
return Parser<ReaderType, WriterType, tcc3::PersonImpl>::write(
_w, tcc3::PersonImpl::from_person(_p));
}
};
struct Parser<ReaderType, WriterType, tcc3::Person>
: public CustomParser<ReaderType, WriterType, tcc3::Person,
tcc3::PersonImpl> {};
} // namespace parsing
} // namespace rfl