diff --git a/docs/supporting_your_own_format.md b/docs/supporting_your_own_format.md index 11ab8f20..c7cef895 100644 --- a/docs/supporting_your_own_format.md +++ b/docs/supporting_your_own_format.md @@ -198,19 +198,6 @@ struct Reader { /// Returns an rfl::Error if `_var` cannot be cast as an array. rfl::Result 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 - std::array, 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> 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 to_object( @@ -220,6 +207,12 @@ struct Reader { /// a std::vector. std::vector 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 + std::optional 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 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, 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`. diff --git a/include/rfl/Flatten.hpp b/include/rfl/Flatten.hpp index 3cd022fe..62beb18b 100644 --- a/include/rfl/Flatten.hpp +++ b/include/rfl/Flatten.hpp @@ -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_; } diff --git a/include/rfl/Result.hpp b/include/rfl/Result.hpp index c321614d..78f88725 100644 --- a/include/rfl/Result.hpp +++ b/include/rfl/Result.hpp @@ -40,6 +40,8 @@ class Result { static_assert(!std::is_same(), "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)) {} diff --git a/include/rfl/bson/Reader.hpp b/include/rfl/bson/Reader.hpp index 7be62c08..0ebd34c3 100644 --- a/include/rfl/bson/Reader.hpp +++ b/include/rfl/bson/Reader.hpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -127,10 +128,9 @@ struct Reader { return InputArrayType{_var.val_}; } - template - std::array, size> to_fields_array( - const FunctionType& _fct, const InputObjectType& _obj) const noexcept { - std::array, size> f_arr; + template + std::optional 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>> to_map( - const InputObjectType& _obj) const noexcept { - std::vector> 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 to_object( diff --git a/include/rfl/cbor/Reader.hpp b/include/rfl/cbor/Reader.hpp index 8340f76c..04dbe301 100644 --- a/include/rfl/cbor/Reader.hpp +++ b/include/rfl/cbor/Reader.hpp @@ -150,83 +150,6 @@ struct Reader { return InputArrayType{_var.val_}; } - template - std::array, size> to_fields_array( - const FunctionType& _fct, const InputObjectType& _obj) const noexcept { - std::array, size> f_arr; - CborValue val; - auto buffer = std::vector(); - 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>> to_map( - const InputObjectType& _obj) const noexcept { - std::vector> map; - CborValue val; - auto buffer = std::vector(); - 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 to_object( const InputVarType& _var) const noexcept { if (!cbor_value_is_map(_var.val_)) { @@ -258,6 +181,40 @@ struct Reader { return vec; } + template + std::optional 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(); + + 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 rfl::Result use_custom_constructor( const InputVarType& _var) const noexcept { diff --git a/include/rfl/flexbuf/Reader.hpp b/include/rfl/flexbuf/Reader.hpp index 5c045fc2..565e6fb7 100644 --- a/include/rfl/flexbuf/Reader.hpp +++ b/include/rfl/flexbuf/Reader.hpp @@ -84,23 +84,19 @@ struct Reader { } } - template - std::array, size> to_fields_array( - const FunctionType& _fct, const InputObjectType& _obj) const noexcept { - std::array, size> f_arr; - + template + std::optional 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 to_array( @@ -111,22 +107,6 @@ struct Reader { return _var.AsVector(); } - rfl::Result>> to_map( - const InputObjectType& _obj) const noexcept { - std::vector> 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 to_object( const InputVarType& _var) const noexcept { if (!_var.IsMap()) { diff --git a/include/rfl/internal/Array.hpp b/include/rfl/internal/Array.hpp index 9f75a35d..a84c1951 100644 --- a/include/rfl/internal/Array.hpp +++ b/include/rfl/internal/Array.hpp @@ -2,6 +2,7 @@ #define RFL_INTERNAL_ARRAY_HPP_ #include +#include #include #include "to_std_array.hpp" diff --git a/include/rfl/internal/is_array.hpp b/include/rfl/internal/is_array.hpp new file mode 100644 index 00000000..093eed4a --- /dev/null +++ b/include/rfl/internal/is_array.hpp @@ -0,0 +1,27 @@ +#ifndef RFL_INTERNAL_ISARRAY_HPP_ +#define RFL_INTERNAL_ISARRAY_HPP_ + +#include +#include +#include + +#include "Array.hpp" + +namespace rfl::internal { + +template +class is_array; + +template +class is_array : public std::false_type {}; + +template +class is_array> : public std::true_type {}; + +template +constexpr bool is_array_v = + is_array>>::value; + +} // namespace rfl::internal + +#endif diff --git a/include/rfl/internal/to_ptr_named_tuple.hpp b/include/rfl/internal/to_ptr_named_tuple.hpp index 20d81c4e..85de26f6 100644 --- a/include/rfl/internal/to_ptr_named_tuple.hpp +++ b/include/rfl/internal/to_ptr_named_tuple.hpp @@ -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>; if constexpr (internal::is_flatten_field::value) { - const auto subtuple = - internal::to_ptr_field_tuple(*std::get(_t).get()); + auto subtuple = internal::to_ptr_field_tuple(*std::get(_t).get()); return flatten_ptr_field_tuple(_t, std::forward(_args)..., flatten_ptr_field_tuple(subtuple)); } else { @@ -39,7 +38,7 @@ auto flatten_ptr_field_tuple(PtrFieldTuple& _t, Args&&... _args) { template auto field_tuple_to_named_tuple(PtrFieldTuple& _ptr_field_tuple) { - const auto ft_to_nt = [](const Fields&... _fields) { + const auto ft_to_nt = [](Fields&&... _fields) { return make_named_tuple(_fields...); }; diff --git a/include/rfl/internal/to_ptr_tuple.hpp b/include/rfl/internal/to_ptr_tuple.hpp index 9b360d45..c3507887 100644 --- a/include/rfl/internal/to_ptr_tuple.hpp +++ b/include/rfl/internal/to_ptr_tuple.hpp @@ -15,9 +15,7 @@ constexpr auto to_ptr_tuple(T& _t) { if constexpr (std::is_pointer_v>) { return to_ptr_tuple(*_t); } else { - return bind_to_tuple(_t, [](auto&& x) { - return std::addressof(std::forward(x)); - }); + return bind_to_tuple(_t, [](auto& x) { return &x; }); } } diff --git a/include/rfl/json/Reader.hpp b/include/rfl/json/Reader.hpp index 0118e700..5ac3edf5 100644 --- a/include/rfl/json/Reader.hpp +++ b/include/rfl/json/Reader.hpp @@ -96,37 +96,6 @@ struct Reader { return InputArrayType(_var.val_); } - template - std::array, size> to_fields_array( - const FunctionType _fct, const InputObjectType _obj) const noexcept { - std::array, 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>> to_map( - const InputObjectType _obj) const noexcept { - std::vector> 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 to_object( const InputVarType _var) const noexcept { if (!yyjson_is_obj(_var.val_)) { @@ -146,6 +115,19 @@ struct Reader { return vec; } + template + std::optional 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 rfl::Result use_custom_constructor( const InputVarType _var) const noexcept { diff --git a/include/rfl/parsing/FieldVariantParser.hpp b/include/rfl/parsing/FieldVariantParser.hpp index 056da129..34dd8d8d 100644 --- a/include/rfl/parsing/FieldVariantParser.hpp +++ b/include/rfl/parsing/FieldVariantParser.hpp @@ -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 requires AreReaderAndWriter> struct FieldVariantParser { - using ResultType = Result>; + using FieldVariantType = std::variant; + using ResultType = Result; 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>(); + const auto reader = + FieldVariantReader(&_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 @@ -76,43 +79,6 @@ struct FieldVariantParser { using VariantType = std::variant...>; return Parser::to_schema(_definitions); } - - private: - template - 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>::type>; - - using ValueType = std::remove_cvref_t; - - const auto key = FieldType::name_.str(); - - if (key == _disc_value) { - const auto to_variant = [](ValueType&& _val) { - return std::variant(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::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 diff --git a/include/rfl/parsing/FieldVariantReader.hpp b/include/rfl/parsing/FieldVariantReader.hpp new file mode 100644 index 00000000..ed5799e0 --- /dev/null +++ b/include/rfl/parsing/FieldVariantReader.hpp @@ -0,0 +1,83 @@ +#ifndef RFL_PARSING_FIELDVARIANTREADER_HPP_ +#define RFL_PARSING_FIELDVARIANTREADER_HPP_ + +#include +#include +#include +#include +#include +#include + +#include "../Result.hpp" +#include "../internal/is_array.hpp" + +namespace rfl::parsing { + +template +class FieldVariantReader { + private: + using InputVarType = typename R::InputVarType; + using FieldVariantType = std::variant; + using ResultType = Result; + + public: + FieldVariantReader(const R* _r, + std::optional>* _field_variant) + : r_(_r), field_variant_(_field_variant) {} + + ~FieldVariantReader() = default; + + template + 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>::type>; + + using ValueType = std::remove_cvref_t; + + constexpr auto key = FieldType::name_.string_view(); + + if (key == _disc_value) { + const auto to_variant = [](ValueType&& _val) { + return std::variant(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::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>* field_variant_; +}; + +} // namespace rfl::parsing + +#endif diff --git a/include/rfl/parsing/IsReader.hpp b/include/rfl/parsing/IsReader.hpp index 5931134b..f1d5a0fe 100644 --- a/include/rfl/parsing/IsReader.hpp +++ b/include/rfl/parsing/IsReader.hpp @@ -16,9 +16,16 @@ namespace rfl { namespace parsing { +template +struct MockObjectReader { + void read(const std::string_view& _name, + typename R::InputVarType& _var) const {} +}; + template concept IsReader = requires(R r, std::string name, std::function fct, + MockObjectReader 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; + /// 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>; + /// Transforms var to a basic type (bool, integral, /// floating point, std::string) { r.template to_basic_type>(var) } -> std::same_as>>; - /// _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, 6>>; - /// Casts var as an InputArrayType. { r.to_array(var) } -> std::same_as>; - /// Iterates through an object and writes the contained key-value pairs into - /// a vector. - { - r.to_map(obj) - } -> std::same_as>>>; - /// Casts var as an InputObjectType. { r.to_object(var) diff --git a/include/rfl/parsing/MapParser.hpp b/include/rfl/parsing/MapParser.hpp index cf26ec7d..a21593f5 100644 --- a/include/rfl/parsing/MapParser.hpp +++ b/include/rfl/parsing/MapParser.hpp @@ -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; static Result 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 { + return make_map(_r, obj); + }; return _r.to_object(_var).and_then(to_map); } @@ -77,72 +81,18 @@ struct MapParser { } private: - template - static Result key_to_numeric(auto& _pair) noexcept { - try { - if constexpr (std::is_integral_v) { - return static_cast(std::stoi(_pair.first)); - } else if constexpr (std::is_floating_point_v) { - return static_cast(std::stod(_pair.first)); - } else { - static_assert(always_false_v, "Unsupported type"); - } - } catch (std::exception& e) { - return Error(e.what()); + static Result make_map(const R& _r, const InputObjectType& _obj) { + MapType map; + std::vector errors; + const auto map_reader = MapReader(&_r, &map, &errors); + const auto err = _r.read_object(map_reader, _obj); + if (err) { + return *err; } - } - - static Result> 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 || - std::is_floating_point_v) { - return key_to_numeric(_pair).transform(to_pair); - - } else if constexpr (internal::has_reflection_type_v) { - using ReflT = typename KeyType::ReflectionType; - - if constexpr (std::is_integral_v || - std::is_floating_point_v) { - return key_to_numeric(_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 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>::read(_r, _pair.second) - .and_then(to_pair) - .value(); - } - - static Result 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 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; } }; diff --git a/include/rfl/parsing/MapReader.hpp b/include/rfl/parsing/MapReader.hpp new file mode 100644 index 00000000..7f66f3b1 --- /dev/null +++ b/include/rfl/parsing/MapReader.hpp @@ -0,0 +1,109 @@ +#ifndef RFL_PARSING_MAPREADER_HPP_ +#define RFL_PARSING_MAPREADER_HPP_ + +#include +#include +#include +#include +#include + +#include "../Result.hpp" +#include "../always_false.hpp" + +namespace rfl::parsing { + +template +class MapReader { + private: + using InputVarType = typename R::InputVarType; + using KeyType = std::remove_cvref_t; + using ValueType = + std::remove_cvref_t; + + public: + MapReader(const R* _r, MapType* _map, std::vector* _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 + Result key_to_numeric(auto& _pair) const noexcept { + try { + if constexpr (std::is_integral_v) { + return static_cast(std::stoi(_pair.first)); + } else if constexpr (std::is_floating_point_v) { + return static_cast(std::stod(_pair.first)); + } else { + static_assert(always_false_v, "Unsupported type"); + } + } catch (std::exception& e) { + return Error(e.what()); + } + } + + Result> make_key(auto& _pair) const noexcept { + const auto to_pair = + [&](auto _key) -> Result> { + 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 || + std::is_floating_point_v) { + return key_to_numeric(_pair).and_then(to_pair); + + } else if constexpr (internal::has_reflection_type_v) { + using ReflT = typename KeyType::ReflectionType; + + if constexpr (std::is_integral_v || + std::is_floating_point_v) { + return key_to_numeric(_pair).and_then(to_pair); + } else { + return to_pair(_pair.first); + } + + } else { + return std::move(_pair); + } + } + + Result> 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>::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* errors_; +}; + +} // namespace rfl::parsing + +#endif diff --git a/include/rfl/parsing/NamedTupleParser.hpp b/include/rfl/parsing/NamedTupleParser.hpp index 34dc9ef6..e00709c2 100644 --- a/include/rfl/parsing/NamedTupleParser.hpp +++ b/include/rfl/parsing/NamedTupleParser.hpp @@ -1,6 +1,7 @@ #ifndef RFL_PARSING_NAMEDTUPLEPARSER_HPP_ #define RFL_PARSING_NAMEDTUPLEPARSER_HPP_ +#include #include #include #include @@ -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; + using NamedTupleType = NamedTuple; + + 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> 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(-1); - }; - const auto to_fields_array = [&](auto _obj) { - return _r.template to_fields_array(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) unsigned char + buf[sizeof(NamedTuple)]; + auto ptr = reinterpret_cast*>(buf); + const auto view = rfl::to_view(*ptr); + using ViewType = std::remove_cvref_t; + const auto err = Parser::read_view(_r, _var, view); + if (err) { + return *err; + } + return *ptr; } + /// Reads the data into a view. + static std::optional read_view( + const R& _r, const InputVarType& _var, + const NamedTuple& _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 static void write(const W& _w, const NamedTuple& _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 static schema::Type to_schema( std::map* _definitions, @@ -78,104 +104,6 @@ struct NamedTupleParser { }; private: - /// Builds the named tuple field by field. - template - static Result> build_named_tuple_recursively( - const R& _r, - const std::array, sizeof...(FieldTypes)>& - _fields_arr, - Args&&... _args) noexcept { - constexpr auto i = sizeof...(Args); - - if constexpr (i == sizeof...(FieldTypes)) { - return NamedTuple(std::move(_args)...); - } else { - using FieldType = typename std::tuple_element< - i, typename NamedTuple::Fields>::type; - - using ValueType = std::remove_cvref_t; - - const auto& f = std::get(_fields_arr); - - if (!f) { - if constexpr (_all_required || - is_required()) { - const auto key = FieldType::name_.str(); - return collect_errors( - _r, _fields_arr, - std::vector( - {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(_r, _fields_arr, - std::vector({std::move(_error)})); - }; - - return get_value(_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 - static Error collect_errors( - const R& _r, - const std::array, sizeof...(FieldTypes)>& - _fields_arr, - std::vector _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::Fields>::type; - - using ValueType = std::remove_cvref_t; - - const auto& f = std::get<_i>(_fields_arr); - - if (!f) { - if constexpr (_all_required || - is_required()) { - 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 { - _errors.emplace_back(std::move(_error)); - return _error; - }; - - get_value(_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 static void build_object_recursively(const W& _w, const NamedTuple& _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 - static auto get_value(const R& _r, const InputVarType _var) noexcept { - static_assert(FieldType::name_ != internal::StringLiteral("xml_content") || - internal::is_basic_type_v, - "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; - return Parser::read(_r, _var).or_else(embellish_error); - } - - /// Builds the object field by field. - template - static void set_field_indices( - std::unordered_map* - _field_indices) noexcept { - if constexpr (_i >= sizeof...(FieldTypes)) { - return; - } else { - using FieldType = - typename std::tuple_element<_i, std::tuple>::type; - const auto name = FieldType::name_.string_view(); - (*_field_indices)[name] = static_cast(_i); - set_field_indices<_i + 1>(_field_indices); + /// C-arrays need special handling here. + template + 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) { + call_destructor_on_array(sizeof(*_ptr) / sizeof(**_ptr), *(_ptr + i)); + } else if constexpr (std::is_destructible_v) { + (_ptr + i)->~T(); + } } } - private: - /// Maps each of the field names to an index signifying their order. - static inline internal::Memoization< - std::unordered_map> - field_indices_; + /// Because of the way we have allocated the fields, we need to manually + /// trigger the destructors. + template + static void call_destructors_where_necessary( + const NamedTupleType& _view, const std::array& _set) { + using FieldType = std::tuple_element_t<_i, typename NamedTupleType::Fields>; + using ValueType = + std::remove_cvref_t>; + if constexpr (!std::is_array_v && + std::is_destructible_v) { + if (std::get<_i>(_set)) { + rfl::get<_i>(_view)->~ValueType(); + } + } else if constexpr (std::is_array_v) { + 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 + static void handle_missing_fields(const std::array& _found, + const NamedTupleType& _view, + std::array* _set, + std::vector* _errors) noexcept { + using FieldType = std::tuple_element_t<_i, typename NamedTupleType::Fields>; + using ValueType = std::remove_reference_t< + std::remove_pointer_t>; + + if (!std::get<_i>(_found)) { + if constexpr (_all_required || + is_required()) { + 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) { + ::new (rfl::get<_i>(_view)) ValueType(); + } else { + using NonConstT = std::remove_const_t; + ::new (const_cast(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 read_object( + const R& _r, const InputObjectType& _obj, + const NamedTupleType& _view) noexcept { + auto found = std::array(); + found.fill(false); + auto set = std::array(); + set.fill(false); + std::vector errors; + const auto object_reader = + ViewReader(&_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 diff --git a/include/rfl/parsing/Parser_default.hpp b/include/rfl/parsing/Parser_default.hpp index 19cce0d8..97d5e62d 100644 --- a/include/rfl/parsing/Parser_default.hpp +++ b/include/rfl/parsing/Parser_default.hpp @@ -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::read(_r, _var).and_then(wrap_in_t); } else if constexpr (std::is_class_v && std::is_aggregate_v) { - using NamedTupleType = named_tuple_t; - const auto to_struct = [](NamedTupleType&& _n) -> Result { - try { - return from_named_tuple(std::move(_n)); - } catch (std::exception& e) { - return Error(e.what()); - } - }; - return Parser::read(_r, _var).and_then(to_struct); + return StructReader::read(_r, _var); } else if constexpr (std::is_enum_v) { using StringConverter = internal::enums::StringConverter; return _r.template to_basic_type(_var).and_then( diff --git a/include/rfl/parsing/StructReader.hpp b/include/rfl/parsing/StructReader.hpp new file mode 100644 index 00000000..6b9bcc52 --- /dev/null +++ b/include/rfl/parsing/StructReader.hpp @@ -0,0 +1,40 @@ +#ifndef RFL_PARSING_STRUCTREADER_HPP_ +#define RFL_PARSING_STRUCTREADER_HPP_ + +#include +#include +#include +#include + +#include "../Result.hpp" +#include "../to_view.hpp" +#include "AreReaderAndWriter.hpp" + +namespace rfl::parsing { + +template +requires AreReaderAndWriter +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 read(const R& _r, const InputVarType& _var) { + alignas(StructType) unsigned char buf[sizeof(StructType)]; + auto ptr = reinterpret_cast(buf); + const auto view = to_view(*ptr); + using ViewType = std::remove_cvref_t; + const auto err = Parser::read_view(_r, _var, view); + if (err) { + return *err; + } + return std::move(*ptr); + } +}; + +} // namespace rfl::parsing + +#endif diff --git a/include/rfl/parsing/ViewReader.hpp b/include/rfl/parsing/ViewReader.hpp new file mode 100644 index 00000000..ccbe2327 --- /dev/null +++ b/include/rfl/parsing/ViewReader.hpp @@ -0,0 +1,91 @@ +#ifndef RFL_PARSING_VIEWREADER_HPP_ +#define RFL_PARSING_VIEWREADER_HPP_ + +#include +#include +#include +#include + +#include "../Result.hpp" +#include "../internal/is_array.hpp" + +namespace rfl::parsing { + +template +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* _found, std::array* _set, + std::vector* _errors) + : r_(_r), view_(_view), found_(_found), set_(_set), errors_(_errors) {} + + ~ViewReader() = default; + + template + 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::Type>>; + if (!std::get<_i>(*found_) && _name == current_name) { + auto res = Parser::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 + void move_to(Target* _t, Source* _s) const { + if constexpr (std::is_const_v) { + return move_to(const_cast*>(_t), _s); + } else if constexpr (!internal::is_array_v && + !std::is_array_v) { + ::new (_t) Target(std::move(*_s)); + } else if constexpr (internal::is_array_v) { + 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* found_; + + /// Indicates that a certain field has been successfully set - necessary, + /// because we have to trigger the destructors manually. + std::array* set_; + + /// Collects any errors we may have come across. + std::vector* errors_; +}; + +} // namespace rfl::parsing + +#endif diff --git a/include/rfl/parsing/is_view_reader.hpp b/include/rfl/parsing/is_view_reader.hpp new file mode 100644 index 00000000..e3290073 --- /dev/null +++ b/include/rfl/parsing/is_view_reader.hpp @@ -0,0 +1,24 @@ +#ifndef RFL_PARSING_ISVIEWREADER_HPP_ +#define RFL_PARSING_ISVIEWREADER_HPP_ + +#include "ViewReader.hpp" + +namespace rfl ::parsing { + +template +class is_view_reader; + +template +class is_view_reader : public std::false_type {}; + +template +class is_view_reader> : public std::true_type { +}; + +template +constexpr bool is_view_reader_v = + is_view_reader>>::value; + +} // namespace rfl::parsing + +#endif diff --git a/include/rfl/parsing/to_single_error_message.hpp b/include/rfl/parsing/to_single_error_message.hpp new file mode 100644 index 00000000..16591d78 --- /dev/null +++ b/include/rfl/parsing/to_single_error_message.hpp @@ -0,0 +1,33 @@ +#ifndef RFL_PARSING_TOSINGLEERRORMESSAGE_HPP_ +#define RFL_PARSING_TOSINGLEERRORMESSAGE_HPP_ + +#include +#include + +#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 _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 diff --git a/include/rfl/xml/Reader.hpp b/include/rfl/xml/Reader.hpp index 2ffb2998..8dc62e01 100644 --- a/include/rfl/xml/Reader.hpp +++ b/include/rfl/xml/Reader.hpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -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 - std::array, size> to_fields_array( - const FunctionType _fct, const InputObjectType _obj) const noexcept { - std::array, size> f_arr; - + template + std::optional 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) { + _object_reader.read(std::string_view("xml_content"), + InputVarType(_obj.node_)); } - return f_arr; - } - - rfl::Result>> to_map( - const InputObjectType _obj) const noexcept { - std::vector> 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 to_object( diff --git a/include/rfl/yaml/Reader.hpp b/include/rfl/yaml/Reader.hpp index e1b6b6b2..2e8d324d 100644 --- a/include/rfl/yaml/Reader.hpp +++ b/include/rfl/yaml/Reader.hpp @@ -86,36 +86,18 @@ struct Reader { return InputArrayType(_var.node_); } - template - std::array, size> to_fields_array( - const FunctionType& _fct, const InputObjectType& _obj) const noexcept { - std::array, size> f_arr; + template + std::optional read_object(const ObjectReader& _object_reader, + const InputObjectType& _obj) const noexcept { for (const auto& p : _obj.node_) { try { const auto k = p.first.as(); - 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>> to_map( - const InputObjectType& _obj) const noexcept { - std::vector> m; - for (const auto& p : _obj.node_) { - try { - auto k = p.first.as(); - m.emplace_back(std::make_pair(k, p.second)); - } catch (std::exception& e) { - continue; - } - } - return m; + return std::nullopt; } rfl::Result to_object( diff --git a/tests/json/test_const_fields.cpp b/tests/json/test_const_fields.cpp new file mode 100644 index 00000000..26537888 --- /dev/null +++ b/tests/json/test_const_fields.cpp @@ -0,0 +1,56 @@ +#include "test_const_fields.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_const_fields { + +using Age = rfl::Validator, 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; + const rfl::Email email; + const std::vector 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({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 diff --git a/tests/json/test_const_fields.hpp b/tests/json/test_const_fields.hpp new file mode 100644 index 00000000..1bfeacb9 --- /dev/null +++ b/tests/json/test_const_fields.hpp @@ -0,0 +1,5 @@ +namespace test_const_fields { + +void test(); + +} diff --git a/tests/json/tests.cpp b/tests/json/tests.cpp index e388772d..38cf2a4f 100644 --- a/tests/json/tests.cpp +++ b/tests/json/tests.cpp @@ -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();