mirror of
https://codeberg.org/DawnMagnet/reflect-cpp
synced 2026-12-06 10:46:18 +08:00
Added tests for custom parsers
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
#include <rfl.hpp>
|
||||
#include <rfl/json.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "write_and_read.hpp"
|
||||
|
||||
namespace tcc3 {
|
||||
|
||||
struct Person {
|
||||
Person(const std::string& _first_name, const std::string& _last_name,
|
||||
const int _age)
|
||||
: first_name_(_first_name), last_name_(_last_name), age_(_age) {}
|
||||
|
||||
const auto& first_name() const { return first_name_; }
|
||||
|
||||
const auto& last_name() const { return last_name_; }
|
||||
|
||||
auto age() const { return age_; }
|
||||
|
||||
private:
|
||||
std::string first_name_;
|
||||
std::string last_name_;
|
||||
int age_;
|
||||
};
|
||||
|
||||
struct PersonImpl {
|
||||
rfl::Field<"firstName", std::string> first_name;
|
||||
rfl::Field<"lastName", std::string> last_name;
|
||||
rfl::Field<"age", int> age;
|
||||
|
||||
static PersonImpl from_person(const Person& _p) {
|
||||
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());
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace tcc3
|
||||
|
||||
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));
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace parsing
|
||||
} // namespace rfl
|
||||
|
||||
void test_custom_class3() {
|
||||
std::cout << "test_custom_class3" << std::endl;
|
||||
|
||||
const auto bart = tcc3::Person("Bart", "Simpson", 10);
|
||||
|
||||
write_and_read(
|
||||
bart, "{\"firstName\":\"Bart\",\"lastName\":\"Simpson\",\"age\":10}");
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "test_custom_class1.hpp"
|
||||
#include "test_custom_class2.hpp"
|
||||
#include "test_custom_class3.hpp"
|
||||
#include "test_default_values.hpp"
|
||||
#include "test_field_variant.hpp"
|
||||
#include "test_literal.hpp"
|
||||
@@ -18,6 +19,7 @@ int main() {
|
||||
test_ref();
|
||||
test_custom_class1();
|
||||
test_custom_class2();
|
||||
test_custom_class3();
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user