mirror of
https://codeberg.org/DawnMagnet/reflect-cpp
synced 2026-11-29 14:26:19 +08:00
Optimizationg for the reader and writer; #68
This commit is contained in:
@@ -198,19 +198,6 @@ struct Reader {
|
||||
/// Returns an rfl::Error if `_var` cannot be cast as an array.
|
||||
rfl::Result<InputArrayType> to_array(const InputVarType& _var) const noexcept {...}
|
||||
|
||||
/// _fct is a function that turns the field name into the field index of the
|
||||
/// struct. It returns -1, if the fields does not exist on the struct. This
|
||||
/// returns an std::array that can be used to build up the struct.
|
||||
/// See below for a more comprehensive explanation.
|
||||
template <size_t size, class FunctionType>
|
||||
std::array<std::optional<InputVarType>, size> to_fields_array(
|
||||
const FunctionType _fct, const InputObjectType& _obj) const noexcept {...}
|
||||
|
||||
/// Iterates through an object and writes the contained key-value pairs into
|
||||
/// a vector.
|
||||
std::vector<std::pair<std::string, InputVarType>> to_map(
|
||||
const InputObjectType& _obj) const noexcept {...}
|
||||
|
||||
/// Casts _var as an InputObjectType.
|
||||
/// Returns an rfl::Error if `_var` cannot be cast as an object.
|
||||
rfl::Result<InputObjectType> to_object(
|
||||
@@ -220,6 +207,12 @@ struct Reader {
|
||||
/// a std::vector<InputVarType>.
|
||||
std::vector<InputVarType> to_vec(const InputArrayType& _arr) const noexcept {...}
|
||||
|
||||
/// Iterates through an object and inserts the key-value pairs into the object
|
||||
/// reader. See below for a more detailed explanation.
|
||||
template <class ObjectReader>
|
||||
std::optional<Error> read_object(const ObjectReader& _object_reader,
|
||||
const InputObjectType& _obj) const noexcept {...}
|
||||
|
||||
/// Constructs T using its custom constructor. This will only be triggered if
|
||||
/// T was determined to have a custom constructor by
|
||||
/// static constexpr bool has_custom_constructor, as defined above.
|
||||
@@ -234,37 +227,15 @@ struct Reader {
|
||||
};
|
||||
```
|
||||
|
||||
Of these methods, `to_fields_array` probably requires futher explanation.
|
||||
Of these methods, `read_object` probably requires further explanation.
|
||||
|
||||
Consider the following struct:
|
||||
`read_object` expects an `ObjectReader` class which might come in several forms. But all
|
||||
of these forms have a method with the following signature:
|
||||
|
||||
```cpp
|
||||
struct Person {
|
||||
rfl::Rename<"firstName", std::string> first_name;
|
||||
rfl::Rename<"lastName", std::string> last_name;
|
||||
rfl::Timestamp<"%Y-%m-%d"> birthday;
|
||||
std::vector<Person> children;
|
||||
};
|
||||
void read(const std::string_view& _name,
|
||||
const InputVarType& _var) const noexcept;
|
||||
```
|
||||
|
||||
This struct contains four fields. `rfl::parsing::Parser` expects `to_fields_array`
|
||||
to return an `std::array<std::optional<InputVarType>, 4>` containing the field "firstName" in the
|
||||
first position, "lastName" in the second position, "birthday" in the third position
|
||||
and "children" in the fourth position.
|
||||
|
||||
`rfl::parsing::Parser` will pass the following two elements:
|
||||
|
||||
1. A function `_fct` of type `FunctionType`.
|
||||
2. An object `_obj` of type `InputObjectType`.
|
||||
|
||||
`_fct` takes a field name of type `std::string_view` as an input and
|
||||
returns an index. This index signifies the position in the `std::array`
|
||||
it wants this field to have. If the field is not contained in the struct,
|
||||
the index will be -1.
|
||||
|
||||
Your job is to implement the following:
|
||||
|
||||
1. Iterate through `_obj`.
|
||||
2. Identify the required index of the field name using `_fct`.
|
||||
3. Set the corresponding field in `std::array` to the field value associated with the field name.
|
||||
4. Any field that could not be set in steps 1-3 must be set to `std::nullopt`.
|
||||
Within your implementation of `read_object`, you must iterate through the object passed
|
||||
to the function and then insert the resulting key-value-pairs into `object_reader.read`.
|
||||
|
||||
@@ -39,6 +39,9 @@ struct Flatten {
|
||||
|
||||
~Flatten() = default;
|
||||
|
||||
/// Returns the underlying object.
|
||||
Type& get() { return value_; }
|
||||
|
||||
/// Returns the underlying object.
|
||||
const Type& get() const { return value_; }
|
||||
|
||||
|
||||
@@ -40,6 +40,8 @@ class Result {
|
||||
static_assert(!std::is_same<T, Error>(), "The result type cannot be Error.");
|
||||
|
||||
public:
|
||||
using Type = T;
|
||||
|
||||
Result(const T& _val) : t_or_err_(_val) {}
|
||||
|
||||
Result(T&& _val) noexcept : t_or_err_(std::move(_val)) {}
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
#include <exception>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
@@ -127,10 +128,9 @@ struct Reader {
|
||||
return InputArrayType{_var.val_};
|
||||
}
|
||||
|
||||
template <size_t size, class FunctionType>
|
||||
std::array<std::optional<InputVarType>, size> to_fields_array(
|
||||
const FunctionType& _fct, const InputObjectType& _obj) const noexcept {
|
||||
std::array<std::optional<InputVarType>, size> f_arr;
|
||||
template <class ObjectReader>
|
||||
std::optional<Error> read_object(const ObjectReader& _object_reader,
|
||||
const InputObjectType& _obj) const noexcept {
|
||||
bson_t b;
|
||||
bson_iter_t iter;
|
||||
const auto doc = _obj.val_->val_.value.v_doc;
|
||||
@@ -138,31 +138,11 @@ struct Reader {
|
||||
if (bson_iter_init(&iter, &b)) {
|
||||
while (bson_iter_next(&iter)) {
|
||||
const char* k = bson_iter_key(&iter);
|
||||
const auto ix = _fct(std::string_view(k));
|
||||
if (ix != -1) {
|
||||
f_arr[ix] = to_input_var(&iter);
|
||||
}
|
||||
_object_reader.read(std::string_view(k), to_input_var(&iter));
|
||||
}
|
||||
}
|
||||
}
|
||||
return f_arr;
|
||||
}
|
||||
|
||||
rfl::Result<std::vector<std::pair<std::string, InputVarType>>> to_map(
|
||||
const InputObjectType& _obj) const noexcept {
|
||||
std::vector<std::pair<std::string, InputVarType>> map;
|
||||
bson_t b;
|
||||
bson_iter_t iter;
|
||||
const auto doc = _obj.val_->val_.value.v_doc;
|
||||
if (bson_init_static(&b, doc.data, doc.data_len)) {
|
||||
if (bson_iter_init(&iter, &b)) {
|
||||
while (bson_iter_next(&iter)) {
|
||||
auto key = std::string(bson_iter_key(&iter));
|
||||
map.emplace_back(std::make_pair(std::move(key), to_input_var(&iter)));
|
||||
}
|
||||
}
|
||||
}
|
||||
return map;
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
rfl::Result<InputObjectType> to_object(
|
||||
|
||||
+34
-77
@@ -150,83 +150,6 @@ struct Reader {
|
||||
return InputArrayType{_var.val_};
|
||||
}
|
||||
|
||||
template <size_t size, class FunctionType>
|
||||
std::array<std::optional<InputVarType>, size> to_fields_array(
|
||||
const FunctionType& _fct, const InputObjectType& _obj) const noexcept {
|
||||
std::array<std::optional<InputVarType>, size> f_arr;
|
||||
CborValue val;
|
||||
auto buffer = std::vector<char>();
|
||||
auto err = cbor_value_enter_container(_obj.val_, &val);
|
||||
if (err != CborNoError) {
|
||||
return f_arr;
|
||||
}
|
||||
size_t length = 0;
|
||||
err = cbor_value_get_map_length(_obj.val_, &length);
|
||||
if (err != CborNoError) {
|
||||
return f_arr;
|
||||
}
|
||||
for (size_t i = 0; i < length; ++i) {
|
||||
if (!cbor_value_is_text_string(&val)) {
|
||||
err = cbor_value_advance(&val);
|
||||
if (err != CborNoError) {
|
||||
return f_arr;
|
||||
}
|
||||
err = cbor_value_advance(&val);
|
||||
if (err != CborNoError) {
|
||||
return f_arr;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
err = get_string(&val, &buffer);
|
||||
if (err != CborNoError) {
|
||||
return f_arr;
|
||||
}
|
||||
err = cbor_value_advance(&val);
|
||||
if (err != CborNoError) {
|
||||
return f_arr;
|
||||
}
|
||||
const auto ix = _fct(std::string_view(buffer.data()));
|
||||
if (ix != -1) {
|
||||
f_arr[ix] = to_input_var(&val);
|
||||
}
|
||||
err = cbor_value_advance(&val);
|
||||
if (err != CborNoError) {
|
||||
return f_arr;
|
||||
}
|
||||
}
|
||||
return f_arr;
|
||||
}
|
||||
|
||||
rfl::Result<std::vector<std::pair<std::string, InputVarType>>> to_map(
|
||||
const InputObjectType& _obj) const noexcept {
|
||||
std::vector<std::pair<std::string, InputVarType>> map;
|
||||
CborValue val;
|
||||
auto buffer = std::vector<char>();
|
||||
auto err = cbor_value_enter_container(_obj.val_, &val);
|
||||
if (err != CborNoError && err != CborErrorOutOfMemory) {
|
||||
return Error(cbor_error_string(err));
|
||||
}
|
||||
size_t length = 0;
|
||||
cbor_value_get_map_length(_obj.val_, &length);
|
||||
for (size_t i = 0; i < length; ++i) {
|
||||
if (!cbor_value_is_text_string(&val)) {
|
||||
return Error("Expected the key to be a string value.");
|
||||
}
|
||||
err = get_string(&val, &buffer);
|
||||
if (err != CborNoError && err != CborErrorOutOfMemory) {
|
||||
return Error(cbor_error_string(err));
|
||||
}
|
||||
err = cbor_value_advance(&val);
|
||||
if (err != CborNoError && err != CborErrorOutOfMemory) {
|
||||
return Error(cbor_error_string(err));
|
||||
}
|
||||
map.emplace_back(
|
||||
std::make_pair(std::string(buffer.data()), to_input_var(&val)));
|
||||
cbor_value_advance(&val);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
rfl::Result<InputObjectType> to_object(
|
||||
const InputVarType& _var) const noexcept {
|
||||
if (!cbor_value_is_map(_var.val_)) {
|
||||
@@ -258,6 +181,40 @@ struct Reader {
|
||||
return vec;
|
||||
}
|
||||
|
||||
template <class ObjectReader>
|
||||
std::optional<Error> read_object(const ObjectReader& _object_reader,
|
||||
const InputObjectType& _obj) const noexcept {
|
||||
size_t length = 0;
|
||||
auto err = cbor_value_get_map_length(_obj.val_, &length);
|
||||
if (err != CborNoError) {
|
||||
return Error(cbor_error_string(err));
|
||||
}
|
||||
|
||||
CborValue val;
|
||||
err = cbor_value_enter_container(_obj.val_, &val);
|
||||
if (err != CborNoError) {
|
||||
return Error(cbor_error_string(err));
|
||||
}
|
||||
|
||||
auto buffer = std::vector<char>();
|
||||
|
||||
for (size_t i = 0; i < length; ++i) {
|
||||
err = get_string(&val, &buffer);
|
||||
if (err != CborNoError) {
|
||||
return Error(cbor_error_string(err));
|
||||
}
|
||||
err = cbor_value_advance(&val);
|
||||
if (err != CborNoError) {
|
||||
return Error(cbor_error_string(err));
|
||||
}
|
||||
const auto name = std::string_view(buffer.data(), buffer.size() - 1);
|
||||
_object_reader.read(name, InputVarType{&val});
|
||||
cbor_value_advance(&val);
|
||||
}
|
||||
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
template <class T>
|
||||
rfl::Result<T> use_custom_constructor(
|
||||
const InputVarType& _var) const noexcept {
|
||||
|
||||
@@ -84,23 +84,19 @@ struct Reader {
|
||||
}
|
||||
}
|
||||
|
||||
template <size_t size, class FunctionType>
|
||||
std::array<std::optional<InputVarType>, size> to_fields_array(
|
||||
const FunctionType& _fct, const InputObjectType& _obj) const noexcept {
|
||||
std::array<std::optional<InputVarType>, size> f_arr;
|
||||
|
||||
template <class ObjectReader>
|
||||
std::optional<Error> read_object(const ObjectReader& _object_reader,
|
||||
const InputObjectType& _obj) const noexcept {
|
||||
const auto keys = _obj.Keys();
|
||||
const auto values = _obj.Values();
|
||||
const auto num_values = std::min(keys.size(), values.size());
|
||||
|
||||
for (size_t i = 0; i < num_values; ++i) {
|
||||
const auto ix = _fct(std::string_view(keys[i].AsString().c_str()));
|
||||
if (ix != -1) {
|
||||
f_arr[ix] = values[i];
|
||||
}
|
||||
_object_reader.read(std::string_view(keys[i].AsString().c_str()),
|
||||
values[i]);
|
||||
}
|
||||
|
||||
return f_arr;
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
rfl::Result<InputArrayType> to_array(
|
||||
@@ -111,22 +107,6 @@ struct Reader {
|
||||
return _var.AsVector();
|
||||
}
|
||||
|
||||
rfl::Result<std::vector<std::pair<std::string, InputVarType>>> to_map(
|
||||
const InputObjectType& _obj) const noexcept {
|
||||
std::vector<std::pair<std::string, InputVarType>> m;
|
||||
|
||||
const auto keys = _obj.Keys();
|
||||
const auto values = _obj.Values();
|
||||
const auto size = std::min(keys.size(), values.size());
|
||||
|
||||
for (size_t i = 0; i < size; ++i) {
|
||||
m.emplace_back(
|
||||
std::make_pair(std::string(keys[i].AsString().c_str()), values[i]));
|
||||
}
|
||||
|
||||
return m;
|
||||
}
|
||||
|
||||
rfl::Result<InputObjectType> to_object(
|
||||
const InputVarType& _var) const noexcept {
|
||||
if (!_var.IsMap()) {
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
#define RFL_INTERNAL_ARRAY_HPP_
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <type_traits>
|
||||
|
||||
#include "to_std_array.hpp"
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
#ifndef RFL_INTERNAL_ISARRAY_HPP_
|
||||
#define RFL_INTERNAL_ISARRAY_HPP_
|
||||
|
||||
#include <tuple>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
|
||||
#include "Array.hpp"
|
||||
|
||||
namespace rfl::internal {
|
||||
|
||||
template <class T>
|
||||
class is_array;
|
||||
|
||||
template <class T>
|
||||
class is_array : public std::false_type {};
|
||||
|
||||
template <class Type>
|
||||
class is_array<Array<Type>> : public std::true_type {};
|
||||
|
||||
template <class T>
|
||||
constexpr bool is_array_v =
|
||||
is_array<std::remove_cvref_t<std::remove_pointer_t<T>>>::value;
|
||||
|
||||
} // namespace rfl::internal
|
||||
|
||||
#endif
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
#include "../always_false.hpp"
|
||||
#include "../field_names_t.hpp"
|
||||
#include "../make_named_tuple.hpp"
|
||||
#include "copy_flattened_tuple_to_named_tuple.hpp"
|
||||
#include "has_fields.hpp"
|
||||
#include "has_flatten_fields.hpp"
|
||||
@@ -13,7 +14,6 @@
|
||||
#include "is_named_tuple.hpp"
|
||||
#include "to_flattened_ptr_tuple.hpp"
|
||||
#include "to_ptr_field_tuple.hpp"
|
||||
#include "../make_named_tuple.hpp"
|
||||
|
||||
namespace rfl {
|
||||
namespace internal {
|
||||
@@ -26,8 +26,7 @@ auto flatten_ptr_field_tuple(PtrFieldTuple& _t, Args&&... _args) {
|
||||
} else {
|
||||
using T = std::tuple_element_t<i, std::remove_cvref_t<PtrFieldTuple>>;
|
||||
if constexpr (internal::is_flatten_field<T>::value) {
|
||||
const auto subtuple =
|
||||
internal::to_ptr_field_tuple(*std::get<i>(_t).get());
|
||||
auto subtuple = internal::to_ptr_field_tuple(*std::get<i>(_t).get());
|
||||
return flatten_ptr_field_tuple(_t, std::forward<Args>(_args)...,
|
||||
flatten_ptr_field_tuple(subtuple));
|
||||
} else {
|
||||
@@ -39,7 +38,7 @@ auto flatten_ptr_field_tuple(PtrFieldTuple& _t, Args&&... _args) {
|
||||
|
||||
template <class PtrFieldTuple>
|
||||
auto field_tuple_to_named_tuple(PtrFieldTuple& _ptr_field_tuple) {
|
||||
const auto ft_to_nt = []<class... Fields>(const Fields&... _fields) {
|
||||
const auto ft_to_nt = []<class... Fields>(Fields&&... _fields) {
|
||||
return make_named_tuple(_fields...);
|
||||
};
|
||||
|
||||
|
||||
@@ -15,9 +15,7 @@ constexpr auto to_ptr_tuple(T& _t) {
|
||||
if constexpr (std::is_pointer_v<std::remove_cvref_t<T>>) {
|
||||
return to_ptr_tuple(*_t);
|
||||
} else {
|
||||
return bind_to_tuple(_t, [](auto&& x) {
|
||||
return std::addressof(std::forward<decltype(x)>(x));
|
||||
});
|
||||
return bind_to_tuple(_t, [](auto& x) { return &x; });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+13
-31
@@ -96,37 +96,6 @@ struct Reader {
|
||||
return InputArrayType(_var.val_);
|
||||
}
|
||||
|
||||
template <size_t size, class FunctionType>
|
||||
std::array<std::optional<InputVarType>, size> to_fields_array(
|
||||
const FunctionType _fct, const InputObjectType _obj) const noexcept {
|
||||
std::array<std::optional<InputVarType>, size> f_arr;
|
||||
yyjson_obj_iter iter;
|
||||
yyjson_obj_iter_init(_obj.val_, &iter);
|
||||
yyjson_val* key;
|
||||
while ((key = yyjson_obj_iter_next(&iter))) {
|
||||
const char* k = yyjson_get_str(key);
|
||||
const auto ix = _fct(std::string_view(k));
|
||||
if (ix != -1) {
|
||||
f_arr[ix] = InputVarType(yyjson_obj_iter_get_val(key));
|
||||
}
|
||||
}
|
||||
return f_arr;
|
||||
}
|
||||
|
||||
rfl::Result<std::vector<std::pair<std::string, InputVarType>>> to_map(
|
||||
const InputObjectType _obj) const noexcept {
|
||||
std::vector<std::pair<std::string, InputVarType>> m;
|
||||
yyjson_obj_iter iter;
|
||||
yyjson_obj_iter_init(_obj.val_, &iter);
|
||||
yyjson_val* key;
|
||||
while ((key = yyjson_obj_iter_next(&iter))) {
|
||||
auto p = std::make_pair(yyjson_get_str(key),
|
||||
InputVarType(yyjson_obj_iter_get_val(key)));
|
||||
m.emplace_back(std::move(p));
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
rfl::Result<InputObjectType> to_object(
|
||||
const InputVarType _var) const noexcept {
|
||||
if (!yyjson_is_obj(_var.val_)) {
|
||||
@@ -146,6 +115,19 @@ struct Reader {
|
||||
return vec;
|
||||
}
|
||||
|
||||
template <class ObjectReader>
|
||||
std::optional<Error> read_object(const ObjectReader& _object_reader,
|
||||
const InputObjectType& _obj) const noexcept {
|
||||
yyjson_obj_iter iter;
|
||||
yyjson_obj_iter_init(_obj.val_, &iter);
|
||||
yyjson_val* key;
|
||||
while ((key = yyjson_obj_iter_next(&iter))) {
|
||||
const auto name = std::string_view(yyjson_get_str(key));
|
||||
_object_reader.read(name, InputVarType(yyjson_obj_iter_get_val(key)));
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
template <class T>
|
||||
rfl::Result<T> use_custom_constructor(
|
||||
const InputVarType _var) const noexcept {
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
|
||||
#include "../Result.hpp"
|
||||
#include "../always_false.hpp"
|
||||
#include "FieldVariantReader.hpp"
|
||||
#include "Parser_base.hpp"
|
||||
#include "schema/Type.hpp"
|
||||
|
||||
@@ -20,7 +21,8 @@ namespace parsing {
|
||||
template <class R, class W, class... FieldTypes>
|
||||
requires AreReaderAndWriter<R, W, std::variant<FieldTypes...>>
|
||||
struct FieldVariantParser {
|
||||
using ResultType = Result<std::variant<FieldTypes...>>;
|
||||
using FieldVariantType = std::variant<FieldTypes...>;
|
||||
using ResultType = Result<FieldVariantType>;
|
||||
|
||||
public:
|
||||
using InputObjectType = typename R::InputObjectType;
|
||||
@@ -35,22 +37,23 @@ struct FieldVariantParser {
|
||||
"Externally tagged variants cannot have duplicate field "
|
||||
"names.");
|
||||
|
||||
const auto to_map = [&](auto _obj) { return _r.to_map(_obj); };
|
||||
|
||||
const auto to_result = [&](auto _map) -> ResultType {
|
||||
if (_map.size() != 1) {
|
||||
return Error(
|
||||
"Could not parse Field: Expected the object to have "
|
||||
"exactly one field, but found " +
|
||||
std::to_string(_map.size()) + " fields.");
|
||||
const auto to_result = [&](const auto _obj) -> ResultType {
|
||||
auto field_variant = std::optional<Result<FieldVariantType>>();
|
||||
const auto reader =
|
||||
FieldVariantReader<R, W, FieldTypes...>(&_r, &field_variant);
|
||||
auto err = _r.read_object(reader, _obj);
|
||||
if (err) {
|
||||
return *err;
|
||||
}
|
||||
const auto it = _map.begin();
|
||||
const auto& disc_value = it->first;
|
||||
const auto& var = it->second;
|
||||
return find_matching_alternative(_r, disc_value, var);
|
||||
if (!field_variant) {
|
||||
return Error(
|
||||
"Could not parse: Expected the object to have "
|
||||
"exactly one field, but found more than one.");
|
||||
}
|
||||
return std::move(*field_variant);
|
||||
};
|
||||
|
||||
return _r.to_object(_var).and_then(to_map).and_then(to_result);
|
||||
return _r.to_object(_var).and_then(to_result);
|
||||
}
|
||||
|
||||
template <class P>
|
||||
@@ -76,43 +79,6 @@ struct FieldVariantParser {
|
||||
using VariantType = std::variant<NamedTuple<FieldTypes>...>;
|
||||
return Parser<R, W, VariantType>::to_schema(_definitions);
|
||||
}
|
||||
|
||||
private:
|
||||
template <int _i = 0>
|
||||
static ResultType find_matching_alternative(
|
||||
const R& _r, const std::string& _disc_value,
|
||||
const InputVarType& _var) noexcept {
|
||||
if constexpr (_i == sizeof...(FieldTypes)) {
|
||||
return Error(
|
||||
"Could not parse std::variant, could not match field named "
|
||||
"'" +
|
||||
_disc_value + "'.");
|
||||
} else {
|
||||
using FieldType = std::remove_cvref_t<
|
||||
typename std::tuple_element<_i, std::tuple<FieldTypes...>>::type>;
|
||||
|
||||
using ValueType = std::remove_cvref_t<typename FieldType::Type>;
|
||||
|
||||
const auto key = FieldType::name_.str();
|
||||
|
||||
if (key == _disc_value) {
|
||||
const auto to_variant = [](ValueType&& _val) {
|
||||
return std::variant<FieldTypes...>(FieldType(std::move(_val)));
|
||||
};
|
||||
|
||||
const auto embellish_error = [&](const Error& _e) {
|
||||
return Error("Could not parse std::variant with field '" +
|
||||
_disc_value + "': " + _e.what());
|
||||
};
|
||||
|
||||
return Parser<R, W, ValueType>::read(_r, _var)
|
||||
.transform(to_variant)
|
||||
.or_else(embellish_error);
|
||||
} else {
|
||||
return find_matching_alternative<_i + 1>(_r, _disc_value, _var);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
} // namespace parsing
|
||||
} // namespace rfl
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
#ifndef RFL_PARSING_FIELDVARIANTREADER_HPP_
|
||||
#define RFL_PARSING_FIELDVARIANTREADER_HPP_
|
||||
|
||||
#include <array>
|
||||
#include <optional>
|
||||
#include <string_view>
|
||||
#include <type_traits>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
#include "../Result.hpp"
|
||||
#include "../internal/is_array.hpp"
|
||||
|
||||
namespace rfl::parsing {
|
||||
|
||||
template <class R, class W, class... FieldTypes>
|
||||
class FieldVariantReader {
|
||||
private:
|
||||
using InputVarType = typename R::InputVarType;
|
||||
using FieldVariantType = std::variant<FieldTypes...>;
|
||||
using ResultType = Result<FieldVariantType>;
|
||||
|
||||
public:
|
||||
FieldVariantReader(const R* _r,
|
||||
std::optional<Result<FieldVariantType>>* _field_variant)
|
||||
: r_(_r), field_variant_(_field_variant) {}
|
||||
|
||||
~FieldVariantReader() = default;
|
||||
|
||||
template <size_t _i = 0>
|
||||
void read(const std::string_view& _disc_value,
|
||||
const InputVarType& _var) const noexcept {
|
||||
if constexpr (_i < sizeof...(FieldTypes)) {
|
||||
if constexpr (_i == 0) {
|
||||
if (*field_variant_) {
|
||||
*field_variant_ = Error(
|
||||
"Could not parse: Expected the object to have "
|
||||
"exactly one field, but found more than one.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
using FieldType = std::remove_cvref_t<
|
||||
typename std::tuple_element<_i, std::tuple<FieldTypes...>>::type>;
|
||||
|
||||
using ValueType = std::remove_cvref_t<typename FieldType::Type>;
|
||||
|
||||
constexpr auto key = FieldType::name_.string_view();
|
||||
|
||||
if (key == _disc_value) {
|
||||
const auto to_variant = [](ValueType&& _val) {
|
||||
return std::variant<FieldTypes...>(FieldType(std::move(_val)));
|
||||
};
|
||||
const auto embellish_error = [&](const Error& _e) {
|
||||
return Error("Could not parse std::variant with field '" +
|
||||
std::string(_disc_value) + "': " + _e.what());
|
||||
};
|
||||
*field_variant_ = Parser<R, W, ValueType>::read(*r_, _var)
|
||||
.transform(to_variant)
|
||||
.or_else(embellish_error);
|
||||
return;
|
||||
} else {
|
||||
read<_i + 1>(_disc_value, _var);
|
||||
}
|
||||
} else {
|
||||
*field_variant_ = Error(
|
||||
"Could not parse std::variant, could not match field named "
|
||||
"'" +
|
||||
std::string(_disc_value) + "'.");
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
/// The underlying reader.
|
||||
const R* r_;
|
||||
|
||||
/// The underlying field variant.
|
||||
std::optional<Result<FieldVariantType>>* field_variant_;
|
||||
};
|
||||
|
||||
} // namespace rfl::parsing
|
||||
|
||||
#endif
|
||||
@@ -16,9 +16,16 @@
|
||||
namespace rfl {
|
||||
namespace parsing {
|
||||
|
||||
template <class R>
|
||||
struct MockObjectReader {
|
||||
void read(const std::string_view& _name,
|
||||
typename R::InputVarType& _var) const {}
|
||||
};
|
||||
|
||||
template <class R, class T>
|
||||
concept IsReader = requires(R r, std::string name,
|
||||
std::function<std::int16_t(std::string_view)> fct,
|
||||
MockObjectReader<R> object_reader,
|
||||
typename R::InputArrayType arr,
|
||||
typename R::InputObjectType obj,
|
||||
typename R::InputVarType var) {
|
||||
@@ -41,29 +48,20 @@ concept IsReader = requires(R r, std::string name,
|
||||
/// Determines whether a variable is empty (the NULL type).
|
||||
{ r.is_empty(var) } -> std::same_as<bool>;
|
||||
|
||||
/// Iterates through an object and writes the key-value pairs into a view.
|
||||
/// This is what we use to handle structs and named tuples, making it a very
|
||||
/// important function.
|
||||
{ r.read_object(object_reader, obj) } -> std::same_as<std::optional<Error>>;
|
||||
|
||||
/// Transforms var to a basic type (bool, integral,
|
||||
/// floating point, std::string)
|
||||
{
|
||||
r.template to_basic_type<internal::wrap_in_rfl_array_t<T>>(var)
|
||||
} -> std::same_as<rfl::Result<internal::wrap_in_rfl_array_t<T>>>;
|
||||
|
||||
/// _fct is a function that turns the field name into the field index of the
|
||||
/// struct. It returns -1, if the fields does not exist on the struct. This
|
||||
/// returns an std::array that can be used to build up the struct.
|
||||
{
|
||||
r.template to_fields_array<6>(fct, obj)
|
||||
} -> std::same_as<std::array<std::optional<typename R::InputVarType>, 6>>;
|
||||
|
||||
/// Casts var as an InputArrayType.
|
||||
{ r.to_array(var) } -> std::same_as<rfl::Result<typename R::InputArrayType>>;
|
||||
|
||||
/// Iterates through an object and writes the contained key-value pairs into
|
||||
/// a vector.
|
||||
{
|
||||
r.to_map(obj)
|
||||
} -> std::same_as<rfl::Result<
|
||||
std::vector<std::pair<std::string, typename R::InputVarType>>>>;
|
||||
|
||||
/// Casts var as an InputObjectType.
|
||||
{
|
||||
r.to_object(var)
|
||||
|
||||
@@ -9,9 +9,11 @@
|
||||
#include "../Ref.hpp"
|
||||
#include "../Result.hpp"
|
||||
#include "../always_false.hpp"
|
||||
#include "MapReader.hpp"
|
||||
#include "Parent.hpp"
|
||||
#include "Parser_base.hpp"
|
||||
#include "schema/Type.hpp"
|
||||
#include "to_single_error_message.hpp"
|
||||
|
||||
namespace rfl {
|
||||
namespace parsing {
|
||||
@@ -33,7 +35,9 @@ struct MapParser {
|
||||
using ParentType = Parent<W>;
|
||||
|
||||
static Result<MapType> read(const R& _r, const InputVarType& _var) noexcept {
|
||||
const auto to_map = [&](const auto& _obj) { return make_map(_r, _obj); };
|
||||
const auto to_map = [&](auto obj) -> Result<MapType> {
|
||||
return make_map(_r, obj);
|
||||
};
|
||||
return _r.to_object(_var).and_then(to_map);
|
||||
}
|
||||
|
||||
@@ -77,72 +81,18 @@ struct MapParser {
|
||||
}
|
||||
|
||||
private:
|
||||
template <class T>
|
||||
static Result<T> key_to_numeric(auto& _pair) noexcept {
|
||||
try {
|
||||
if constexpr (std::is_integral_v<T>) {
|
||||
return static_cast<T>(std::stoi(_pair.first));
|
||||
} else if constexpr (std::is_floating_point_v<T>) {
|
||||
return static_cast<T>(std::stod(_pair.first));
|
||||
} else {
|
||||
static_assert(always_false_v<T>, "Unsupported type");
|
||||
}
|
||||
} catch (std::exception& e) {
|
||||
return Error(e.what());
|
||||
static Result<MapType> make_map(const R& _r, const InputObjectType& _obj) {
|
||||
MapType map;
|
||||
std::vector<Error> errors;
|
||||
const auto map_reader = MapReader<R, W, MapType>(&_r, &map, &errors);
|
||||
const auto err = _r.read_object(map_reader, _obj);
|
||||
if (err) {
|
||||
return *err;
|
||||
}
|
||||
}
|
||||
|
||||
static Result<std::pair<KeyType, ValueType>> make_key(auto& _pair) noexcept {
|
||||
const auto to_pair = [&](auto _key) {
|
||||
return std::make_pair(KeyType(std::move(_key)), std::move(_pair.second));
|
||||
};
|
||||
|
||||
if constexpr (std::is_integral_v<KeyType> ||
|
||||
std::is_floating_point_v<KeyType>) {
|
||||
return key_to_numeric<KeyType>(_pair).transform(to_pair);
|
||||
|
||||
} else if constexpr (internal::has_reflection_type_v<KeyType>) {
|
||||
using ReflT = typename KeyType::ReflectionType;
|
||||
|
||||
if constexpr (std::is_integral_v<ReflT> ||
|
||||
std::is_floating_point_v<ReflT>) {
|
||||
return key_to_numeric<ReflT>(_pair).transform(to_pair);
|
||||
} else {
|
||||
return to_pair(_pair.first);
|
||||
}
|
||||
|
||||
} else {
|
||||
return std::move(_pair);
|
||||
if (errors.size() != 0) {
|
||||
return to_single_error_message(errors);
|
||||
}
|
||||
}
|
||||
|
||||
static std::pair<KeyType, ValueType> get_pair(const R& _r, auto& _pair) {
|
||||
const auto to_pair = [&](ValueType&& _val) {
|
||||
auto pair = std::make_pair(std::move(_pair.first), std::move(_val));
|
||||
return make_key(pair);
|
||||
};
|
||||
return Parser<R, W, std::remove_cvref_t<ValueType>>::read(_r, _pair.second)
|
||||
.and_then(to_pair)
|
||||
.value();
|
||||
}
|
||||
|
||||
static Result<MapType> iterate_map(const R& _r, const auto& _map) noexcept {
|
||||
MapType res;
|
||||
try {
|
||||
for (auto& p : _map) {
|
||||
res.insert(get_pair(_r, p));
|
||||
}
|
||||
} catch (std::exception& e) {
|
||||
return Error(e.what());
|
||||
}
|
||||
return res;
|
||||
};
|
||||
|
||||
static Result<MapType> make_map(const R& _r, const auto& _obj) noexcept {
|
||||
const auto iterate = [&](const auto& _map) {
|
||||
return iterate_map(_r, _map);
|
||||
};
|
||||
return _r.to_map(_obj).and_then(iterate);
|
||||
return map;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
#ifndef RFL_PARSING_MAPREADER_HPP_
|
||||
#define RFL_PARSING_MAPREADER_HPP_
|
||||
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "../Result.hpp"
|
||||
#include "../always_false.hpp"
|
||||
|
||||
namespace rfl::parsing {
|
||||
|
||||
template <class R, class W, class MapType>
|
||||
class MapReader {
|
||||
private:
|
||||
using InputVarType = typename R::InputVarType;
|
||||
using KeyType = std::remove_cvref_t<typename MapType::value_type::first_type>;
|
||||
using ValueType =
|
||||
std::remove_cvref_t<typename MapType::value_type::second_type>;
|
||||
|
||||
public:
|
||||
MapReader(const R* _r, MapType* _map, std::vector<Error>* _errors)
|
||||
: r_(_r), map_(_map), errors_(_errors) {}
|
||||
|
||||
~MapReader() = default;
|
||||
|
||||
void read(const std::string_view& _name,
|
||||
const InputVarType& _var) const noexcept {
|
||||
auto res = get_pair(_name, _var);
|
||||
if (res) {
|
||||
map_->emplace(std::move(*res));
|
||||
} else {
|
||||
errors_->push_back(Error("Failed to parse field '" + std::string(_name) +
|
||||
"': " + res.error()->what()));
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
template <class T>
|
||||
Result<T> key_to_numeric(auto& _pair) const noexcept {
|
||||
try {
|
||||
if constexpr (std::is_integral_v<T>) {
|
||||
return static_cast<T>(std::stoi(_pair.first));
|
||||
} else if constexpr (std::is_floating_point_v<T>) {
|
||||
return static_cast<T>(std::stod(_pair.first));
|
||||
} else {
|
||||
static_assert(always_false_v<T>, "Unsupported type");
|
||||
}
|
||||
} catch (std::exception& e) {
|
||||
return Error(e.what());
|
||||
}
|
||||
}
|
||||
|
||||
Result<std::pair<KeyType, ValueType>> make_key(auto& _pair) const noexcept {
|
||||
const auto to_pair =
|
||||
[&](auto _key) -> Result<std::pair<KeyType, ValueType>> {
|
||||
try {
|
||||
return std::make_pair(KeyType(std::move(_key)),
|
||||
std::move(_pair.second));
|
||||
} catch (std::exception& e) {
|
||||
return Error(e.what());
|
||||
}
|
||||
};
|
||||
|
||||
if constexpr (std::is_integral_v<KeyType> ||
|
||||
std::is_floating_point_v<KeyType>) {
|
||||
return key_to_numeric<KeyType>(_pair).and_then(to_pair);
|
||||
|
||||
} else if constexpr (internal::has_reflection_type_v<KeyType>) {
|
||||
using ReflT = typename KeyType::ReflectionType;
|
||||
|
||||
if constexpr (std::is_integral_v<ReflT> ||
|
||||
std::is_floating_point_v<ReflT>) {
|
||||
return key_to_numeric<ReflT>(_pair).and_then(to_pair);
|
||||
} else {
|
||||
return to_pair(_pair.first);
|
||||
}
|
||||
|
||||
} else {
|
||||
return std::move(_pair);
|
||||
}
|
||||
}
|
||||
|
||||
Result<std::pair<KeyType, ValueType>> get_pair(
|
||||
const std::string_view& _name, const InputVarType& _var) const noexcept {
|
||||
const auto to_pair = [&](ValueType&& _val) {
|
||||
auto pair = std::make_pair(std::string(_name), std::move(_val));
|
||||
return make_key(pair);
|
||||
};
|
||||
return Parser<R, W, std::remove_cvref_t<ValueType>>::read(*r_, _var)
|
||||
.and_then(to_pair);
|
||||
}
|
||||
|
||||
private:
|
||||
/// The underlying reader.
|
||||
const R* r_;
|
||||
|
||||
/// The underlying map.
|
||||
MapType* map_;
|
||||
|
||||
/// Collects any errors we may have come across.
|
||||
std::vector<Error>* errors_;
|
||||
};
|
||||
|
||||
} // namespace rfl::parsing
|
||||
|
||||
#endif
|
||||
@@ -1,6 +1,7 @@
|
||||
#ifndef RFL_PARSING_NAMEDTUPLEPARSER_HPP_
|
||||
#define RFL_PARSING_NAMEDTUPLEPARSER_HPP_
|
||||
|
||||
#include <array>
|
||||
#include <map>
|
||||
#include <tuple>
|
||||
#include <type_traits>
|
||||
@@ -10,15 +11,19 @@
|
||||
#include "../Result.hpp"
|
||||
#include "../always_false.hpp"
|
||||
#include "../internal/Memoization.hpp"
|
||||
#include "../internal/is_array.hpp"
|
||||
#include "../internal/is_attribute.hpp"
|
||||
#include "../internal/is_basic_type.hpp"
|
||||
#include "../internal/strings/replace_all.hpp"
|
||||
#include "../to_view.hpp"
|
||||
#include "AreReaderAndWriter.hpp"
|
||||
#include "Parent.hpp"
|
||||
#include "Parser_base.hpp"
|
||||
#include "ViewReader.hpp"
|
||||
#include "is_empty.hpp"
|
||||
#include "is_required.hpp"
|
||||
#include "schema/Type.hpp"
|
||||
#include "to_single_error_message.hpp"
|
||||
|
||||
namespace rfl {
|
||||
namespace parsing {
|
||||
@@ -35,23 +40,42 @@ struct NamedTupleParser {
|
||||
|
||||
using ParentType = Parent<W>;
|
||||
|
||||
using NamedTupleType = NamedTuple<FieldTypes...>;
|
||||
|
||||
static constexpr size_t size_ = NamedTupleType::size();
|
||||
|
||||
public:
|
||||
/// The way this works is that we allocate space on the stack in this size of
|
||||
/// the named tuple in which we then write the individual fields using
|
||||
/// views and placement new. This is how we deal with the fact that some
|
||||
/// fields might not be default-constructible.
|
||||
static Result<NamedTuple<FieldTypes...>> 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<sizeof...(FieldTypes)>(fct, _obj);
|
||||
};
|
||||
const auto build = [&](auto _fields_vec) {
|
||||
return build_named_tuple_recursively(_r, _fields_vec);
|
||||
};
|
||||
return _r.to_object(_var).transform(to_fields_array).and_then(build);
|
||||
alignas(NamedTuple<FieldTypes...>) unsigned char
|
||||
buf[sizeof(NamedTuple<FieldTypes...>)];
|
||||
auto ptr = reinterpret_cast<NamedTuple<FieldTypes...>*>(buf);
|
||||
const auto view = rfl::to_view(*ptr);
|
||||
using ViewType = std::remove_cvref_t<decltype(view)>;
|
||||
const auto err = Parser<R, W, ViewType>::read_view(_r, _var, view);
|
||||
if (err) {
|
||||
return *err;
|
||||
}
|
||||
return *ptr;
|
||||
}
|
||||
|
||||
/// Reads the data into a view.
|
||||
static std::optional<Error> read_view(
|
||||
const R& _r, const InputVarType& _var,
|
||||
const NamedTuple<FieldTypes...>& _view) noexcept {
|
||||
const auto obj = _r.to_object(_var);
|
||||
if (obj) {
|
||||
return read_object(_r, *obj, _view);
|
||||
}
|
||||
return obj.error();
|
||||
}
|
||||
|
||||
/// For writing, we do not need to make the distinction between
|
||||
/// default-constructible and non-default constructible fields.
|
||||
template <class P>
|
||||
static void write(const W& _w, const NamedTuple<FieldTypes...>& _tup,
|
||||
const P& _parent) noexcept {
|
||||
@@ -60,6 +84,8 @@ struct NamedTupleParser {
|
||||
_w.end_object(&obj);
|
||||
}
|
||||
|
||||
/// For generating the schema, we also do not need to make the distinction
|
||||
/// between default-constructible and non-default constructible fields.
|
||||
template <size_t _i = 0>
|
||||
static schema::Type to_schema(
|
||||
std::map<std::string, schema::Type>* _definitions,
|
||||
@@ -78,104 +104,6 @@ struct NamedTupleParser {
|
||||
};
|
||||
|
||||
private:
|
||||
/// Builds the named tuple field by field.
|
||||
template <class... Args>
|
||||
static Result<NamedTuple<FieldTypes...>> build_named_tuple_recursively(
|
||||
const R& _r,
|
||||
const std::array<std::optional<InputVarType>, sizeof...(FieldTypes)>&
|
||||
_fields_arr,
|
||||
Args&&... _args) noexcept {
|
||||
constexpr auto i = sizeof...(Args);
|
||||
|
||||
if constexpr (i == sizeof...(FieldTypes)) {
|
||||
return NamedTuple<FieldTypes...>(std::move(_args)...);
|
||||
} else {
|
||||
using FieldType = typename std::tuple_element<
|
||||
i, typename NamedTuple<FieldTypes...>::Fields>::type;
|
||||
|
||||
using ValueType = std::remove_cvref_t<typename FieldType::Type>;
|
||||
|
||||
const auto& f = std::get<i>(_fields_arr);
|
||||
|
||||
if (!f) {
|
||||
if constexpr (_all_required ||
|
||||
is_required<ValueType, _ignore_empty_containers>()) {
|
||||
const auto key = FieldType::name_.str();
|
||||
return collect_errors<i + 1>(
|
||||
_r, _fields_arr,
|
||||
std::vector<Error>(
|
||||
{Error("Field named '" + key + "' not found!")}));
|
||||
} else {
|
||||
return build_named_tuple_recursively(
|
||||
_r, _fields_arr, std::move(_args)..., FieldType(ValueType()));
|
||||
}
|
||||
}
|
||||
|
||||
const auto build = [&](auto&& _value) {
|
||||
return build_named_tuple_recursively(
|
||||
_r, _fields_arr, std::move(_args)..., FieldType(std::move(_value)));
|
||||
};
|
||||
|
||||
const auto handle_error = [&](Error&& _error) {
|
||||
return collect_errors<i + 1>(_r, _fields_arr,
|
||||
std::vector<Error>({std::move(_error)}));
|
||||
};
|
||||
|
||||
return get_value<FieldType>(_r, *f).or_else(handle_error).and_then(build);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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>, sizeof...(FieldTypes)>&
|
||||
_fields_arr,
|
||||
std::vector<Error> _errors) noexcept {
|
||||
if constexpr (_i == sizeof...(FieldTypes)) {
|
||||
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) + ") " +
|
||||
internal::strings::replace_all(_errors.at(i).what(), "\n",
|
||||
"\n ");
|
||||
}
|
||||
return Error(msg);
|
||||
}
|
||||
} else {
|
||||
using FieldType = typename std::tuple_element<
|
||||
_i, typename NamedTuple<FieldTypes...>::Fields>::type;
|
||||
|
||||
using ValueType = std::remove_cvref_t<typename FieldType::Type>;
|
||||
|
||||
const auto& f = std::get<_i>(_fields_arr);
|
||||
|
||||
if (!f) {
|
||||
if constexpr (_all_required ||
|
||||
is_required<ValueType, _ignore_empty_containers>()) {
|
||||
const auto key = FieldType::name_.str();
|
||||
_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<FieldType>(_r, *f).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 NamedTuple<FieldTypes...>& _tup,
|
||||
@@ -210,50 +138,95 @@ struct NamedTupleParser {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 field_indices_.value(set_field_indices<0>);
|
||||
}
|
||||
|
||||
/// Retrieves the value from the object. This is mainly needed to
|
||||
/// generate a better error message.
|
||||
template <class FieldType>
|
||||
static auto get_value(const R& _r, const InputVarType _var) noexcept {
|
||||
static_assert(FieldType::name_ != internal::StringLiteral("xml_content") ||
|
||||
internal::is_basic_type_v<typename FieldType::Type>,
|
||||
"xml_content must be a string, a boolean, a floating point "
|
||||
"value or integral.");
|
||||
const auto embellish_error = [&](const Error& _e) {
|
||||
const auto key = FieldType::name_.str();
|
||||
return Error("Failed to parse field '" + key + "': " + _e.what());
|
||||
};
|
||||
using ValueType = std::remove_cvref_t<typename FieldType::Type>;
|
||||
return Parser<R, W, ValueType>::read(_r, _var).or_else(embellish_error);
|
||||
}
|
||||
|
||||
/// Builds the object field by field.
|
||||
template <size_t _i = 0>
|
||||
static void set_field_indices(
|
||||
std::unordered_map<std::string_view, std::int16_t>*
|
||||
_field_indices) noexcept {
|
||||
if constexpr (_i >= sizeof...(FieldTypes)) {
|
||||
return;
|
||||
} else {
|
||||
using FieldType =
|
||||
typename std::tuple_element<_i, std::tuple<FieldTypes...>>::type;
|
||||
const auto name = FieldType::name_.string_view();
|
||||
(*_field_indices)[name] = static_cast<std::int16_t>(_i);
|
||||
set_field_indices<_i + 1>(_field_indices);
|
||||
/// C-arrays need special handling here.
|
||||
template <class T>
|
||||
static void call_destructor_on_array(const size_t _size, T* _ptr) {
|
||||
for (size_t i = 0; i < _size; ++i) {
|
||||
if constexpr (std::is_array_v<T>) {
|
||||
call_destructor_on_array(sizeof(*_ptr) / sizeof(**_ptr), *(_ptr + i));
|
||||
} else if constexpr (std::is_destructible_v<T>) {
|
||||
(_ptr + i)->~T();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
/// Maps each of the field names to an index signifying their order.
|
||||
static inline internal::Memoization<
|
||||
std::unordered_map<std::string_view, std::int16_t>>
|
||||
field_indices_;
|
||||
/// Because of the way we have allocated the fields, we need to manually
|
||||
/// trigger the destructors.
|
||||
template <size_t _i = 0>
|
||||
static void call_destructors_where_necessary(
|
||||
const NamedTupleType& _view, const std::array<bool, size_>& _set) {
|
||||
using FieldType = std::tuple_element_t<_i, typename NamedTupleType::Fields>;
|
||||
using ValueType =
|
||||
std::remove_cvref_t<std::remove_pointer_t<typename FieldType::Type>>;
|
||||
if constexpr (!std::is_array_v<ValueType> &&
|
||||
std::is_destructible_v<ValueType>) {
|
||||
if (std::get<_i>(_set)) {
|
||||
rfl::get<_i>(_view)->~ValueType();
|
||||
}
|
||||
} else if constexpr (std::is_array_v<ValueType>) {
|
||||
if (std::get<_i>(_set)) {
|
||||
auto ptr = rfl::get<_i>(_view);
|
||||
call_destructor_on_array(sizeof(*ptr) / sizeof(**ptr), *ptr);
|
||||
}
|
||||
}
|
||||
if constexpr (_i + 1 < size_) {
|
||||
call_destructors_where_necessary<_i + 1>(_view, _set);
|
||||
}
|
||||
}
|
||||
|
||||
/// Generates error messages for when fields are missing.
|
||||
template <size_t _i = 0>
|
||||
static void handle_missing_fields(const std::array<bool, size_>& _found,
|
||||
const NamedTupleType& _view,
|
||||
std::array<bool, size_>* _set,
|
||||
std::vector<Error>* _errors) noexcept {
|
||||
using FieldType = std::tuple_element_t<_i, typename NamedTupleType::Fields>;
|
||||
using ValueType = std::remove_reference_t<
|
||||
std::remove_pointer_t<typename FieldType::Type>>;
|
||||
|
||||
if (!std::get<_i>(_found)) {
|
||||
if constexpr (_all_required ||
|
||||
is_required<ValueType, _ignore_empty_containers>()) {
|
||||
constexpr auto current_name =
|
||||
std::tuple_element_t<_i, typename NamedTupleType::Fields>::name();
|
||||
_errors->push_back("Field named '" + std::string(current_name) +
|
||||
"' not found.");
|
||||
} else {
|
||||
if constexpr (!std::is_const_v<ValueType>) {
|
||||
::new (rfl::get<_i>(_view)) ValueType();
|
||||
} else {
|
||||
using NonConstT = std::remove_const_t<ValueType>;
|
||||
::new (const_cast<NonConstT*>(rfl::get<_i>(_view))) NonConstT();
|
||||
}
|
||||
std::get<_i>(*_set) = true;
|
||||
}
|
||||
}
|
||||
if constexpr (_i + 1 < size_) {
|
||||
handle_missing_fields<_i + 1>(_found, _view, _set, _errors);
|
||||
}
|
||||
}
|
||||
|
||||
static std::optional<Error> read_object(
|
||||
const R& _r, const InputObjectType& _obj,
|
||||
const NamedTupleType& _view) noexcept {
|
||||
auto found = std::array<bool, NamedTupleType::size()>();
|
||||
found.fill(false);
|
||||
auto set = std::array<bool, NamedTupleType::size()>();
|
||||
set.fill(false);
|
||||
std::vector<Error> errors;
|
||||
const auto object_reader =
|
||||
ViewReader<R, W, NamedTupleType>(&_r, &_view, &found, &set, &errors);
|
||||
const auto err = _r.read_object(object_reader, _obj);
|
||||
if (err) {
|
||||
return *err;
|
||||
}
|
||||
handle_missing_fields(found, _view, &set, &errors);
|
||||
if (errors.size() != 0) {
|
||||
call_destructors_where_necessary(_view, set);
|
||||
return to_single_error_message(errors);
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace parsing
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
#include "AreReaderAndWriter.hpp"
|
||||
#include "Parent.hpp"
|
||||
#include "Parser_base.hpp"
|
||||
#include "StructReader.hpp"
|
||||
#include "is_tagged_union_wrapper.hpp"
|
||||
#include "schema/Type.hpp"
|
||||
|
||||
@@ -52,15 +53,7 @@ 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>) {
|
||||
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);
|
||||
return StructReader<R, W, T>::read(_r, _var);
|
||||
} else if constexpr (std::is_enum_v<T>) {
|
||||
using StringConverter = internal::enums::StringConverter<T>;
|
||||
return _r.template to_basic_type<std::string>(_var).and_then(
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
#ifndef RFL_PARSING_STRUCTREADER_HPP_
|
||||
#define RFL_PARSING_STRUCTREADER_HPP_
|
||||
|
||||
#include <array>
|
||||
#include <string_view>
|
||||
#include <type_traits>
|
||||
#include <vector>
|
||||
|
||||
#include "../Result.hpp"
|
||||
#include "../to_view.hpp"
|
||||
#include "AreReaderAndWriter.hpp"
|
||||
|
||||
namespace rfl::parsing {
|
||||
|
||||
template <class R, class W, class StructType>
|
||||
requires AreReaderAndWriter<R, W, StructType>
|
||||
struct StructReader {
|
||||
public:
|
||||
using InputVarType = typename R::InputVarType;
|
||||
|
||||
/// The way this works is that we allocate space on the stack in this size of
|
||||
/// the struct in which we then write the individual fields using
|
||||
/// views and placement new. This is how we deal with the fact that some
|
||||
/// fields might not be default-constructible.
|
||||
static Result<StructType> read(const R& _r, const InputVarType& _var) {
|
||||
alignas(StructType) unsigned char buf[sizeof(StructType)];
|
||||
auto ptr = reinterpret_cast<StructType*>(buf);
|
||||
const auto view = to_view(*ptr);
|
||||
using ViewType = std::remove_cvref_t<decltype(view)>;
|
||||
const auto err = Parser<R, W, ViewType>::read_view(_r, _var, view);
|
||||
if (err) {
|
||||
return *err;
|
||||
}
|
||||
return std::move(*ptr);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace rfl::parsing
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,91 @@
|
||||
#ifndef RFL_PARSING_VIEWREADER_HPP_
|
||||
#define RFL_PARSING_VIEWREADER_HPP_
|
||||
|
||||
#include <array>
|
||||
#include <string_view>
|
||||
#include <type_traits>
|
||||
#include <vector>
|
||||
|
||||
#include "../Result.hpp"
|
||||
#include "../internal/is_array.hpp"
|
||||
|
||||
namespace rfl::parsing {
|
||||
|
||||
template <class R, class W, class ViewType>
|
||||
class ViewReader {
|
||||
private:
|
||||
using InputVarType = typename R::InputVarType;
|
||||
static constexpr size_t size_ = ViewType::size();
|
||||
|
||||
public:
|
||||
ViewReader(const R* _r, const ViewType* _view,
|
||||
std::array<bool, size_>* _found, std::array<bool, size_>* _set,
|
||||
std::vector<Error>* _errors)
|
||||
: r_(_r), view_(_view), found_(_found), set_(_set), errors_(_errors) {}
|
||||
|
||||
~ViewReader() = default;
|
||||
|
||||
template <size_t _i = 0>
|
||||
void read(const std::string_view& _name, const InputVarType& _var) const {
|
||||
constexpr auto current_name =
|
||||
std::tuple_element_t<_i, typename ViewType::Fields>::name();
|
||||
using CurrentType = std::remove_cvref_t<std::remove_pointer_t<
|
||||
typename std::tuple_element_t<_i, typename ViewType::Fields>::Type>>;
|
||||
if (!std::get<_i>(*found_) && _name == current_name) {
|
||||
auto res = Parser<R, W, CurrentType>::read(*r_, _var);
|
||||
if (res) {
|
||||
move_to(rfl::get<_i>(*view_), &(*res));
|
||||
std::get<_i>(*set_) = true;
|
||||
} else {
|
||||
errors_->push_back(Error("Failed to parse field '" +
|
||||
std::string(current_name) +
|
||||
"': " + res.error()->what()));
|
||||
}
|
||||
std::get<_i>(*found_) = true;
|
||||
return;
|
||||
}
|
||||
if constexpr (_i + 1 < size_) {
|
||||
read<_i + 1>(_name, _var);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
template <class Target, class Source>
|
||||
void move_to(Target* _t, Source* _s) const {
|
||||
if constexpr (std::is_const_v<Target>) {
|
||||
return move_to(const_cast<std::remove_const_t<Target>*>(_t), _s);
|
||||
} else if constexpr (!internal::is_array_v<Source> &&
|
||||
!std::is_array_v<Target>) {
|
||||
::new (_t) Target(std::move(*_s));
|
||||
} else if constexpr (internal::is_array_v<Source>) {
|
||||
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.
|
||||
const ViewType* view_;
|
||||
|
||||
/// Indicates that a certain field has been found.
|
||||
std::array<bool, size_>* found_;
|
||||
|
||||
/// Indicates that a certain field has been successfully set - necessary,
|
||||
/// because we have to trigger the destructors manually.
|
||||
std::array<bool, size_>* set_;
|
||||
|
||||
/// Collects any errors we may have come across.
|
||||
std::vector<Error>* errors_;
|
||||
};
|
||||
|
||||
} // namespace rfl::parsing
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,24 @@
|
||||
#ifndef RFL_PARSING_ISVIEWREADER_HPP_
|
||||
#define RFL_PARSING_ISVIEWREADER_HPP_
|
||||
|
||||
#include "ViewReader.hpp"
|
||||
|
||||
namespace rfl ::parsing {
|
||||
|
||||
template <class T>
|
||||
class is_view_reader;
|
||||
|
||||
template <class T>
|
||||
class is_view_reader : public std::false_type {};
|
||||
|
||||
template <class R, class W, class NamedTupleType>
|
||||
class is_view_reader<ViewReader<R, W, NamedTupleType>> : public std::true_type {
|
||||
};
|
||||
|
||||
template <class T>
|
||||
constexpr bool is_view_reader_v =
|
||||
is_view_reader<std::remove_cvref_t<std::remove_pointer_t<T>>>::value;
|
||||
|
||||
} // namespace rfl::parsing
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,33 @@
|
||||
#ifndef RFL_PARSING_TOSINGLEERRORMESSAGE_HPP_
|
||||
#define RFL_PARSING_TOSINGLEERRORMESSAGE_HPP_
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "../internal/strings/replace_all.hpp"
|
||||
|
||||
namespace rfl::parsing {
|
||||
|
||||
/// Combines a set of errors to a single, readable error message.
|
||||
inline Error to_single_error_message(std::vector<Error> _errors) {
|
||||
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 < 10; ++i) {
|
||||
msg +=
|
||||
"\n" + std::to_string(i + 1) + ") " +
|
||||
internal::strings::replace_all(_errors.at(i).what(), "\n", "\n ");
|
||||
}
|
||||
if (_errors.size() > 10) {
|
||||
msg +=
|
||||
"\n...\nMore than 10 errors occurred, but I am only showing the "
|
||||
"first 10.";
|
||||
}
|
||||
return Error(msg);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace rfl::parsing
|
||||
|
||||
#endif
|
||||
+11
-34
@@ -5,6 +5,7 @@
|
||||
#include <exception>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <pugixml.hpp>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
@@ -17,6 +18,7 @@
|
||||
|
||||
#include "../Result.hpp"
|
||||
#include "../always_false.hpp"
|
||||
#include "../parsing/is_view_reader.hpp"
|
||||
|
||||
namespace rfl {
|
||||
namespace xml {
|
||||
@@ -119,50 +121,25 @@ struct Reader {
|
||||
return std::visit(cast_as_node, _var.node_or_attribute_).transform(wrap);
|
||||
}
|
||||
|
||||
template <size_t size, class FunctionType>
|
||||
std::array<std::optional<InputVarType>, size> to_fields_array(
|
||||
const FunctionType _fct, const InputObjectType _obj) const noexcept {
|
||||
std::array<std::optional<InputVarType>, size> f_arr;
|
||||
|
||||
template <class ObjectReader>
|
||||
std::optional<Error> read_object(const ObjectReader& _object_reader,
|
||||
const InputObjectType& _obj) const noexcept {
|
||||
for (auto child = _obj.node_.first_child(); child;
|
||||
child = child.next_sibling()) {
|
||||
const auto name = child.name();
|
||||
const auto ix = _fct(std::string_view(name));
|
||||
// XML allows for duplicate node names, but we always want the first
|
||||
// sibling.
|
||||
if (ix != -1 && !f_arr[ix]) {
|
||||
f_arr[ix] = InputVarType(child);
|
||||
}
|
||||
_object_reader.read(std::string_view(child.name()), InputVarType(child));
|
||||
}
|
||||
|
||||
for (auto attr = _obj.node_.first_attribute(); attr;
|
||||
attr = attr.next_attribute()) {
|
||||
const auto name = attr.name();
|
||||
const auto ix = _fct(std::string_view(name));
|
||||
// XML allows for duplicate node names, but we always want the first
|
||||
// sibling.
|
||||
if (ix != -1 && !f_arr[ix]) {
|
||||
f_arr[ix] = InputVarType(attr);
|
||||
}
|
||||
_object_reader.read(std::string_view(attr.name()), InputVarType(attr));
|
||||
}
|
||||
|
||||
const auto ix = _fct(std::string_view("xml_content"));
|
||||
if (ix != -1) {
|
||||
f_arr[ix] = InputVarType(_obj.node_);
|
||||
if constexpr (parsing::is_view_reader_v<ObjectReader>) {
|
||||
_object_reader.read(std::string_view("xml_content"),
|
||||
InputVarType(_obj.node_));
|
||||
}
|
||||
|
||||
return f_arr;
|
||||
}
|
||||
|
||||
rfl::Result<std::vector<std::pair<std::string, InputVarType>>> to_map(
|
||||
const InputObjectType _obj) const noexcept {
|
||||
std::vector<std::pair<std::string, InputVarType>> m;
|
||||
for (auto child = _obj.node_.first_child(); child;
|
||||
child = child.next_sibling()) {
|
||||
auto p = std::make_pair(std::string(child.name()), InputVarType(child));
|
||||
m.emplace_back(std::move(p));
|
||||
}
|
||||
return m;
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
rfl::Result<InputObjectType> to_object(
|
||||
|
||||
@@ -86,36 +86,18 @@ struct Reader {
|
||||
return InputArrayType(_var.node_);
|
||||
}
|
||||
|
||||
template <size_t size, class FunctionType>
|
||||
std::array<std::optional<InputVarType>, size> to_fields_array(
|
||||
const FunctionType& _fct, const InputObjectType& _obj) const noexcept {
|
||||
std::array<std::optional<InputVarType>, size> f_arr;
|
||||
template <class ObjectReader>
|
||||
std::optional<Error> read_object(const ObjectReader& _object_reader,
|
||||
const InputObjectType& _obj) const noexcept {
|
||||
for (const auto& p : _obj.node_) {
|
||||
try {
|
||||
const auto k = p.first.as<std::string>();
|
||||
const auto ix = _fct(std::string_view(k));
|
||||
if (ix != -1) {
|
||||
f_arr[ix] = InputVarType(p.second);
|
||||
}
|
||||
_object_reader.read(std::string_view(k), InputVarType(p.second));
|
||||
} catch (std::exception& e) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
return f_arr;
|
||||
}
|
||||
|
||||
rfl::Result<std::vector<std::pair<std::string, InputVarType>>> to_map(
|
||||
const InputObjectType& _obj) const noexcept {
|
||||
std::vector<std::pair<std::string, InputVarType>> m;
|
||||
for (const auto& p : _obj.node_) {
|
||||
try {
|
||||
auto k = p.first.as<std::string>();
|
||||
m.emplace_back(std::make_pair(k, p.second));
|
||||
} catch (std::exception& e) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
return m;
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
rfl::Result<InputObjectType> to_object(
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
#include "test_const_fields.hpp"
|
||||
|
||||
#include <iostream>
|
||||
#include <optional>
|
||||
#include <rfl.hpp>
|
||||
#include <rfl/json.hpp>
|
||||
#include <source_location>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "write_and_read.hpp"
|
||||
|
||||
namespace test_const_fields {
|
||||
|
||||
using Age = rfl::Validator<unsigned int, rfl::Minimum<0>, rfl::Maximum<130>>;
|
||||
|
||||
struct Person {
|
||||
const rfl::Rename<"firstName", std::string> first_name;
|
||||
const rfl::Rename<"lastName", std::string> last_name = "Simpson";
|
||||
const std::string town = "Springfield";
|
||||
const rfl::Timestamp<"%Y-%m-%d"> birthday;
|
||||
const std::optional<Age> age;
|
||||
const rfl::Email email;
|
||||
const std::vector<Person> children;
|
||||
};
|
||||
|
||||
void test() {
|
||||
std::cout << std::source_location::current().function_name() << std::endl;
|
||||
|
||||
const auto bart = Person{.first_name = "Bart",
|
||||
.birthday = "1987-04-19",
|
||||
.age = 10,
|
||||
.email = "bart@simpson.com"};
|
||||
|
||||
const auto lisa = Person{.first_name = "Lisa",
|
||||
.birthday = "1987-04-19",
|
||||
.age = 8,
|
||||
.email = "lisa@simpson.com"};
|
||||
|
||||
const auto maggie = Person{.first_name = "Maggie",
|
||||
.birthday = "1987-04-19",
|
||||
.age = 0,
|
||||
.email = "maggie@simpson.com"};
|
||||
|
||||
const auto homer =
|
||||
Person{.first_name = "Homer",
|
||||
.birthday = "1987-04-19",
|
||||
.age = 45,
|
||||
.email = "homer@simpson.com",
|
||||
.children = std::vector<Person>({bart, lisa, maggie})};
|
||||
|
||||
write_and_read(
|
||||
homer,
|
||||
R"({"firstName":"Homer","lastName":"Simpson","town":"Springfield","birthday":"1987-04-19","age":45,"email":"homer@simpson.com","children":[{"firstName":"Bart","lastName":"Simpson","town":"Springfield","birthday":"1987-04-19","age":10,"email":"bart@simpson.com","children":[]},{"firstName":"Lisa","lastName":"Simpson","town":"Springfield","birthday":"1987-04-19","age":8,"email":"lisa@simpson.com","children":[]},{"firstName":"Maggie","lastName":"Simpson","town":"Springfield","birthday":"1987-04-19","age":0,"email":"maggie@simpson.com","children":[]}]})");
|
||||
}
|
||||
} // namespace test_const_fields
|
||||
@@ -0,0 +1,5 @@
|
||||
namespace test_const_fields {
|
||||
|
||||
void test();
|
||||
|
||||
}
|
||||
@@ -15,6 +15,7 @@
|
||||
#include "test_c_array_class3.hpp"
|
||||
#include "test_c_array_class4.hpp"
|
||||
#include "test_c_array_class5.hpp"
|
||||
#include "test_const_fields.hpp"
|
||||
#include "test_custom_class1.hpp"
|
||||
#include "test_custom_class2.hpp"
|
||||
#include "test_custom_class3.hpp"
|
||||
@@ -124,6 +125,7 @@ int main() {
|
||||
test_monster_example::test();
|
||||
test_unnamed_namespace::test();
|
||||
test_inside_function::test();
|
||||
test_const_fields::test();
|
||||
|
||||
test_enum1::test();
|
||||
test_enum2::test();
|
||||
|
||||
Reference in New Issue
Block a user