diff --git a/README.md b/README.md index 034b4cb2..fa2fa3ed 100644 --- a/README.md +++ b/README.md @@ -444,6 +444,7 @@ reflect-cpp supports the following containers from the C++ standard library: - `std::array` - `std::deque` +- `std::filesystem::path` - `std::forward_list` - `std::map` - `std::multimap` diff --git a/include/rfl/parsing/Parser.hpp b/include/rfl/parsing/Parser.hpp index 5eb177a7..bc0606a7 100644 --- a/include/rfl/parsing/Parser.hpp +++ b/include/rfl/parsing/Parser.hpp @@ -6,6 +6,7 @@ #include "Parser_box.hpp" #include "Parser_c_array.hpp" #include "Parser_default.hpp" +#include "Parser_filepath.hpp" #include "Parser_map_like.hpp" #include "Parser_named_tuple.hpp" #include "Parser_optional.hpp" diff --git a/include/rfl/parsing/Parser_filepath.hpp b/include/rfl/parsing/Parser_filepath.hpp new file mode 100644 index 00000000..95d88e07 --- /dev/null +++ b/include/rfl/parsing/Parser_filepath.hpp @@ -0,0 +1,51 @@ +#ifndef RFL_PARSING_PARSER_FILEPATH_HPP_ +#define RFL_PARSING_PARSER_FILEPATH_HPP_ + +#include +#include + +#include "../Result.hpp" +#include "Parser_base.hpp" +#include "schema/Type.hpp" + +namespace rfl { +namespace parsing { + +template +requires AreReaderAndWriter +struct Parser { + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; + + /// Expresses the variables as type T. + static Result read(const R& _r, + const InputVarType& _var) noexcept { + const auto to_path = + [&](std::string&& _str) -> Result { + try { + return std::filesystem::path(_str); + } catch (std::exception& e) { + return Error(e.what()); + } + }; + return Parser::read(_r, _var).and_then( + to_path); + } + + template + static void write(const W& _w, const std::filesystem::path& _p, + const P& _parent) noexcept { + return Parser::write(_w, _p.string(), + _parent); + } + + static schema::Type to_schema( + std::map* _definitions) { + return Parser::to_schema(_definitions); + } +}; + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/tests/json/test_filepath.cpp b/tests/json/test_filepath.cpp new file mode 100644 index 00000000..07f30ca3 --- /dev/null +++ b/tests/json/test_filepath.cpp @@ -0,0 +1,26 @@ +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_filepath { + +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name = "Simpson"; + std::filesystem::path path; +}; + +TEST(json, test_filepath) { + auto homer = + Person{.first_name = "Homer", .path = "/usr/lib/homer_simpson.cf"}; + + write_and_read( + homer, + R"({"firstName":"Homer","lastName":"Simpson","path":"/usr/lib/homer_simpson.cf"})"); +} +} // namespace test_filepath