#ifndef RFL_PARSING_MAPPARSER_HPP_ #define RFL_PARSING_MAPPARSER_HPP_ #include #include #include #include "rfl/Result.hpp" #include "rfl/always_false.hpp" #include "rfl/parsing/Parser_base.hpp" namespace rfl { namespace parsing { template requires AreReaderAndWriter struct MapParser { public: using InputObjectType = typename R::InputObjectType; using InputVarType = typename R::InputVarType; using OutputObjectType = typename W::OutputObjectType; using OutputVarType = typename W::OutputVarType; using KeyType = std::decay_t; using ValueType = std::decay_t; static Result read(const R& _r, const InputVarType& _var) noexcept { const auto to_map = [&](const auto& _obj) { return make_map(_r, _obj); }; return _r.to_object(_var).and_then(to_map); } static OutputVarType write(const W& _w, const MapType& _m) noexcept { auto obj = _w.new_object(); for (const auto& [k, v] : _m) { auto parsed_val = Parser>::write(_w, v); if constexpr (internal::has_reflection_type_v) { using ReflT = typename KeyType::ReflectionType; if constexpr (std::is_integral_v || std::is_floating_point_v) { _w.set_field(std::to_string(k.reflection()), std::move(parsed_val), &obj); } else { _w.set_field(k.reflection(), std::move(parsed_val), &obj); } } else if constexpr (std::is_integral_v || std::is_floating_point_v) { _w.set_field(std::to_string(k), std::move(parsed_val), &obj); } else { _w.set_field(k, std::move(parsed_val), &obj); } } return obj; } 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_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); } } 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 make_map(const R& _r, const auto& _obj) noexcept { auto m = _r.to_map(_obj); MapType res; try { for (auto& p : m) { res.insert(get_pair(_r, p)); } } catch (std::exception& e) { return Error(e.what()); } return res; } }; } // namespace parsing } // namespace rfl #endif