mirror of
https://codeberg.org/DawnMagnet/reflect-cpp
synced 2026-12-06 02:36:18 +08:00
Added support for compile-time field name retrieval
This commit is contained in:
@@ -193,6 +193,58 @@ This results in the following JSON string:
|
||||
|
||||
Other forms of tagging are supported as well. Refer to the [documentation](https://github.com/getml/reflect-cpp/tree/main/docs) for details.
|
||||
|
||||
## Reflective programming
|
||||
|
||||
Beyond serialization and deserialization through, reflect-cpp also supports reflective programming in general. For instance:
|
||||
|
||||
```cpp
|
||||
struct Person {
|
||||
std::string first_name;
|
||||
std::string last_name;
|
||||
std::vector<Person> children;
|
||||
};
|
||||
|
||||
const auto lisa = Person{.first_name = "Lisa", .last_name = "Simpson"};
|
||||
|
||||
// Returns a deep copy of "lisa" with the first_name replaced.
|
||||
const auto maggie = rfl::replace(
|
||||
lisa, rfl::make_field<"first_name">(std::string("Maggie")));
|
||||
```
|
||||
|
||||
```cpp
|
||||
struct A {
|
||||
std::string f1;
|
||||
std::string f2;
|
||||
};
|
||||
|
||||
struct B {
|
||||
std::string f3;
|
||||
std::string f4;
|
||||
};
|
||||
|
||||
struct C {
|
||||
std::string f1;
|
||||
std::string f2;
|
||||
std::string f4;
|
||||
};
|
||||
|
||||
const auto a = A{.f1 = "Hello", .f2 = "World"};
|
||||
|
||||
const auto b = B{.f3 = "Hello", .f4 = "World"};
|
||||
|
||||
// f1 and f2 are taken from a, f4 is taken from b, f3 is ignored.
|
||||
const auto c = rfl::as<C>(a, b);
|
||||
```
|
||||
```cpp
|
||||
const auto a = A{.f1 = "Hello", .f2 = "World"};
|
||||
|
||||
const auto c = C{.f1 = "C++", .f2 = "is", .f4 = "great"};
|
||||
|
||||
// The fields f1 and f2 are replaced with the fields f1 and f2 in a.
|
||||
const auto c2 = rfl::replace(c, a);
|
||||
```
|
||||
|
||||
|
||||
## Support for containers
|
||||
|
||||
### C++ standard library
|
||||
|
||||
+14
-12
@@ -9,25 +9,27 @@ For example:
|
||||
|
||||
```cpp
|
||||
struct A {
|
||||
rfl::Field<"f1", std::string> f1;
|
||||
rfl::Field<"f2", std::string> f2;
|
||||
std::string f1;
|
||||
std::string f2;
|
||||
};
|
||||
|
||||
struct B {
|
||||
rfl::Field<"f3", std::string> f3;
|
||||
rfl::Field<"f4", std::string> f4;
|
||||
std::string f3;
|
||||
std::string f4;
|
||||
};
|
||||
|
||||
struct C {
|
||||
rfl::Field<"f1", std::string> f1;
|
||||
rfl::Field<"f2", std::string> f2;
|
||||
rfl::Field<"f4", std::string> f4;
|
||||
std::string f1;
|
||||
std::string f2;
|
||||
std::string f4;
|
||||
};
|
||||
|
||||
const auto a = A{.f1 = "Hello", .f2 = "World"};
|
||||
|
||||
const auto b = B{.f3 = "Hello", .f4 = "World"};
|
||||
|
||||
// Creates c by retrieving f1 and f2 from a and f4 from b.
|
||||
// Ignores f3.
|
||||
const auto c = rfl::as<C>(a, b);
|
||||
```
|
||||
|
||||
@@ -49,19 +51,19 @@ In this case, `f1`, `f2` and `f4` are now moved into the newly created `c` of ty
|
||||
|
||||
```cpp
|
||||
struct A {
|
||||
rfl::Field<"f1", std::string> f1;
|
||||
rfl::Field<"f2", std::string> f2;
|
||||
std::string f1;
|
||||
std::string f2;
|
||||
};
|
||||
|
||||
struct B {
|
||||
rfl::Field<"f3", std::string> f3;
|
||||
rfl::Field<"f4", std::string> f4;
|
||||
std::string f3;
|
||||
std::string f4;
|
||||
};
|
||||
|
||||
struct C {
|
||||
rfl::Flatten<A> a;
|
||||
rfl::Flatten<B> b;
|
||||
rfl::Field<"f5", int> f5;
|
||||
int f5;
|
||||
};
|
||||
|
||||
const auto a = A{.f1 = "Hello", .f2 = "World"};
|
||||
|
||||
@@ -12,12 +12,7 @@ struct Person {
|
||||
};
|
||||
```
|
||||
|
||||
Even though this requires slightly more effort from the programmer, it has an important
|
||||
advantage: These field names are known at *compile time*, whereas the field names which
|
||||
are retrieved automatically are only known at *runtime*. Even though the runtime overhead
|
||||
should be negligible in most cases, this allows for compile-time checks
|
||||
which are otherwise impossible. It also allows for functionalities like `rfl::replace`,
|
||||
`rfl::as` or interactions with `rfl::NamedTuple` which we will see later in the documentation.
|
||||
These annotations are required if you are planning to use a compiler other than MSVC, GCC or clang.
|
||||
|
||||
There are a two things you have to keep in mind:
|
||||
|
||||
|
||||
+18
-48
@@ -1,14 +1,14 @@
|
||||
# `rfl::NamedTuple`
|
||||
|
||||
`rfl::NamedTuple` is very similar to `std::tuple`, but unlike `std::tuple` the fields have names.
|
||||
`rfl::NamedTuple` is very similar to `std::tuple`, but unlike `std::tuple`, the fields have names.
|
||||
|
||||
In other words, consider the following struct:
|
||||
|
||||
```cpp
|
||||
struct Person {
|
||||
rfl::Field<"firstName", std::string> first_name;
|
||||
rfl::Field<"lastName", std::string> last_name;
|
||||
rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">> birthday;
|
||||
std::string first_name;
|
||||
std::string last_name;
|
||||
rfl::Timestamp<"%Y-%m-%d"> birthday;
|
||||
};
|
||||
```
|
||||
|
||||
@@ -16,8 +16,8 @@ You might as well define the following `rfl::NamedTuple`:
|
||||
|
||||
```cpp
|
||||
using Person = rfl::NamedTuple<
|
||||
rfl::Field<"firstName", std::string>,
|
||||
rfl::Field<"lastName", std::string>,
|
||||
rfl::Field<"first_name", std::string>,
|
||||
rfl::Field<"last_name", std::string>,
|
||||
rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">>>;
|
||||
```
|
||||
|
||||
@@ -34,8 +34,8 @@ In plain language, that means that the compiler will regard this as absolutely e
|
||||
|
||||
```cpp
|
||||
using Person2 = rfl::NamedTuple<
|
||||
rfl::Field<"firstName", std::string>,
|
||||
rfl::Field<"lastName", std::string>,
|
||||
rfl::Field<"first_name", std::string>,
|
||||
rfl::Field<"last_name", std::string>,
|
||||
rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">>>;
|
||||
```
|
||||
|
||||
@@ -43,9 +43,9 @@ However, this will be seen as a type that is different from `Person`, the struct
|
||||
|
||||
```cpp
|
||||
struct Person2 {
|
||||
rfl::Field<"firstName", std::string> first_name;
|
||||
rfl::Field<"lastName", std::string> last_name;
|
||||
rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">> birthday;
|
||||
std::string first_name;
|
||||
std::string last_name;
|
||||
rfl::Timestamp<"%Y-%m-%d"> birthday;
|
||||
};
|
||||
```
|
||||
|
||||
@@ -53,8 +53,8 @@ Structural typing also means that you can declare new types on-the-fly. For inst
|
||||
to create a `Person` named tuple, you don't actually have to declare it at all. The following will do:
|
||||
|
||||
```cpp
|
||||
const auto person = rfl::Field<"firstName", std::string>("Homer") *
|
||||
rfl::Field<"lastName", std::string>("Simpson") *
|
||||
const auto person = rfl::Field<"first_name", std::string>("Homer") *
|
||||
rfl::Field<"last_name", std::string>("Simpson") *
|
||||
rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">>("1987-04-19");
|
||||
```
|
||||
|
||||
@@ -66,9 +66,9 @@ For instance, consider something like this:
|
||||
|
||||
```cpp
|
||||
struct Person {
|
||||
rfl::Field<"firstName", std::string> first_name;
|
||||
rfl::Field<"lastName", std::string> last_name;
|
||||
rfl::Field<"children", std::vector<Person>> children;
|
||||
std::string first_name;
|
||||
std::string last_name;
|
||||
std::vector<Person> children;
|
||||
};
|
||||
```
|
||||
|
||||
@@ -80,8 +80,8 @@ This is impossible to accomplish using structural typing and `rfl::NamedTuple`,
|
||||
Fields inside the named tuple can be accessed using `rfl::get` or the `.get` method:
|
||||
|
||||
```cpp
|
||||
const auto person = rfl::Field<"firstName", std::string>("Homer") *
|
||||
rfl::Field<"lastName", std::string>("Simpson") *
|
||||
const auto person = rfl::Field<"first_name", std::string>("Homer") *
|
||||
rfl::Field<"last_name", std::string>("Simpson") *
|
||||
rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">>("1987-04-19");
|
||||
|
||||
// OK in most circumstances (there are restrictions
|
||||
@@ -95,36 +95,6 @@ const auto first_name = person.template get<"firstName">();
|
||||
const auto first_name = rfl::get<"firstName">(person);
|
||||
```
|
||||
|
||||
## Similarity to structs
|
||||
|
||||
Most of the functionality we have described also work for `rfl::NamedTuple`.
|
||||
It should be noted that you are free to mix `rfl::NamedTuple` and structs.
|
||||
For instance, you can build a `rfl::TaggedUnion` from a combination of
|
||||
`rfl::NamedTuple` and structs or you could construct a struct from named tuples using
|
||||
`rfl::as`.
|
||||
|
||||
### `std::variant` and `rfl::TaggedUnion`
|
||||
|
||||
`rfl::NamedTuple`s can be inserted into `std::variant`:
|
||||
|
||||
```cpp
|
||||
using Circle = rfl::NamedTuple<rfl::Field<"radius", double>>;
|
||||
|
||||
using Rectangle = rfl::NamedTuple<
|
||||
rfl::Field<"height", double>,
|
||||
rfl::Field<"width", double>>;
|
||||
|
||||
using Square rfl::NamedTuple<rfl::Field<"width", double>>;
|
||||
|
||||
// Untagged variant - OK
|
||||
using Shapes = std::variant<Circle, Rectangle, Square>;
|
||||
|
||||
// Externally tagged variant - also OK:
|
||||
using Shapes = std::variant<rfl::Field<"circle", Circle>,
|
||||
rfl::Field<"rectangle", Rectangle>,
|
||||
rfl::Field<"square", Square>>;
|
||||
```
|
||||
|
||||
### `rfl::replace`
|
||||
|
||||
`rfl::replace` works for `rfl::NamedTuple` as well:
|
||||
|
||||
+16
-16
@@ -10,13 +10,13 @@ In some cases, we really only want to change one or a few fields, to get from on
|
||||
const auto lisa = Person{
|
||||
.first_name = "Lisa",
|
||||
.last_name = "Simpson",
|
||||
.children = rfl::default_value // same as std::vector<Person>()
|
||||
.children = std::vector<Person>()
|
||||
};
|
||||
|
||||
// Returns a deep copy of the original object,
|
||||
// replacing first_name.
|
||||
const auto maggie =
|
||||
rfl::replace(lisa, rfl::make_field<"firstName">(std::string("Maggie")));
|
||||
rfl::replace(lisa, rfl::make_field<"first_name">(std::string("Maggie")));
|
||||
```
|
||||
|
||||
`maggie` is now a deep copy of `lisa`, but with a new `first_name`.
|
||||
@@ -27,9 +27,9 @@ For instance, suppose we had put the field `children` into a `rfl::Box`:
|
||||
|
||||
```cpp
|
||||
struct Person {
|
||||
rfl::Field<"firstName", std::string> first_name;
|
||||
rfl::Field<"lastName", std::string> last_name;
|
||||
rfl::Field<"children", rfl::Box<std::vector<Person>>> children;
|
||||
std::string first_name;
|
||||
std::string last_name;
|
||||
rfl::Box<std::vector<Person>> children;
|
||||
};
|
||||
```
|
||||
|
||||
@@ -67,15 +67,15 @@ as if they were on the main level:
|
||||
|
||||
```cpp
|
||||
struct Person {
|
||||
rfl::Field<"firstName", std::string> first_name;
|
||||
rfl::Field<"lastName", rfl::Box<std::string>> last_name;
|
||||
rfl::Field<"age", int> age;
|
||||
std::string first_name;
|
||||
rfl::Box<std::string> last_name;
|
||||
int age;
|
||||
};
|
||||
|
||||
struct Employee {
|
||||
rfl::Flatten<Person> person;
|
||||
rfl::Field<"employer", rfl::Box<std::string>> employer;
|
||||
rfl::Field<"salary", float> salary;
|
||||
rfl::Box<std::string> employer;
|
||||
float salary;
|
||||
};
|
||||
|
||||
auto employee = Employee{
|
||||
@@ -98,15 +98,15 @@ You can also replace structs with other structs. Consider the following example:
|
||||
|
||||
```cpp
|
||||
struct Person {
|
||||
rfl::Field<"firstName", std::string> first_name;
|
||||
rfl::Field<"lastName", std::string> last_name;
|
||||
rfl::Field<"age", int> age;
|
||||
std::string first_name;
|
||||
std::string last_name;
|
||||
int age;
|
||||
};
|
||||
|
||||
struct Employee {
|
||||
rfl::Flatten<Person> person;
|
||||
rfl::Field<"employer", std::string> employer;
|
||||
rfl::Field<"salary", float> salary;
|
||||
std::string employer;
|
||||
float salary;
|
||||
};
|
||||
|
||||
const auto employee = Employee{
|
||||
@@ -125,7 +125,7 @@ This code flattens the employee structs and then replaces all relevant fields wi
|
||||
Finally, we get this JSON string:
|
||||
|
||||
```json
|
||||
{"firstName":"Carl","lastName":"","age":45,"employer":"Mr. Burns","salary":60000.0}
|
||||
{"first_name":"Carl","last_name":"","age":45,"employer":"Mr. Burns","salary":60000.0}
|
||||
```
|
||||
|
||||
Don't worry, this is fairly optimized and makes heavy use of forwarding. It does not make any copies than it absolutely has to.
|
||||
|
||||
@@ -82,18 +82,18 @@ It is also possible to set the tag explicitly:
|
||||
```cpp
|
||||
struct Circle {
|
||||
using Tag = rfl::Literal<"circle", "Circle">;
|
||||
rfl::Field<"radius", double> radius;
|
||||
double radius;
|
||||
};
|
||||
|
||||
struct Rectangle {
|
||||
using Tag = rfl::Literal<"rectangle", "Rectangle">;
|
||||
rfl::Field<"height", double> height;
|
||||
rfl::Field<"width", double> width;
|
||||
double height;
|
||||
double width;
|
||||
};
|
||||
|
||||
struct Square {
|
||||
using Tag = rfl::Literal<"square", "Square">;
|
||||
rfl::Field<"width", double> width;
|
||||
double width;
|
||||
};
|
||||
|
||||
using Shapes = rfl::TaggedUnion<"shape", Circle, Square, Rectangle>;
|
||||
|
||||
+24
-7
@@ -53,6 +53,26 @@ class Literal {
|
||||
|
||||
~Literal() = default;
|
||||
|
||||
/// Constructs a new Literal.
|
||||
template <internal::StringLiteral _name>
|
||||
static Literal<fields_...> make() {
|
||||
return Literal(Literal<fields_...>::template value_of<_name>());
|
||||
}
|
||||
|
||||
/// Constructs a new Literal, equivalent to make, for reasons of consistency.
|
||||
template <internal::StringLiteral _name>
|
||||
static Literal<fields_...> from_name() {
|
||||
return Literal<fields_...>::template make<_name>();
|
||||
}
|
||||
|
||||
/// Constructs a new Literal.
|
||||
template <ValueType _value>
|
||||
static Literal<fields_...> from_value() {
|
||||
static_assert(_value < num_fields_,
|
||||
"Value cannot exceed number of fields.");
|
||||
return Literal<fields_...>(_value);
|
||||
}
|
||||
|
||||
/// Determines whether the literal contains the string.
|
||||
static bool contains(const std::string& _str) { return has_value(_str); }
|
||||
|
||||
@@ -104,12 +124,6 @@ class Literal {
|
||||
return find_value(_str).transform(to_literal);
|
||||
};
|
||||
|
||||
/// Constructs a new Literal.
|
||||
template <internal::StringLiteral _name>
|
||||
static Literal<fields_...> make() {
|
||||
return Literal(Literal<fields_...>::template value_of<_name>());
|
||||
}
|
||||
|
||||
/// The name defined by the Literal.
|
||||
std::string name() const { return find_name(); }
|
||||
|
||||
@@ -141,6 +155,9 @@ class Literal {
|
||||
/// Alias for .name().
|
||||
std::string reflection() const { return name(); }
|
||||
|
||||
/// Returns the number of fields in the Literal.
|
||||
static constexpr size_t size() { return num_fields_; }
|
||||
|
||||
/// Alias for .name().
|
||||
std::string str() const { return name(); }
|
||||
|
||||
@@ -156,7 +173,7 @@ class Literal {
|
||||
}
|
||||
|
||||
private:
|
||||
/// Only make is allowed to use this constructor.
|
||||
/// Only the static methods are allowed to access this.
|
||||
Literal(const ValueType _value) : value_(_value) {}
|
||||
|
||||
/// Returns all of the allowed fields.
|
||||
|
||||
@@ -26,7 +26,7 @@ class Timestamp {
|
||||
using ReflectionType = std::string;
|
||||
|
||||
Timestamp(const char* _str) {
|
||||
const auto r = strptime(_str, _format.value_, &tm_);
|
||||
const auto r = strptime(_str, _format.str().c_str(), &tm_);
|
||||
if (r == NULL) {
|
||||
throw std::runtime_error("String '" + std::string(_str) +
|
||||
"' did not match format '" + Format().str() +
|
||||
@@ -59,7 +59,7 @@ class Timestamp {
|
||||
/// Necessary for the serialization to work.
|
||||
ReflectionType reflection() const {
|
||||
char outstr[200];
|
||||
strftime(outstr, 200, format_.value_, &tm_);
|
||||
strftime(outstr, 200, format_.str().c_str(), &tm_);
|
||||
return std::string(outstr);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
#ifndef RFL_FIELD_NAMES_T_HPP_
|
||||
#define RFL_FIELD_NAMES_T_HPP_
|
||||
|
||||
#include <functional>
|
||||
#include <type_traits>
|
||||
|
||||
#include "rfl/internal/get_field_names.hpp"
|
||||
|
||||
namespace rfl {
|
||||
|
||||
/// Returns a rfl::Literal containing the field names of struct T.
|
||||
template <class T>
|
||||
using field_names_t = typename std::invoke_result<
|
||||
decltype(internal::get_field_names<std::decay_t<T>>)>::type;
|
||||
|
||||
} // namespace rfl
|
||||
|
||||
#endif
|
||||
@@ -4,24 +4,46 @@
|
||||
#include <type_traits>
|
||||
|
||||
#include "internal/copy_from_named_tuple.hpp"
|
||||
#include "internal/copy_from_tuple.hpp"
|
||||
#include "internal/has_fields.hpp"
|
||||
#include "internal/move_from_named_tuple.hpp"
|
||||
#include "internal/move_from_tuple.hpp"
|
||||
#include "named_tuple_t.hpp"
|
||||
|
||||
namespace rfl {
|
||||
|
||||
/// Generates the struct T from a named tuple.
|
||||
template <class T, class NamedTupleType>
|
||||
T from_named_tuple(NamedTupleType&& _n) {
|
||||
using RequiredType = std::decay_t<rfl::named_tuple_t<T>>;
|
||||
if constexpr (!std::is_same<std::decay_t<NamedTupleType>, RequiredType>()) {
|
||||
return from_named_tuple<T>(RequiredType(std::forward<NamedTupleType>(_n)));
|
||||
} else if constexpr (internal::has_fields<T>()) {
|
||||
if constexpr (std::is_lvalue_reference<NamedTupleType>{}) {
|
||||
return internal::copy_from_named_tuple<T>(_n);
|
||||
return internal::copy_from_named_tuple<T>(_n);
|
||||
} else {
|
||||
return internal::move_from_named_tuple<T>(_n);
|
||||
return internal::move_from_named_tuple<T>(_n);
|
||||
}
|
||||
} else {
|
||||
if constexpr (std::is_lvalue_reference<NamedTupleType>{}) {
|
||||
return internal::copy_from_tuple<T>(_n.values());
|
||||
} else {
|
||||
return internal::move_from_tuple<T>(std::move(_n.values()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Generates the struct T from a named tuple.
|
||||
template <class T, class NamedTupleType>
|
||||
T from_named_tuple(const NamedTupleType& _n) {
|
||||
using RequiredType = std::decay_t<rfl::named_tuple_t<T>>;
|
||||
if constexpr (!std::is_same<std::decay_t<NamedTupleType>, RequiredType>()) {
|
||||
return from_named_tuple<T>(RequiredType(_n));
|
||||
} else if constexpr (internal::has_fields<T>()) {
|
||||
return internal::copy_from_named_tuple<T>(_n);
|
||||
} else {
|
||||
return internal::copy_from_tuple<T>(_n.values());
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace rfl
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
#define RFL_INTERNAL_STRINGLITERAL_HPP_
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
@@ -13,35 +14,36 @@ namespace internal {
|
||||
/// for the parameters names in the NamedTuples.
|
||||
template <size_t N>
|
||||
struct StringLiteral {
|
||||
constexpr StringLiteral(const char (&_str)[N]) {
|
||||
std::copy_n(_str, N, value_);
|
||||
}
|
||||
constexpr StringLiteral(const auto... _chars) : arr_{_chars...} {}
|
||||
|
||||
char value_[N];
|
||||
constexpr StringLiteral(const char (&_str)[N]) {
|
||||
std::copy_n(_str, N - 1, std::data(arr_));
|
||||
}
|
||||
|
||||
/// Returns the value as a string.
|
||||
std::string str() const { return std::string(value_); }
|
||||
/// Returns the value as a string.
|
||||
std::string str() const { return std::string(std::data(arr_), N - 1); }
|
||||
|
||||
/// Returns the value as a string.
|
||||
std::string_view string_view() const {
|
||||
return std::string_view(value_, N - 1);
|
||||
}
|
||||
/// Returns the value as a string.
|
||||
constexpr std::string_view string_view() const {
|
||||
return std::string_view(std::data(arr_), N - 1);
|
||||
}
|
||||
|
||||
std::array<char, N - 1> arr_;
|
||||
};
|
||||
|
||||
template <size_t N1, size_t N2>
|
||||
constexpr inline bool operator==(const StringLiteral<N1>& _first,
|
||||
const StringLiteral<N2>& _second) {
|
||||
if constexpr (N1 != N2) {
|
||||
return false;
|
||||
}
|
||||
return std::string_view(_first.value_, N1) ==
|
||||
std::string_view(_second.value_, N2);
|
||||
if constexpr (N1 != N2) {
|
||||
return false;
|
||||
}
|
||||
return _first.string_view() == _second.string_view();
|
||||
}
|
||||
|
||||
template <size_t N1, size_t N2>
|
||||
constexpr inline bool operator!=(const StringLiteral<N1>& _first,
|
||||
const StringLiteral<N2>& _second) {
|
||||
return !(_first == _second);
|
||||
return !(_first == _second);
|
||||
}
|
||||
|
||||
} // namespace internal
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
#ifndef RFL_INTERNAL_COPY_FLATTENED_TUPLE_TO_NAMED_TUPLE_HPP_
|
||||
#define RFL_INTERNAL_COPY_FLATTENED_TUPLE_TO_NAMED_TUPLE_HPP_
|
||||
|
||||
#include <functional>
|
||||
#include <tuple>
|
||||
#include <type_traits>
|
||||
|
||||
#include "rfl/Field.hpp"
|
||||
#include "rfl/internal/lit_name.hpp"
|
||||
#include "rfl/make_named_tuple.hpp"
|
||||
|
||||
namespace rfl {
|
||||
namespace internal {
|
||||
|
||||
template <class FieldNames, class... Fields>
|
||||
auto copy_flattened_tuple_to_named_tuple(const auto& _flattened_tuple,
|
||||
Fields&&... _fields) {
|
||||
constexpr auto size =
|
||||
std::tuple_size_v<std::decay_t<decltype(_flattened_tuple)>>;
|
||||
constexpr auto i = sizeof...(_fields);
|
||||
if constexpr (i == size) {
|
||||
return make_named_tuple(std::move(_fields)...);
|
||||
} else {
|
||||
const auto name_literal = FieldNames::template name_of<i>();
|
||||
auto new_field =
|
||||
rfl::make_field<lit_name_v<std::decay_t<decltype(name_literal)>>>(
|
||||
std::get<i>(_flattened_tuple));
|
||||
return copy_flattened_tuple_to_named_tuple<FieldNames>(
|
||||
_flattened_tuple, std::move(_fields)..., std::move(new_field));
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace internal
|
||||
} // namespace rfl
|
||||
|
||||
#endif
|
||||
@@ -1,66 +1,17 @@
|
||||
#ifndef RFL_INTERNAL_COPY_FROM_NAMED_TUPLE_HPP_
|
||||
#define RFL_INTERNAL_COPY_FROM_NAMED_TUPLE_HPP_
|
||||
|
||||
#include <functional>
|
||||
#include <type_traits>
|
||||
|
||||
#include "rfl/internal/has_flatten_fields.hpp"
|
||||
#include "rfl/internal/is_named_tuple.hpp"
|
||||
#include "rfl/internal/move_from_named_tuple.hpp"
|
||||
#include "rfl/internal/ptr_field_tuple_t.hpp"
|
||||
#include "rfl/named_tuple_t.hpp"
|
||||
|
||||
namespace rfl {
|
||||
namespace internal {
|
||||
|
||||
template <class FieldTupleType, class NamedTupleType, class... Args>
|
||||
FieldTupleType concat_named_tuple(const NamedTupleType& _n, Args&&... _args);
|
||||
|
||||
/// Creates a struct of type T from a named tuple.
|
||||
/// All fields of the struct must be an rfl::Field.
|
||||
template <class T, class NamedTupleType>
|
||||
T copy_from_named_tuple(const NamedTupleType& _n) {
|
||||
using RequiredType = std::decay_t<named_tuple_t<T>>;
|
||||
|
||||
if constexpr (internal::is_named_tuple_v<std::decay_t<T>>) {
|
||||
return _n;
|
||||
} else if constexpr (std::is_same<std::decay_t<NamedTupleType>,
|
||||
RequiredType>()) {
|
||||
const auto make = []<class... ValueTypes>(ValueTypes&&... _values) {
|
||||
return T{std::move(_values)...};
|
||||
};
|
||||
|
||||
using PtrFieldTupleType = internal::ptr_field_tuple_t<std::decay_t<T>>;
|
||||
|
||||
if constexpr (!internal::has_flatten_fields<PtrFieldTupleType>()) {
|
||||
auto values = _n.values();
|
||||
return std::apply(make, std::move(values));
|
||||
} else {
|
||||
auto fields = concat_named_tuple<PtrFieldTupleType>(_n);
|
||||
return std::apply(make, std::move(fields));
|
||||
}
|
||||
|
||||
} else {
|
||||
return move_from_named_tuple<T, RequiredType>(RequiredType(_n));
|
||||
}
|
||||
}
|
||||
|
||||
template <class FieldTupleType, class NamedTupleType, class... Args>
|
||||
FieldTupleType concat_named_tuple(const NamedTupleType& _n, Args&&... _args) {
|
||||
constexpr auto i = sizeof...(Args);
|
||||
if constexpr (i == std::tuple_size_v<std::decay_t<FieldTupleType>>) {
|
||||
return std::make_tuple(std::forward<Args>(_args)...);
|
||||
} else {
|
||||
using T = std::tuple_element_t<i, FieldTupleType>;
|
||||
if constexpr (internal::is_flatten_field<T>::value) {
|
||||
return concat_named_tuple<FieldTupleType>(
|
||||
_n, std::move(_args)...,
|
||||
copy_from_named_tuple<typename T::Type>(_n));
|
||||
} else {
|
||||
return concat_named_tuple<FieldTupleType>(
|
||||
_n, std::move(_args)..., _n.template get_field<T::name_>());
|
||||
}
|
||||
}
|
||||
auto n = _n;
|
||||
return move_from_named_tuple(std::move(n));
|
||||
}
|
||||
|
||||
} // namespace internal
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
#ifndef RFL_COPY_FROM_TUPLE_HPP_
|
||||
#define RFL_COPY_FROM_TUPLE_HPP_
|
||||
|
||||
#include "rfl/internal/move_from_tuple.hpp"
|
||||
|
||||
namespace rfl {
|
||||
namespace internal {
|
||||
|
||||
/// Creates a struct of type T from a tuple by copying the underlying
|
||||
/// fields.
|
||||
template <class T, class TupleType>
|
||||
T copy_from_tuple(const TupleType& _t) {
|
||||
auto t = _t;
|
||||
return move_from_tuple<T, TupleType>(std::move(t));
|
||||
}
|
||||
|
||||
} // namespace internal
|
||||
} // namespace rfl
|
||||
|
||||
#endif
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,19 @@
|
||||
#ifndef RFL_INTERNAL_FIELD_NAMES_T_HPP_
|
||||
#define RFL_INTERNAL_FIELD_NAMES_T_HPP_
|
||||
|
||||
#include <functional>
|
||||
#include <type_traits>
|
||||
|
||||
#include "rfl/internal/to_ptr_tuple.hpp"
|
||||
|
||||
namespace rfl {
|
||||
namespace internal {
|
||||
|
||||
template <class T>
|
||||
using field_names_t =
|
||||
typename std::invoke_result<decltype(to_ptr_tuple<T>), T>::type;
|
||||
|
||||
} // namespace internal
|
||||
} // namespace rfl
|
||||
|
||||
#endif
|
||||
@@ -6,13 +6,16 @@
|
||||
#include <memory>
|
||||
#include <source_location>
|
||||
#include <string>
|
||||
#include <tuple>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
|
||||
#include "rfl/Literal.hpp"
|
||||
#include "rfl/internal/fake_object.hpp"
|
||||
#include "rfl/internal/is_flatten_field.hpp"
|
||||
#include "rfl/internal/is_rename.hpp"
|
||||
#include "rfl/internal/num_fields.hpp"
|
||||
#include "rfl/internal/to_ptr_tuple.hpp"
|
||||
|
||||
namespace rfl {
|
||||
namespace internal {
|
||||
@@ -32,73 +35,96 @@ constexpr auto wrap(const T& arg) noexcept {
|
||||
return Wrapper{arg};
|
||||
}
|
||||
|
||||
template <auto ptr>
|
||||
consteval auto get_field_name_str_view() {
|
||||
const auto func_name =
|
||||
std::string_view{std::source_location::current().function_name()};
|
||||
#if defined(__clang__)
|
||||
const auto split = func_name.substr(0, func_name.find("}]"));
|
||||
return split.substr(split.find_last_of(".") + 1);
|
||||
#elif defined(__GNUC__)
|
||||
const auto split = func_name.substr(0, func_name.find(")}"));
|
||||
return split.substr(split.find_last_of(":") + 1);
|
||||
#elif defined(_MSC_VER)
|
||||
const auto split = func_name.substr(0, func_name.find_last_of("}"));
|
||||
return split.substr(split.find_last_of(">") + 1);
|
||||
#else
|
||||
static_assert(false,
|
||||
"You are using an unsupported compiler. Please use GCC, Clang "
|
||||
"or MSVC or switch to the rfl::Field-syntax.");
|
||||
#endif
|
||||
}
|
||||
|
||||
template <auto ptr>
|
||||
consteval auto get_field_name_str_lit() {
|
||||
constexpr auto name = get_field_name_str_view<ptr>();
|
||||
const auto to_str_lit = [&]<auto... Ns>(std::index_sequence<Ns...>) {
|
||||
return StringLiteral<sizeof...(Ns) + 1>{name[Ns]...};
|
||||
};
|
||||
return to_str_lit(std::make_index_sequence<name.size()>{});
|
||||
}
|
||||
|
||||
template <class T>
|
||||
auto get_field_names();
|
||||
|
||||
template <int i, auto ptr>
|
||||
template <auto ptr>
|
||||
auto get_field_name() {
|
||||
using Type = std::decay_t<std::remove_pointer_t<
|
||||
typename std::remove_pointer_t<decltype(ptr)>::Type>>;
|
||||
if constexpr (is_rename_v<Type>) {
|
||||
using Name = typename Type::Name;
|
||||
return std::array<std::string, 1>{Name().str()};
|
||||
return Name();
|
||||
} else if constexpr (is_flatten_field_v<Type>) {
|
||||
return get_field_names<std::decay_t<typename Type::Type>>();
|
||||
} else {
|
||||
const std::string func_name =
|
||||
std::source_location::current().function_name();
|
||||
const size_t pos = func_name.find(">->");
|
||||
const size_t begin =
|
||||
(pos != std::string::npos) ? pos + 3 : func_name.find_last_of(":.") + 1;
|
||||
if (begin == std::string::npos) {
|
||||
return std::array<std::string, 1>{"f_" + std::to_string(i)};
|
||||
}
|
||||
const size_t end = func_name.find_first_of("])}>", begin);
|
||||
if (end == std::string::npos) {
|
||||
return std::array<std::string, 1>{"f_" + std::to_string(i)};
|
||||
}
|
||||
return std::array<std::string, 1>{func_name.substr(begin, end - begin)};
|
||||
return rfl::Literal<get_field_name_str_lit<ptr>()>();
|
||||
}
|
||||
}
|
||||
|
||||
template <auto N1, auto N2>
|
||||
auto concat_two_arrays(std::array<std::string, N1>&& _arr1,
|
||||
std::array<std::string, N2>&& _arr2) {
|
||||
std::array<std::string, N1 + N2> res;
|
||||
for (size_t i = 0; i < N1; ++i) {
|
||||
res[i] = std::move(_arr1[i]);
|
||||
}
|
||||
for (size_t i = 0; i < N2; ++i) {
|
||||
res[i + N1] = std::move(_arr2[i]);
|
||||
}
|
||||
return res;
|
||||
template <StringLiteral... _names1, StringLiteral... _names2>
|
||||
auto concat_two_literals(const rfl::Literal<_names1...>& _lit1,
|
||||
const rfl::Literal<_names2...>& _lit2) {
|
||||
return rfl::Literal<_names1..., _names2...>::template from_value<0>();
|
||||
}
|
||||
|
||||
template <class Head, class... Tail>
|
||||
auto concat_arrays(Head&& _head, Tail&&... _tail) {
|
||||
auto concat_literals(const Head& _head, const Tail&... _tail) {
|
||||
if constexpr (sizeof...(_tail) == 0) {
|
||||
return std::move(_head);
|
||||
return _head;
|
||||
} else {
|
||||
return concat_two_arrays(std::move(_head),
|
||||
concat_arrays(std::move(_tail)...));
|
||||
return concat_two_literals(_head, concat_literals(_tail...));
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef __clang__
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wundefined-var-template"
|
||||
#endif
|
||||
|
||||
template <class T>
|
||||
#if __GNUC__
|
||||
#ifndef __clang__
|
||||
[[gnu::no_sanitize_undefined]]
|
||||
#endif
|
||||
#endif
|
||||
auto get_field_names() {
|
||||
if constexpr (std::is_pointer_v<std::decay_t<T>>) {
|
||||
return get_field_names<std::remove_pointer_t<T>>();
|
||||
} else
|
||||
return []<std::size_t... Is>(std::index_sequence<Is...>) {
|
||||
return concat_arrays(
|
||||
get_field_name<Is + 1, wrap(std::get<Is>(
|
||||
to_ptr_tuple(fake_object<T>)))>()...);
|
||||
}(std::make_index_sequence<num_fields<T>>());
|
||||
} else {
|
||||
constexpr auto ptr_tuple = to_ptr_tuple(fake_object<T>);
|
||||
const auto get = [&]<std::size_t... Is>(std::index_sequence<Is...>) {
|
||||
return concat_literals(
|
||||
get_field_name<wrap(std::get<Is>(ptr_tuple))>()...);
|
||||
};
|
||||
return get(
|
||||
std::make_index_sequence<std::tuple_size_v<decltype(ptr_tuple)>>());
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef __clang__
|
||||
#pragma clang diagnostic pop
|
||||
#endif
|
||||
|
||||
} // namespace internal
|
||||
} // namespace rfl
|
||||
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
#ifndef RFL_INTERNAL_LIT_NAME_HPP_
|
||||
#define RFL_INTERNAL_LIT_NAME_HPP_
|
||||
|
||||
#include "rfl/Literal.hpp"
|
||||
|
||||
namespace rfl {
|
||||
namespace internal {
|
||||
|
||||
template <class T>
|
||||
struct lit_name;
|
||||
|
||||
template <auto _name>
|
||||
struct lit_name<rfl::Literal<_name>> {
|
||||
constexpr static auto name_ = _name;
|
||||
};
|
||||
|
||||
template <class LiteralType>
|
||||
constexpr auto lit_name_v = lit_name<LiteralType>::name_;
|
||||
|
||||
} // namespace internal
|
||||
} // namespace rfl
|
||||
|
||||
#endif
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -5,9 +5,13 @@
|
||||
#include <tuple>
|
||||
|
||||
#include "rfl/always_false.hpp"
|
||||
#include "rfl/field_names_t.hpp"
|
||||
#include "rfl/internal/copy_flattened_tuple_to_named_tuple.hpp"
|
||||
#include "rfl/internal/has_fields.hpp"
|
||||
#include "rfl/internal/has_flatten_fields.hpp"
|
||||
#include "rfl/internal/is_field.hpp"
|
||||
#include "rfl/internal/is_named_tuple.hpp"
|
||||
#include "rfl/internal/to_flattened_ptr_tuple.hpp"
|
||||
#include "rfl/internal/to_ptr_field_tuple.hpp"
|
||||
#include "rfl/make_named_tuple.hpp"
|
||||
|
||||
@@ -51,13 +55,19 @@ auto field_tuple_to_named_tuple(const PtrFieldTuple& _ptr_field_tuple) {
|
||||
/// the struct.
|
||||
template <class T>
|
||||
auto to_ptr_named_tuple(const T& _t) {
|
||||
if constexpr (std::is_pointer_v<std::decay_t<T>>) {
|
||||
return to_ptr_named_tuple(*_t);
|
||||
} else if constexpr (is_named_tuple_v<std::decay_t<T>>) {
|
||||
return nt_to_ptr_named_tuple(_t);
|
||||
if constexpr (has_fields<std::decay_t<T>>()) {
|
||||
if constexpr (std::is_pointer_v<std::decay_t<T>>) {
|
||||
return to_ptr_named_tuple(*_t);
|
||||
} else if constexpr (is_named_tuple_v<std::decay_t<T>>) {
|
||||
return nt_to_ptr_named_tuple(_t);
|
||||
} else {
|
||||
const auto ptr_field_tuple = to_ptr_field_tuple(_t);
|
||||
return field_tuple_to_named_tuple(ptr_field_tuple);
|
||||
}
|
||||
} else {
|
||||
const auto ptr_field_tuple = to_ptr_field_tuple(_t);
|
||||
return field_tuple_to_named_tuple(ptr_field_tuple);
|
||||
using FieldNames = rfl::field_names_t<T>;
|
||||
const auto flattened_ptr_tuple = to_flattened_ptr_tuple(_t);
|
||||
return copy_flattened_tuple_to_named_tuple<FieldNames>(flattened_ptr_tuple);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+12
-234
@@ -70,219 +70,6 @@ struct Parser;
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
/// Used for any structs that are aggregates.
|
||||
template <class R, class W, class T>
|
||||
struct StructParser {
|
||||
using InputObjectType = typename R::InputObjectType;
|
||||
using InputVarType = typename R::InputVarType;
|
||||
|
||||
using OutputObjectType = typename W::OutputObjectType;
|
||||
using OutputVarType = typename W::OutputVarType;
|
||||
|
||||
using PtrTupleType = internal::flattened_ptr_tuple_t<T>;
|
||||
using TupleType = internal::flattened_tuple_t<T>;
|
||||
|
||||
static constexpr auto tuple_size = std::tuple_size_v<TupleType>;
|
||||
|
||||
public:
|
||||
/// Generates a NamedTuple from a JSON Object.
|
||||
static Result<T> read(const R& _r, const InputVarType& _var) noexcept {
|
||||
const auto& indices = field_indices();
|
||||
|
||||
const auto fct = [&](const std::string_view& _str) -> std::int16_t {
|
||||
const auto it = indices.find(_str);
|
||||
return it != indices.end() ? it->second : static_cast<std::uint16_t>(-1);
|
||||
};
|
||||
|
||||
const auto to_fields_array = [&](auto _obj) {
|
||||
return _r.template to_fields_array<tuple_size>(fct, _obj);
|
||||
};
|
||||
|
||||
const auto build_tuple = [&](auto _fields_vec) -> Result<TupleType> {
|
||||
return build_tuple_recursively(_r, _fields_vec);
|
||||
};
|
||||
|
||||
const auto to_struct = [](TupleType&& _t) -> T {
|
||||
return internal::move_from_tuple<T, TupleType>(std::move(_t));
|
||||
};
|
||||
|
||||
return _r.to_object(_var)
|
||||
.transform(to_fields_array)
|
||||
.and_then(build_tuple)
|
||||
.transform(to_struct);
|
||||
}
|
||||
|
||||
/// Transforms a NamedTuple into a JSON object.
|
||||
static OutputVarType write(const W& _w, const T& _var) noexcept {
|
||||
const auto ptr_tuple = internal::to_flattened_ptr_tuple(_var);
|
||||
|
||||
auto obj = _w.new_object();
|
||||
|
||||
build_object_recursively(_w, ptr_tuple, &obj);
|
||||
|
||||
return OutputVarType(obj);
|
||||
}
|
||||
|
||||
private:
|
||||
/// Builds the tuple field by field containing the values for the structs
|
||||
/// recursively.
|
||||
template <class... Args>
|
||||
static Result<TupleType> build_tuple_recursively(
|
||||
const R& _r,
|
||||
const std::array<std::optional<InputVarType>, tuple_size>& _fields_arr,
|
||||
Args&&... _args) noexcept {
|
||||
constexpr auto i = sizeof...(Args);
|
||||
|
||||
if constexpr (i == std::tuple_size_v<TupleType>) {
|
||||
return std::make_tuple(std::move(_args)...);
|
||||
} else {
|
||||
using ValueType =
|
||||
std::decay_t<typename std::tuple_element<i, TupleType>::type>;
|
||||
|
||||
const auto& f = std::get<i>(_fields_arr);
|
||||
|
||||
const auto key = std::get<i>(field_names());
|
||||
|
||||
if (!f) {
|
||||
if constexpr (is_required<ValueType>()) {
|
||||
return collect_errors<i + 1>(
|
||||
_r, _fields_arr,
|
||||
std::vector<Error>(
|
||||
{Error("Field named '" + key + "' not found!")}));
|
||||
} else {
|
||||
return build_tuple_recursively(_r, _fields_arr, std::move(_args)...,
|
||||
ValueType());
|
||||
}
|
||||
}
|
||||
|
||||
const auto handle_error = [&](Error&& _error) {
|
||||
return collect_errors<i + 1>(_r, _fields_arr,
|
||||
std::vector<Error>({std::move(_error)}));
|
||||
};
|
||||
|
||||
const auto build_tuple = [&](auto&& _value) {
|
||||
return build_tuple_recursively(_r, _fields_arr, std::move(_args)...,
|
||||
std::move(_value));
|
||||
};
|
||||
|
||||
return get_value<ValueType>(_r, *f, key)
|
||||
.or_else(handle_error)
|
||||
.and_then(build_tuple);
|
||||
}
|
||||
}
|
||||
|
||||
/// If something went wrong, we want to collect all of the errors - it's
|
||||
/// just good UX.
|
||||
template <int _i>
|
||||
static Error collect_errors(
|
||||
const R& _r,
|
||||
const std::array<std::optional<InputVarType>, tuple_size>& _fields_arr,
|
||||
std::vector<Error> _errors) noexcept {
|
||||
if constexpr (_i == tuple_size) {
|
||||
if (_errors.size() == 1) {
|
||||
return std::move(_errors[0]);
|
||||
} else {
|
||||
std::string msg =
|
||||
"Found " + std::to_string(_errors.size()) + " errors:";
|
||||
for (size_t i = 0; i < _errors.size(); ++i) {
|
||||
msg += "\n" + std::to_string(i + 1) + ") " + _errors.at(i).what();
|
||||
}
|
||||
return Error(msg);
|
||||
}
|
||||
} else {
|
||||
using ValueType =
|
||||
std::decay_t<typename std::tuple_element<_i, TupleType>::type>;
|
||||
|
||||
const auto& f = std::get<_i>(_fields_arr);
|
||||
|
||||
const auto key = std::get<_i>(field_names());
|
||||
|
||||
if (!f) {
|
||||
if constexpr (is_required<ValueType>()) {
|
||||
_errors.emplace_back(Error("Field named '" + key + "' not found."));
|
||||
}
|
||||
return collect_errors<_i + 1>(_r, _fields_arr, std::move(_errors));
|
||||
}
|
||||
|
||||
const auto add_error_if_applicable =
|
||||
[&](Error&& _error) -> Result<ValueType> {
|
||||
_errors.emplace_back(std::move(_error));
|
||||
return _error;
|
||||
};
|
||||
|
||||
get_value<ValueType>(_r, *f, key).or_else(add_error_if_applicable);
|
||||
|
||||
return collect_errors<_i + 1>(_r, _fields_arr, std::move(_errors));
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds the object field by field.
|
||||
template <int _i = 0>
|
||||
static void build_object_recursively(const W& _w, const PtrTupleType& _tup,
|
||||
OutputObjectType* _ptr) noexcept {
|
||||
if constexpr (_i >= tuple_size) {
|
||||
return;
|
||||
} else {
|
||||
using ValueType =
|
||||
std::decay_t<typename std::tuple_element<_i, PtrTupleType>::type>;
|
||||
|
||||
auto value = Parser<R, W, ValueType>::write(_w, std::get<_i>(_tup));
|
||||
|
||||
const auto& key = std::get<_i>(field_names());
|
||||
|
||||
if constexpr (!is_required<ValueType>()) {
|
||||
if (!_w.is_empty(value)) {
|
||||
_w.set_field(key, value, _ptr);
|
||||
}
|
||||
} else {
|
||||
_w.set_field(key, value, _ptr);
|
||||
}
|
||||
|
||||
return build_object_recursively<_i + 1>(_w, _tup, _ptr);
|
||||
}
|
||||
}
|
||||
|
||||
/// Uses a memoization pattern to retrieve the field indices.
|
||||
/// There are some objects that we are likely to parse many times,
|
||||
/// so we only calculate these indices once.
|
||||
static const auto& field_indices() noexcept {
|
||||
return fields_.value(make_fields).indices_;
|
||||
}
|
||||
|
||||
/// Uses a memoization pattern to retrieve the field names.
|
||||
/// There are some objects that we are likely to parse many times,
|
||||
/// so we only calculate these indices once.
|
||||
static const auto& field_names() noexcept {
|
||||
return fields_.value(make_fields).names_;
|
||||
}
|
||||
|
||||
/// Retrieves the value from the object. This is mainly needed to
|
||||
/// generate a better error message.
|
||||
template <class ValueType>
|
||||
static auto get_value(const R& _r, const InputVarType _var,
|
||||
const std::string& _key) noexcept {
|
||||
const auto embellish_error = [&](const Error& _e) {
|
||||
return Error("Failed to parse field '" + _key + "': " + _e.what());
|
||||
};
|
||||
return Parser<R, W, ValueType>::read(_r, _var).or_else(embellish_error);
|
||||
}
|
||||
|
||||
/// Builds the object field by field.
|
||||
static void make_fields(internal::Fields<tuple_size>* _fields) noexcept {
|
||||
_fields->names_ = internal::get_field_names<T>();
|
||||
for (size_t i = 0; i < tuple_size; ++i) {
|
||||
_fields->indices_[_fields->names_[i]] = static_cast<std::int16_t>(i);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
/// Maps each of the field names to an index signifying their order and
|
||||
/// vice-versa.
|
||||
static inline internal::Memoization<internal::Fields<tuple_size>> fields_;
|
||||
};
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
|
||||
/// Default case - anything that cannot be explicitly matched.
|
||||
template <class R, class W, class T>
|
||||
requires AreReaderAndWriter<R, W, T>
|
||||
@@ -306,20 +93,15 @@ struct Parser {
|
||||
};
|
||||
return Parser<R, W, ReflectionType>::read(_r, _var).and_then(wrap_in_t);
|
||||
} else if constexpr (std::is_class_v<T> && std::is_aggregate_v<T>) {
|
||||
if constexpr (internal::has_fields<T>()) {
|
||||
using NamedTupleType = named_tuple_t<T>;
|
||||
const auto to_struct = [](NamedTupleType&& _n) -> Result<T> {
|
||||
try {
|
||||
return from_named_tuple<T>(std::move(_n));
|
||||
} catch (std::exception& e) {
|
||||
return Error(e.what());
|
||||
}
|
||||
};
|
||||
return Parser<R, W, NamedTupleType>::read(_r, _var).and_then(
|
||||
to_struct);
|
||||
} else {
|
||||
return StructParser<R, W, T>::read(_r, _var);
|
||||
}
|
||||
using NamedTupleType = named_tuple_t<T>;
|
||||
const auto to_struct = [](NamedTupleType&& _n) -> Result<T> {
|
||||
try {
|
||||
return from_named_tuple<T>(std::move(_n));
|
||||
} catch (std::exception& e) {
|
||||
return Error(e.what());
|
||||
}
|
||||
};
|
||||
return Parser<R, W, NamedTupleType>::read(_r, _var).and_then(to_struct);
|
||||
} else if constexpr (internal::is_basic_type_v<T>) {
|
||||
return _r.template to_basic_type<std::decay_t<T>>(_var);
|
||||
} else {
|
||||
@@ -343,13 +125,9 @@ struct Parser {
|
||||
return Parser<R, W, ReflectionType>::write(_w, r);
|
||||
}
|
||||
} else if constexpr (std::is_class_v<T> && std::is_aggregate_v<T>) {
|
||||
if constexpr (internal::has_fields<T>()) {
|
||||
const auto ptr_named_tuple = internal::to_ptr_named_tuple(_var);
|
||||
using PtrNamedTupleType = std::decay_t<decltype(ptr_named_tuple)>;
|
||||
return Parser<R, W, PtrNamedTupleType>::write(_w, ptr_named_tuple);
|
||||
} else {
|
||||
return StructParser<R, W, T>::write(_w, _var);
|
||||
}
|
||||
const auto ptr_named_tuple = internal::to_ptr_named_tuple(_var);
|
||||
using PtrNamedTupleType = std::decay_t<decltype(ptr_named_tuple)>;
|
||||
return Parser<R, W, PtrNamedTupleType>::write(_w, ptr_named_tuple);
|
||||
} else if constexpr (internal::is_basic_type_v<T>) {
|
||||
return _w.from_basic_type(_var);
|
||||
} else {
|
||||
|
||||
@@ -16,6 +16,7 @@ add_executable(
|
||||
"test_any_of.cpp"
|
||||
"test_array.cpp"
|
||||
"test_as.cpp"
|
||||
"test_as2.cpp"
|
||||
"test_as_flatten.cpp"
|
||||
"test_box.cpp"
|
||||
"test_custom_class1.cpp"
|
||||
@@ -46,8 +47,11 @@ add_executable(
|
||||
"test_readme_example.cpp"
|
||||
"test_ref.cpp"
|
||||
"test_replace.cpp"
|
||||
"test_replace2.cpp"
|
||||
"test_replace_flatten.cpp"
|
||||
"test_replace_flatten2.cpp"
|
||||
"test_replace_with_other_struct.cpp"
|
||||
"test_replace_with_other_struct2.cpp"
|
||||
"test_result.cpp"
|
||||
"test_save_load.cpp"
|
||||
"test_set.cpp"
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
#include "test_as2.hpp"
|
||||
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
#include <rfl.hpp>
|
||||
#include <rfl/json.hpp>
|
||||
#include <source_location>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "write_and_read.hpp"
|
||||
|
||||
namespace test_as2 {
|
||||
|
||||
struct A {
|
||||
std::string f1;
|
||||
rfl::Box<std::string> f2;
|
||||
};
|
||||
|
||||
struct B {
|
||||
std::string f3;
|
||||
rfl::Box<std::string> f4;
|
||||
};
|
||||
|
||||
struct C {
|
||||
std::string f1;
|
||||
rfl::Box<std::string> f2;
|
||||
rfl::Box<std::string> f4;
|
||||
};
|
||||
|
||||
void test() {
|
||||
std::cout << std::source_location::current().function_name() << std::endl;
|
||||
|
||||
auto a = A{.f1 = "Hello", .f2 = rfl::make_box<std::string>("World")};
|
||||
|
||||
auto b = B{.f3 = "Hello", .f4 = rfl::make_box<std::string>("World")};
|
||||
|
||||
const auto c = rfl::as<C>(std::move(a), std::move(b));
|
||||
|
||||
write_and_read(c, R"({"f1":"Hello","f2":"World","f4":"World"})");
|
||||
}
|
||||
|
||||
} // namespace test_as2
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace test_as2 {
|
||||
void test();
|
||||
}
|
||||
|
||||
@@ -13,19 +13,19 @@
|
||||
namespace test_as_flatten {
|
||||
|
||||
struct A {
|
||||
rfl::Field<"f1", std::string> f1;
|
||||
rfl::Field<"f2", rfl::Box<std::string>> f2;
|
||||
std::string f1;
|
||||
rfl::Box<std::string> f2;
|
||||
};
|
||||
|
||||
struct B {
|
||||
rfl::Field<"f3", std::string> f3;
|
||||
rfl::Field<"f4", rfl::Box<std::string>> f4;
|
||||
std::string f3;
|
||||
rfl::Box<std::string> f4;
|
||||
};
|
||||
|
||||
struct C {
|
||||
rfl::Flatten<A> a;
|
||||
rfl::Flatten<B> b;
|
||||
rfl::Field<"f5", int> f5;
|
||||
int f5;
|
||||
};
|
||||
|
||||
void test() {
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
#include "test_replace2.hpp"
|
||||
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
#include <rfl.hpp>
|
||||
#include <rfl/json.hpp>
|
||||
#include <source_location>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "write_and_read.hpp"
|
||||
|
||||
namespace test_replace2 {
|
||||
|
||||
struct Person {
|
||||
std::string first_name;
|
||||
std::string last_name;
|
||||
rfl::Box<std::vector<Person>> children;
|
||||
};
|
||||
|
||||
void test() {
|
||||
std::cout << std::source_location::current().function_name() << std::endl;
|
||||
|
||||
auto lisa = Person{.first_name = "Lisa",
|
||||
.last_name = "Simpson",
|
||||
.children = rfl::make_box<std::vector<Person>>()};
|
||||
|
||||
const auto maggie = rfl::replace(
|
||||
std::move(lisa), rfl::make_field<"first_name">(std::string("Maggie")));
|
||||
|
||||
write_and_read(
|
||||
maggie, R"({"first_name":"Maggie","last_name":"Simpson","children":[]})");
|
||||
}
|
||||
} // namespace test_replace2
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace test_replace2 {
|
||||
void test();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
#include "test_replace_flatten2.hpp"
|
||||
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
#include <rfl.hpp>
|
||||
#include <rfl/json.hpp>
|
||||
#include <source_location>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "write_and_read.hpp"
|
||||
|
||||
namespace test_replace_flatten2 {
|
||||
|
||||
struct Person {
|
||||
std::string first_name;
|
||||
rfl::Box<std::string> last_name;
|
||||
int age;
|
||||
};
|
||||
|
||||
struct Employee {
|
||||
rfl::Flatten<Person> person;
|
||||
rfl::Box<std::string> employer;
|
||||
float salary;
|
||||
};
|
||||
|
||||
void test() {
|
||||
std::cout << std::source_location::current().function_name() << std::endl;
|
||||
|
||||
auto employee = Employee{
|
||||
.person = Person{.first_name = "Homer",
|
||||
.last_name = rfl::make_box<std::string>("Simpson"),
|
||||
.age = 45},
|
||||
.employer = rfl::make_box<std::string>("Mr. Burns"),
|
||||
.salary = 60000.0};
|
||||
|
||||
auto employee2 =
|
||||
rfl::replace(std::move(employee), rfl::make_field<"salary">(70000.0),
|
||||
rfl::make_field<"age">(46));
|
||||
|
||||
write_and_read(
|
||||
employee2,
|
||||
R"({"first_name":"Homer","last_name":"Simpson","age":46,"employer":"Mr. Burns","salary":70000.0})");
|
||||
}
|
||||
} // namespace test_replace_flatten2
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace test_replace_flatten2 {
|
||||
void test();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
#include "test_replace_with_other_struct2.hpp"
|
||||
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
#include <rfl.hpp>
|
||||
#include <rfl/json.hpp>
|
||||
#include <source_location>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "write_and_read.hpp"
|
||||
|
||||
namespace test_replace_with_other_struct2 {
|
||||
|
||||
struct Person {
|
||||
std::string first_name;
|
||||
std::string last_name;
|
||||
int age;
|
||||
};
|
||||
|
||||
struct Employee {
|
||||
rfl::Flatten<Person> person;
|
||||
std::string employer;
|
||||
float salary;
|
||||
};
|
||||
|
||||
void test() {
|
||||
std::cout << std::source_location::current().function_name() << std::endl;
|
||||
|
||||
const auto employee = Employee{
|
||||
.person =
|
||||
Person{.first_name = "Homer", .last_name = "Simpson", .age = 45},
|
||||
.employer = std::string("Mr. Burns"),
|
||||
.salary = 60000.0};
|
||||
|
||||
const auto carl = Person{.first_name = "Carl", .last_name = "", .age = 45};
|
||||
|
||||
const auto employee2 = rfl::replace(employee, carl);
|
||||
|
||||
write_and_read(
|
||||
employee2,
|
||||
R"({"first_name":"Carl","last_name":"","age":45,"employer":"Mr. Burns","salary":60000.0})");
|
||||
}
|
||||
} // namespace test_replace_with_other_struct2
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace test_replace_with_other_struct2 {
|
||||
void test();
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
#include "test_any_of.hpp"
|
||||
#include "test_array.hpp"
|
||||
#include "test_as.hpp"
|
||||
#include "test_as2.hpp"
|
||||
#include "test_as_flatten.hpp"
|
||||
#include "test_box.hpp"
|
||||
#include "test_custom_class1.hpp"
|
||||
@@ -34,8 +35,11 @@
|
||||
#include "test_readme_example.hpp"
|
||||
#include "test_ref.hpp"
|
||||
#include "test_replace.hpp"
|
||||
#include "test_replace2.hpp"
|
||||
#include "test_replace_flatten.hpp"
|
||||
#include "test_replace_flatten2.hpp"
|
||||
#include "test_replace_with_other_struct.hpp"
|
||||
#include "test_replace_with_other_struct2.hpp"
|
||||
#include "test_result.hpp"
|
||||
#include "test_save_load.hpp"
|
||||
#include "test_set.hpp"
|
||||
@@ -99,9 +103,13 @@ int main() {
|
||||
test_custom_class4::test();
|
||||
|
||||
test_replace::test();
|
||||
test_replace2::test();
|
||||
test_replace_flatten::test();
|
||||
test_replace_flatten2::test();
|
||||
test_replace_with_other_struct::test();
|
||||
test_replace_with_other_struct2::test();
|
||||
test_as::test();
|
||||
test_as2::test();
|
||||
test_as_flatten::test();
|
||||
|
||||
test_custom_constructor::test();
|
||||
|
||||
Reference in New Issue
Block a user