#ifndef RFL_TOML_READER_HPP_ #define RFL_TOML_READER_HPP_ #include #include #include #include #include #include #include #include #include #include #include #include #include "../Result.hpp" #include "../always_false.hpp" namespace rfl::toml { struct Reader { using InputArrayType = ::toml::array*; using InputObjectType = ::toml::table*; using InputVarType = ::toml::node*; template static constexpr bool has_custom_constructor = (requires(InputVarType var) { T::from_toml_obj(var); }); rfl::Result get_field(const std::string& _name, const InputObjectType& _obj) const noexcept { auto var = (*_obj)[_name]; if (!var) { return rfl::Error("Object contains no field named '" + _name + "'."); } return var.node(); } bool is_empty(const InputVarType& _var) const noexcept { return !_var && true; } template rfl::Result to_basic_type(const InputVarType& _var) const noexcept { if constexpr (std::is_same, std::string>()) { const auto ptr = _var->as(); if (!ptr) { return Error("Could not cast the node to std::string!"); } return **ptr; } else if constexpr (std::is_same, bool>()) { const auto ptr = _var->as(); if (!ptr) { return Error("Could not cast the node to bool!"); } return **ptr; } else if constexpr (std::is_floating_point>()) { const auto ptr = _var->as(); if (!ptr) { return Error("Could not cast the node to double!"); } return static_cast>(**ptr); } else if constexpr (std::is_integral>()) { const auto ptr = _var->as(); if (!ptr) { return Error("Could not cast the node to int64_t!"); } return static_cast>(**ptr); } else { static_assert(rfl::always_false_v, "Unsupported type."); } } rfl::Result to_array(const InputVarType& _var) const noexcept { const auto ptr = _var->as_array(); if (!ptr) { return rfl::Error("Could not cast to an array!"); } return ptr; } template std::optional read_array(const ArrayReader& _array_reader, const InputArrayType& _arr) const noexcept { for (auto& node : *_arr) { const auto err = _array_reader.read(&node); if (err) { return err; } } return std::nullopt; } template std::optional read_object(const ObjectReader& _object_reader, InputObjectType _obj) const noexcept { for (auto& [k, v] : *_obj) { _object_reader.read(std::string_view(k), &v); } return std::nullopt; } rfl::Result to_object(const InputVarType& _var) const noexcept { const auto ptr = _var->as_table(); if (!ptr) { return rfl::Error("Could not cast to a table!"); } return ptr; } template rfl::Result use_custom_constructor(const InputVarType _var) const noexcept { try { return T::from_toml_obj(_var); } catch (std::exception& e) { return rfl::Error(e.what()); } } }; } // namespace rfl::toml #endif