From df56b2e31fbc776a92ae1d94999f73b7661c9128 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dr=2E=20Patrick=20Urbanke=20=28=E5=8A=89=E8=87=AA=E6=88=90?= =?UTF-8?q?=29?= Date: Sun, 13 Oct 2024 20:30:56 +0200 Subject: [PATCH] Added the ability to transform structs from and to generic elements; resolves #201 (#210) --- .github/workflows/linux-clang-14.yaml | 1 + .github/workflows/linux-clang-16.yaml | 1 + .github/workflows/linux-gcc.yaml | 1 + .github/workflows/macos-clang-arm.yaml | 1 + .github/workflows/macos-clang-x64.yaml | 1 + .github/workflows/windows-msvc.yaml | 1 + README.md | 4 +- docs/generic.md | 66 +++++++++- include/rfl.hpp | 2 + include/rfl/Generic.hpp | 55 ++++++-- include/rfl/Object.hpp | 10 ++ include/rfl/Variant.hpp | 43 +++++-- include/rfl/from_generic.hpp | 17 +++ include/rfl/generic/Parser.hpp | 17 +++ include/rfl/generic/Reader.hpp | 89 +++++++++++++ include/rfl/generic/Writer.hpp | 117 ++++++++++++++++++ include/rfl/generic/read.hpp | 25 ++++ include/rfl/generic/write.hpp | 29 +++++ .../internal/variant/is_convertible_to.hpp | 17 +++ ...l_destructors_on_tuple_where_necessary.hpp | 1 - include/rfl/to_generic.hpp | 17 +++ src/reflectcpp.cpp | 2 + src/rfl/Generic.cpp | 45 +++++-- src/rfl/generic/Reader.cpp | 58 +++++++++ src/rfl/generic/Writer.cpp | 90 ++++++++++++++ tests/CMakeLists.txt | 1 + tests/generic/CMakeLists.txt | 18 +++ tests/generic/test_add_struct_name.cpp | 46 +++++++ tests/generic/test_array.cpp | 31 +++++ tests/generic/test_box.cpp | 44 +++++++ tests/generic/test_combined_processors.cpp | 49 ++++++++ tests/generic/test_custom_class1.cpp | 36 ++++++ tests/generic/test_custom_class3.cpp | 64 ++++++++++ tests/generic/test_custom_class4.cpp | 65 ++++++++++ tests/generic/test_default_values.cpp | 27 ++++ tests/generic/test_deque.cpp | 28 +++++ tests/generic/test_enum.cpp | 24 ++++ tests/generic/test_field_variant.cpp | 34 +++++ tests/generic/test_flag_enum.cpp | 35 ++++++ tests/generic/test_flag_enum_with_int.cpp | 34 +++++ tests/generic/test_flatten.cpp | 33 +++++ tests/generic/test_flatten_anonymous.cpp | 34 +++++ tests/generic/test_forward_list.cpp | 28 +++++ tests/generic/test_literal.cpp | 25 ++++ tests/generic/test_literal_map.cpp | 23 ++++ tests/generic/test_map.cpp | 27 ++++ .../generic/test_map_with_key_validation.cpp | 28 +++++ tests/generic/test_monster_example.cpp | 59 +++++++++ tests/generic/test_readme_example.cpp | 46 +++++++ tests/generic/test_readme_example2.cpp | 22 ++++ tests/generic/test_ref.cpp | 44 +++++++ tests/generic/test_set.cpp | 25 ++++ tests/generic/test_size.cpp | 37 ++++++ .../generic/test_snake_case_to_camel_case.cpp | 34 +++++ .../test_snake_case_to_pascal_case.cpp | 34 +++++ tests/generic/test_string_map.cpp | 19 +++ tests/generic/test_tagged_union.cpp | 30 +++++ tests/generic/test_timestamp.cpp | 31 +++++ tests/generic/test_unique_ptr.cpp | 28 +++++ tests/generic/test_unique_ptr2.cpp | 43 +++++++ tests/generic/test_variant.cpp | 31 +++++ tests/generic/test_wstring.cpp | 21 ++++ tests/generic/write_and_read.hpp | 22 ++++ tests/json/test_json_schema.cpp | 2 +- tests/json/test_rfl_variant_get_if.cpp | 4 +- 65 files changed, 1933 insertions(+), 43 deletions(-) create mode 100644 include/rfl/from_generic.hpp create mode 100644 include/rfl/generic/Parser.hpp create mode 100644 include/rfl/generic/Reader.hpp create mode 100644 include/rfl/generic/Writer.hpp create mode 100644 include/rfl/generic/read.hpp create mode 100644 include/rfl/generic/write.hpp create mode 100644 include/rfl/internal/variant/is_convertible_to.hpp create mode 100644 include/rfl/to_generic.hpp create mode 100644 src/rfl/generic/Reader.cpp create mode 100644 src/rfl/generic/Writer.cpp create mode 100644 tests/generic/CMakeLists.txt create mode 100644 tests/generic/test_add_struct_name.cpp create mode 100644 tests/generic/test_array.cpp create mode 100644 tests/generic/test_box.cpp create mode 100644 tests/generic/test_combined_processors.cpp create mode 100644 tests/generic/test_custom_class1.cpp create mode 100644 tests/generic/test_custom_class3.cpp create mode 100644 tests/generic/test_custom_class4.cpp create mode 100644 tests/generic/test_default_values.cpp create mode 100644 tests/generic/test_deque.cpp create mode 100644 tests/generic/test_enum.cpp create mode 100644 tests/generic/test_field_variant.cpp create mode 100644 tests/generic/test_flag_enum.cpp create mode 100644 tests/generic/test_flag_enum_with_int.cpp create mode 100644 tests/generic/test_flatten.cpp create mode 100644 tests/generic/test_flatten_anonymous.cpp create mode 100644 tests/generic/test_forward_list.cpp create mode 100644 tests/generic/test_literal.cpp create mode 100644 tests/generic/test_literal_map.cpp create mode 100644 tests/generic/test_map.cpp create mode 100644 tests/generic/test_map_with_key_validation.cpp create mode 100644 tests/generic/test_monster_example.cpp create mode 100644 tests/generic/test_readme_example.cpp create mode 100644 tests/generic/test_readme_example2.cpp create mode 100644 tests/generic/test_ref.cpp create mode 100644 tests/generic/test_set.cpp create mode 100644 tests/generic/test_size.cpp create mode 100644 tests/generic/test_snake_case_to_camel_case.cpp create mode 100644 tests/generic/test_snake_case_to_pascal_case.cpp create mode 100644 tests/generic/test_string_map.cpp create mode 100644 tests/generic/test_tagged_union.cpp create mode 100644 tests/generic/test_timestamp.cpp create mode 100644 tests/generic/test_unique_ptr.cpp create mode 100644 tests/generic/test_unique_ptr2.cpp create mode 100644 tests/generic/test_variant.cpp create mode 100644 tests/generic/test_wstring.cpp create mode 100644 tests/generic/write_and_read.hpp diff --git a/.github/workflows/linux-clang-14.yaml b/.github/workflows/linux-clang-14.yaml index 14f441c0..585606e0 100644 --- a/.github/workflows/linux-clang-14.yaml +++ b/.github/workflows/linux-clang-14.yaml @@ -34,6 +34,7 @@ jobs: ./build/tests/bson/reflect-cpp-bson-tests ./build/tests/cbor/reflect-cpp-cbor-tests ./build/tests/flexbuffers/reflect-cpp-flexbuffers-tests + ./build/tests/generic/reflect-cpp-generic-tests ./build/tests/json/reflect-cpp-json-tests ./build/tests/json_c_arrays_and_inheritance/reflect-cpp-json-c-arrays-and-inheritance-tests ./build/tests/msgpack/reflect-cpp-msgpack-tests diff --git a/.github/workflows/linux-clang-16.yaml b/.github/workflows/linux-clang-16.yaml index dab550e3..c714c8b3 100644 --- a/.github/workflows/linux-clang-16.yaml +++ b/.github/workflows/linux-clang-16.yaml @@ -34,6 +34,7 @@ jobs: ./build/tests/bson/reflect-cpp-bson-tests ./build/tests/cbor/reflect-cpp-cbor-tests ./build/tests/flexbuffers/reflect-cpp-flexbuffers-tests + ./build/tests/generic/reflect-cpp-generic-tests ./build/tests/json/reflect-cpp-json-tests ./build/tests/json_c_arrays_and_inheritance/reflect-cpp-json-c-arrays-and-inheritance-tests ./build/tests/msgpack/reflect-cpp-msgpack-tests diff --git a/.github/workflows/linux-gcc.yaml b/.github/workflows/linux-gcc.yaml index 0a0b711a..6bfd0e8c 100644 --- a/.github/workflows/linux-gcc.yaml +++ b/.github/workflows/linux-gcc.yaml @@ -27,6 +27,7 @@ jobs: ./build/tests/bson/reflect-cpp-bson-tests ./build/tests/cbor/reflect-cpp-cbor-tests ./build/tests/flexbuffers/reflect-cpp-flexbuffers-tests + ./build/tests/generic/reflect-cpp-generic-tests ./build/tests/json/reflect-cpp-json-tests ./build/tests/json_c_arrays_and_inheritance/reflect-cpp-json-c-arrays-and-inheritance-tests ./build/tests/msgpack/reflect-cpp-msgpack-tests diff --git a/.github/workflows/macos-clang-arm.yaml b/.github/workflows/macos-clang-arm.yaml index 73db47d4..e2679467 100644 --- a/.github/workflows/macos-clang-arm.yaml +++ b/.github/workflows/macos-clang-arm.yaml @@ -29,6 +29,7 @@ jobs: ./build/tests/bson/reflect-cpp-bson-tests ./build/tests/cbor/reflect-cpp-cbor-tests ./build/tests/flexbuffers/reflect-cpp-flexbuffers-tests + ./build/tests/generic/reflect-cpp-generic-tests ./build/tests/json/reflect-cpp-json-tests ./build/tests/json_c_arrays_and_inheritance/reflect-cpp-json-c-arrays-and-inheritance-tests ./build/tests/msgpack/reflect-cpp-msgpack-tests diff --git a/.github/workflows/macos-clang-x64.yaml b/.github/workflows/macos-clang-x64.yaml index a757847d..8c8a84f4 100644 --- a/.github/workflows/macos-clang-x64.yaml +++ b/.github/workflows/macos-clang-x64.yaml @@ -26,6 +26,7 @@ jobs: ./build/tests/bson/reflect-cpp-bson-tests ./build/tests/cbor/reflect-cpp-cbor-tests ./build/tests/flexbuffers/reflect-cpp-flexbuffers-tests + ./build/tests/generic/reflect-cpp-generic-tests ./build/tests/json/reflect-cpp-json-tests ./build/tests/json_c_arrays_and_inheritance/reflect-cpp-json-c-arrays-and-inheritance-tests ./build/tests/msgpack/reflect-cpp-msgpack-tests diff --git a/.github/workflows/windows-msvc.yaml b/.github/workflows/windows-msvc.yaml index 068caeef..91ae24e2 100644 --- a/.github/workflows/windows-msvc.yaml +++ b/.github/workflows/windows-msvc.yaml @@ -24,6 +24,7 @@ jobs: .\build\tests\bson\Release\reflect-cpp-bson-tests.exe .\build\tests\cbor\Release\reflect-cpp-cbor-tests.exe .\build\tests\flexbuffers\Release\reflect-cpp-flexbuffers-tests.exe + .\build\tests\generic\Release\reflect-cpp-generic-tests.exe .\build\tests\msgpack\Release\reflect-cpp-msgpack-tests.exe .\build\tests\toml\Release\reflect-cpp-toml-tests.exe .\build\tests\xml\Release\reflect-cpp-xml-tests.exe diff --git a/README.md b/README.md index a214a2d5..36a153bf 100644 --- a/README.md +++ b/README.md @@ -529,8 +529,8 @@ The following compilers are supported: Simply copy the contents of the folders `include` and `src` into your source repository or add it to your include path and also add `src/reflectcpp.cpp` and `src/reflectcpp_json.cpp` and `src/yyjson.c` to your source files for compilation. -If you want to link to your own version of YYJSON, then only copy `src/reflectcpp.cpp` and `src/reflectcpp_json.cpp`. -If you don't need JSON support, then only copy `src/reflectcpp.cpp`. +If you want to link to your own version of YYJSON, then only add `src/reflectcpp.cpp` and `src/reflectcpp_json.cpp`. +If you don't need JSON support, then only add `src/reflectcpp.cpp`. If you need support for other serialization formats like flexbuffers or XML, you should also add `src/reflectcpp_.cpp` and include and link the respective libraries, as listed in the section on serialization formats. diff --git a/docs/generic.md b/docs/generic.md index 98a62e94..55759b27 100644 --- a/docs/generic.md +++ b/docs/generic.md @@ -8,7 +8,7 @@ have `rfl::Generic`. `rfl::Generic` is a convenience wrapper around the following type: ```cpp -std::variant; +std::variant; ``` `Object` and `Array` are defined as follows: @@ -53,14 +53,14 @@ The resulting JSON strings looks as follows: `rfl::Generic` contains some convenience methods that allow you to handle parsed data: -You can retrieve the underlying `std::variant` using `.get()`. This then allows you to handle allow possible six cases using the [visitor pattern](https://en.cppreference.com/w/cpp/utility/variant/visit). +You can retrieve the underlying `std::variant` using `.get()`. This then allows you to handle allow possible seven cases using the [visitor pattern](https://en.cppreference.com/w/cpp/utility/variant/visit). -If you have a guess what the types of a particular field might be, you can use any of the six convenience methods `.to_array()`, `.to_bool()`, `.to_double()`, `.to_int()`, `.to_object()`, `.to_string()`. Each +If you have a guess what the types of a particular field might be, you can use any of the seven convenience methods `.to_array()`, `.to_bool()`, `.to_double()`, `.to_int()`, `.to_null()`, `.to_object()`, `.to_string()`. Each of these methods will return an `rfl::Result<...>` with the corresponding type, if the `rfl::Generic` does indeed contain such a type. -If you prefer, you can also use the following six convenience *functions*: +If you prefer, you can also use the following seven convenience *functions*: -`rfl::to_array(...)`, `rfl::to_bool(...)`, `rfl::to_double(...)`, `rfl::to_int(...)`, `rfl::to_object(...)`, `rfl::to_string(...)`. +`rfl::to_array(...)`, `rfl::to_bool(...)`, `rfl::to_double(...)`, `rfl::to_int(...)`, `rfl::to_null`, `rfl::to_object(...)`, `rfl::to_string(...)`. These functions are particularly useful for monadic error handling: @@ -85,3 +85,59 @@ int age = homer.get("age").and_then(rfl::to_int).value(); This will throw an exception if any of our assumptions are false. Please refer to the part of the documentation on `rfl::Result` to learn more about monadic error handling. + +## `rfl::to_generic` and `rfl::from_generic` + +You can transform any struct that can be converted to a JSON to the equivalent generic instead. + +In other words: + +```cpp +assert(rfl::json::write(my_struct) == rfl::json::write(rfl::to_generic(my_struct))); +``` + +And: + +```cpp +assert(rfl::json::read(rfl::json::write(my_struct)).value() == rfl::to_generic(my_struct)); +``` + +What is more, you can apply any processors you want to: + +```cpp +assert(rfl::json::write(my_struct) == rfl::json::write(rfl::to_generic(my_struct))); + +assert(rfl::json::read(rfl::json::write(my_struct)).value() == rfl::to_generic(my_struct)); +``` + +Conversely, the same statements hold for reading. In other words: + +```cpp +assert(rfl::json::read(my_json_string).value() == rfl::from_generic(rfl::json::read(my_json_string).value()).value()); +``` + +Likewise, you can apply processors: + +```cpp +assert(rfl::json::read(my_json_string).value() == rfl::from_generic(rfl::json::read(my_json_string).value()).value()); +``` + +In fact, you can think of `rfl::from_generic` and `rfl::to_generic` as manifestations of the reader and writer interface. You could as well write `rfl::generic::read<...>(...)` and `rfl::generic::write(...)`. + +This can be used to dynamically build structs: + +```cpp +struct Person { + std::string first_name; + std::string last_name; + int age; +}; + +auto bart = rfl::Generic::Object(); +bart["first_name"] = "Bart"; +bart["last_name"] = "Simpson"; +bart["age"] = 10; + +const auto person = rfl::from_generic(bart).value(); +``` + diff --git a/include/rfl.hpp b/include/rfl.hpp index 456b3159..04892f1a 100644 --- a/include/rfl.hpp +++ b/include/rfl.hpp @@ -56,6 +56,7 @@ #include "rfl/extract_discriminators.hpp" #include "rfl/field_type.hpp" #include "rfl/fields.hpp" +#include "rfl/from_generic.hpp" #include "rfl/from_named_tuple.hpp" #include "rfl/get.hpp" #include "rfl/make_from_tuple.hpp" @@ -66,6 +67,7 @@ #include "rfl/patterns.hpp" #include "rfl/remove_fields.hpp" #include "rfl/replace.hpp" +#include "rfl/to_generic.hpp" #include "rfl/to_named_tuple.hpp" #include "rfl/to_view.hpp" #include "rfl/tuple_cat.hpp" diff --git a/include/rfl/Generic.hpp b/include/rfl/Generic.hpp index e751e942..9cd4389b 100644 --- a/include/rfl/Generic.hpp +++ b/include/rfl/Generic.hpp @@ -1,21 +1,28 @@ #ifndef RFL_GENERIC_HPP_ #define RFL_GENERIC_HPP_ +#include +#include #include #include #include #include "Object.hpp" #include "Result.hpp" +#include "Variant.hpp" namespace rfl { class Generic { public: + constexpr static std::nullopt_t Null = std::nullopt; + using Array = std::vector; using Object = rfl::Object; - using ReflectionType = - std::variant; + using VariantType = std::variant; + using ReflectionType = std::optional< + std::variant>; Generic(); @@ -23,34 +30,39 @@ class Generic { Generic(const Generic& _other); + Generic(const VariantType& _value); + + Generic(VariantType&& _value) noexcept; + Generic(const ReflectionType& _value); - Generic(ReflectionType&& _value) noexcept; - template , + typename std::enable_if, bool>::type = true> Generic(const T& _value) : value_(_value) {} template , + typename std::enable_if, bool>::type = true> Generic(T&& _value) noexcept : value_(std::forward(_value)) {} ~Generic(); /// Returns the underlying object. - const ReflectionType& get() const { return value_; } + const VariantType& get() const { return value_; } + + /// Whether the object contains the null value. + bool is_null() const noexcept; /// Assigns the underlying object. - Generic& operator=(const ReflectionType& _value); + Generic& operator=(const VariantType& _value); /// Assigns the underlying object. - Generic& operator=(ReflectionType&& _value) noexcept; + Generic& operator=(VariantType&& _value) noexcept; /// Assigns the underlying object. template , + typename std::enable_if, bool>::type = true> auto& operator=(const T& _value) { value_ = _value; @@ -64,7 +76,7 @@ class Generic { Generic& operator=(Generic&& _other); /// Returns the underlying object, necessary for the serialization to work. - const ReflectionType& reflection() const { return value_; }; + ReflectionType reflection() const noexcept; /// Casts the underlying value to an rfl::Generic::Array or returns an /// rfl::Error, if the underlying value is not an rfl::Generic::Array. @@ -86,12 +98,25 @@ class Generic { /// rfl::Error, if the underlying value is not an rfl::Generic::Object. Result to_object() const noexcept; + /// Casts the underlying value to rfl::Generic::Null or returns an + /// rfl::Error, if the underlying value is not rfl::Generic::Null. + Result to_null() const noexcept; + /// Casts the underlying value to a string or returns an rfl::Error, if the /// underlying value is not a string. Result to_string() const noexcept; + /// Returns the underlying variant. + VariantType& variant() noexcept { return value_; }; + + /// Returns the underlying variant. + const VariantType& variant() const noexcept { return value_; }; + private: - ReflectionType value_; + static VariantType from_reflection_type(const ReflectionType& _r) noexcept; + + private: + VariantType value_; }; /// Casts the underlying value to an rfl::Generic::Array or returns an @@ -120,6 +145,12 @@ inline Result to_object(const Generic& _g) noexcept { return _g.to_object(); } +/// Casts the underlying value to a double or returns an rfl::Error, if the +/// underlying value is not a double. +inline Result to_null(const Generic& _g) noexcept { + return _g.to_null(); +} + /// Casts the underlying value to a string or returns an rfl::Error, if the /// underlying value is not a string. inline Result to_string(const Generic& _g) noexcept { diff --git a/include/rfl/Object.hpp b/include/rfl/Object.hpp index 0053b502..1fca958a 100644 --- a/include/rfl/Object.hpp +++ b/include/rfl/Object.hpp @@ -128,6 +128,16 @@ class Object { insert(std::make_pair(std::move(_k), std::move(_v))); } + /// Inserts a new element at the end. + void insert(const std::string_view& _k, const T& _v) { + insert(std::make_pair(std::string(_k), _v)); + } + + /// Inserts a new element at the end. + void insert(const std::string_view& _k, T&& _v) { + insert(std::make_pair(std::string(_k), std::move(_v))); + } + /// Alias for insert that primarily exists for compatability with standard /// containers. template diff --git a/include/rfl/Variant.hpp b/include/rfl/Variant.hpp index b6041823..59b12f7c 100644 --- a/include/rfl/Variant.hpp +++ b/include/rfl/Variant.hpp @@ -14,6 +14,7 @@ #include "internal/nth_element_t.hpp" #include "internal/variant/find_max_size.hpp" #include "internal/variant/is_alternative_type.hpp" +#include "internal/variant/is_convertible_to.hpp" #include "internal/variant/result_t.hpp" namespace rfl { @@ -40,6 +41,9 @@ class Variant { template using Index = std::integral_constant; + template + struct TypeWrapper {}; + public: Variant() { using FirstAlternative = internal::nth_element_t<0, AlternativeTypes...>; @@ -233,6 +237,21 @@ class Variant { _other.visit(copy_one); } + template + void copy_from_other_type(const T& _t) { + bool set = false; + const auto copy_one = [&, this](const T& _t, + const TypeWrapper) { + if constexpr (std::is_convertible_v) { + if (!set) { + move_from_type(AltType(_t)); + set = true; + } + } + }; + (copy_one(_t, TypeWrapper{}), ...); + } + template void copy_from_type(const T& _t) noexcept { using CurrentType = std::remove_cvref_t; @@ -442,7 +461,7 @@ class Variant { }; template -constexpr T* get_if(Variant& _v) noexcept { +constexpr T* get_if(Variant* _v) noexcept { const auto get = [](auto& _v) -> T* { using Type = std::remove_cvref_t; if constexpr (std::is_same>()) { @@ -451,11 +470,11 @@ constexpr T* get_if(Variant& _v) noexcept { return nullptr; } }; - return _v.visit(get); + return _v->visit(get); } template -constexpr const T* get_if(const Variant& _v) noexcept { +constexpr const T* get_if(const Variant* _v) noexcept { const auto get = [](const auto& _v) -> const T* { using Type = std::remove_cvref_t; if constexpr (std::is_same>()) { @@ -464,24 +483,24 @@ constexpr const T* get_if(const Variant& _v) noexcept { return nullptr; } }; - return _v.visit(get); + return _v->visit(get); } template -constexpr auto* get_if(Variant& _v) noexcept { +constexpr auto* get_if(Variant* _v) noexcept { using T = internal::nth_element_t<_i, Types...>; return get_if(_v); } template -constexpr auto* get_if(const Variant& _v) noexcept { +constexpr auto* get_if(const Variant* _v) noexcept { using T = internal::nth_element_t<_i, Types...>; return get_if(_v); } template constexpr T& get(Variant& _v) { - auto ptr = get_if(_v); + auto ptr = get_if(&_v); if (!ptr) { throw std::runtime_error("Variant does not contain signified type."); } @@ -490,7 +509,7 @@ constexpr T& get(Variant& _v) { template constexpr T&& get(Variant&& _v) { - auto ptr = get_if(_v); + auto ptr = get_if(&_v); if (!ptr) { throw std::runtime_error("Variant does not contain signified type."); } @@ -499,7 +518,7 @@ constexpr T&& get(Variant&& _v) { template constexpr const T& get(const Variant& _v) { - auto ptr = get_if(_v); + auto ptr = get_if(&_v); if (!ptr) { throw std::runtime_error("Variant does not contain signified type."); } @@ -508,7 +527,7 @@ constexpr const T& get(const Variant& _v) { template constexpr auto& get(Variant& _v) { - auto ptr = get_if<_i>(_v); + auto ptr = get_if<_i>(&_v); if (!ptr) { throw std::runtime_error("Variant does not contain signified type."); } @@ -517,7 +536,7 @@ constexpr auto& get(Variant& _v) { template constexpr auto&& get(Variant&& _v) { - auto ptr = get_if<_i>(_v); + auto ptr = get_if<_i>(&_v); if (!ptr) { throw std::runtime_error("Variant does not contain signified type."); } @@ -526,7 +545,7 @@ constexpr auto&& get(Variant&& _v) { template constexpr const auto& get(const Variant& _v) { - auto ptr = get_if<_i>(_v); + auto ptr = get_if<_i>(&_v); if (!ptr) { throw std::runtime_error("Variant does not contain signified type."); } diff --git a/include/rfl/from_generic.hpp b/include/rfl/from_generic.hpp new file mode 100644 index 00000000..0080a811 --- /dev/null +++ b/include/rfl/from_generic.hpp @@ -0,0 +1,17 @@ +#ifndef RFL_FROM_GENERIC_HPP_ +#define RFL_FROM_GENERIC_HPP_ + +#include "Generic.hpp" +#include "generic/read.hpp" + +namespace rfl { + +/// Generates the struct T from a named tuple. +template +auto from_generic(const Generic& _g) { + return rfl::generic::read(_g); +} + +} // namespace rfl + +#endif diff --git a/include/rfl/generic/Parser.hpp b/include/rfl/generic/Parser.hpp new file mode 100644 index 00000000..30d9015a --- /dev/null +++ b/include/rfl/generic/Parser.hpp @@ -0,0 +1,17 @@ +#ifndef GENERIC_PARSER_HPP_ +#define GENERIC_PARSER_HPP_ + +#include "../parsing/Parser.hpp" +#include "Reader.hpp" +#include "Writer.hpp" + +namespace rfl { +namespace generic { + +template +using Parser = parsing::Parser; + +} +} // namespace rfl + +#endif diff --git a/include/rfl/generic/Reader.hpp b/include/rfl/generic/Reader.hpp new file mode 100644 index 00000000..5da2ebe6 --- /dev/null +++ b/include/rfl/generic/Reader.hpp @@ -0,0 +1,89 @@ +#ifndef GENERIC_READER_HPP_ +#define GENERIC_READER_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../Bytestring.hpp" +#include "../Generic.hpp" +#include "../Result.hpp" +#include "../always_false.hpp" + +namespace rfl::generic { + +struct Reader { + using InputArrayType = Generic::Array; + using InputObjectType = Generic::Object; + using InputVarType = Generic; + + template + static constexpr bool has_custom_constructor = false; + + rfl::Result get_field_from_array( + const size_t _idx, const InputArrayType& _arr) const noexcept; + + rfl::Result get_field_from_object( + const std::string& _name, const InputObjectType& _obj) const noexcept; + + bool is_empty(const InputVarType& _var) const noexcept; + + template + rfl::Result to_basic_type(const InputVarType& _var) const noexcept { + if constexpr (std::is_same, std::string>()) { + return _var.to_string(); + } else if constexpr (std::is_same, bool>()) { + return _var.to_bool(); + } else if constexpr (std::is_floating_point>()) { + return _var.to_double().transform( + [](const auto& _v) { return static_cast(_v); }); + } else if constexpr (std::is_integral>()) { + return _var.to_int().transform( + [](const auto& _v) { return static_cast(_v); }); + } else { + static_assert(rfl::always_false_v, "Unsupported type."); + } + } + + template + std::optional read_array(const ArrayReader& _array_reader, + const InputArrayType& _arr) const noexcept { + for (const auto& v : _arr) { + const auto err = _array_reader.read(InputVarType(v)); + if (err) { + return err; + } + } + return std::nullopt; + } + + template + std::optional read_object(const ObjectReader& _object_reader, + const InputObjectType& _obj) const noexcept { + for (const auto& [k, v] : _obj) { + _object_reader.read(std::string_view(k), v); + } + return std::nullopt; + } + + rfl::Result to_array(const InputVarType& _var) const noexcept; + + rfl::Result to_object( + const InputVarType& _var) const noexcept; + + template + rfl::Result use_custom_constructor( + const InputVarType _var) const noexcept { + return rfl::Error("Not supported for generic types"); + } +}; + +} // namespace rfl::generic + +#endif diff --git a/include/rfl/generic/Writer.hpp b/include/rfl/generic/Writer.hpp new file mode 100644 index 00000000..98ffabd7 --- /dev/null +++ b/include/rfl/generic/Writer.hpp @@ -0,0 +1,117 @@ +#ifndef GENERIC_WRITER_HPP_ +#define GENERIC_WRITER_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../Generic.hpp" +#include "../Result.hpp" +#include "../Variant.hpp" +#include "../always_false.hpp" + +namespace rfl::generic { + +struct Writer { + struct OutputArray { + Generic::Array* val_; + }; + + struct OutputObject { + Generic::Object* val_; + }; + + using OutputArrayType = OutputArray; + using OutputObjectType = OutputObject; + using OutputVarType = Generic; + + Writer() {} + + ~Writer() = default; + + OutputArrayType array_as_root(const size_t _size) const noexcept; + + OutputObjectType object_as_root(const size_t _size) const noexcept; + + OutputVarType null_as_root() const noexcept; + + template + OutputVarType value_as_root(const T& _var) const noexcept { + root_ = to_generic(_var); + return root_; + } + + OutputArrayType add_array_to_array(const size_t _size, + OutputArrayType* _parent) const noexcept; + + OutputArrayType add_array_to_object(const std::string_view& _name, + const size_t _size, + OutputObjectType* _parent) const noexcept; + + OutputObjectType add_object_to_array(const size_t _size, + OutputArrayType* _parent) const noexcept; + + OutputObjectType add_object_to_object( + const std::string_view& _name, const size_t _size, + OutputObjectType* _parent) const noexcept; + + template + OutputVarType add_value_to_array(const T& _var, + OutputArrayType* _parent) const noexcept { + const auto g = to_generic(_var); + _parent->val_->push_back(g); + return g; + } + + template + OutputVarType add_value_to_object(const std::string_view& _name, + const T& _var, + OutputObjectType* _parent) const noexcept { + const auto g = to_generic(_var); + _parent->val_->insert(_name, g); + return g; + } + + OutputVarType add_null_to_array(OutputArrayType* _parent) const noexcept; + + OutputVarType add_null_to_object(const std::string_view& _name, + OutputObjectType* _parent) const noexcept; + + void end_array(OutputArrayType* _arr) const noexcept {} + + void end_object(OutputObjectType* _obj) const noexcept {} + + OutputVarType& root() { return root_; } + + private: + template + OutputVarType to_generic(const T& _var) const noexcept { + if constexpr (std::is_same, std::string>()) { + return OutputVarType(_var); + } else if constexpr (std::is_same, bool>()) { + return OutputVarType(_var); + } else if constexpr (std::is_floating_point>()) { + return OutputVarType(static_cast(_var)); + } else if constexpr (std::is_integral>()) { + return OutputVarType(static_cast(_var)); + } else { + static_assert(always_false_v, "Unsupported type"); + } + return OutputVarType{}; + } + + private: + mutable OutputVarType root_; +}; + +} // namespace rfl::generic + +#endif diff --git a/include/rfl/generic/read.hpp b/include/rfl/generic/read.hpp new file mode 100644 index 00000000..2a0e61a4 --- /dev/null +++ b/include/rfl/generic/read.hpp @@ -0,0 +1,25 @@ +#ifndef GENERIC_READ_HPP_ +#define GENERIC_READ_HPP_ + +#include +#include + +#include "../Generic.hpp" +#include "../Processors.hpp" +#include "../Result.hpp" +#include "Parser.hpp" + +namespace rfl { +namespace generic { + +/// Parses an object from a generic type. +template +auto read(const Generic& _g) { + const auto r = Reader(); + return Parser>::read(r, _g); +} + +} // namespace generic +} // namespace rfl + +#endif diff --git a/include/rfl/generic/write.hpp b/include/rfl/generic/write.hpp new file mode 100644 index 00000000..f2019ca0 --- /dev/null +++ b/include/rfl/generic/write.hpp @@ -0,0 +1,29 @@ +#ifndef GENERIC_WRITE_HPP_ +#define GENERIC_WRITE_HPP_ + +#include +#include +#include +#include + +#include "../Generic.hpp" +#include "../parsing/Parent.hpp" +#include "Parser.hpp" + +namespace rfl { +namespace generic { + +/// Writes an object to a generic. +template +Generic write(const auto& _t) { + using T = std::remove_cvref_t; + using ParentType = parsing::Parent; + auto w = Writer(); + Parser>::write(w, _t, typename ParentType::Root{}); + return w.root(); +} + +} // namespace generic +} // namespace rfl + +#endif diff --git a/include/rfl/internal/variant/is_convertible_to.hpp b/include/rfl/internal/variant/is_convertible_to.hpp new file mode 100644 index 00000000..8121bf74 --- /dev/null +++ b/include/rfl/internal/variant/is_convertible_to.hpp @@ -0,0 +1,17 @@ +#ifndef RFL_INTERNAL_VARIANT_IS_CONVERTIBLE_TO_HPP_ +#define RFL_INTERNAL_VARIANT_IS_CONVERTIBLE_TO_HPP_ + +#include + +#include "../element_index.hpp" + +namespace rfl::internal::variant { + +template +static constexpr bool is_convertible_to() { + return std::disjunction_v...>; +} + +} // namespace rfl::internal::variant + +#endif diff --git a/include/rfl/parsing/call_destructors_on_tuple_where_necessary.hpp b/include/rfl/parsing/call_destructors_on_tuple_where_necessary.hpp index 09ae685a..77d7e991 100644 --- a/include/rfl/parsing/call_destructors_on_tuple_where_necessary.hpp +++ b/include/rfl/parsing/call_destructors_on_tuple_where_necessary.hpp @@ -16,7 +16,6 @@ template void call_destructor_on_one_tuple_element_if_necessary(const size_t _num_set, TupleType* _tup) { using FieldType = tuple_element_t<_i, TupleType>; - using OriginalType = std::remove_cv_t; using ValueType = std::remove_cv_t>; if constexpr (!std::is_array_v && std::is_destructible_v) { diff --git a/include/rfl/to_generic.hpp b/include/rfl/to_generic.hpp new file mode 100644 index 00000000..acd5efbe --- /dev/null +++ b/include/rfl/to_generic.hpp @@ -0,0 +1,17 @@ +#ifndef RFL_TO_GENERIC_HPP_ +#define RFL_TO_GENERIC_HPP_ + +#include "Generic.hpp" +#include "generic/write.hpp" + +namespace rfl { + +/// Generates a generic that is equivalent to the struct _t. +template +Generic to_generic(const auto& _t) { + return rfl::generic::write(_t); +} + +} // namespace rfl + +#endif diff --git a/src/reflectcpp.cpp b/src/reflectcpp.cpp index cbd73b92..52cf1c11 100644 --- a/src/reflectcpp.cpp +++ b/src/reflectcpp.cpp @@ -30,4 +30,6 @@ SOFTWARE. // compilation. #include "rfl/Generic.cpp" +#include "rfl/generic/Reader.cpp" +#include "rfl/generic/Writer.cpp" #include "rfl/parsing/schema/Type.cpp" diff --git a/src/rfl/Generic.cpp b/src/rfl/Generic.cpp index cdc78d54..2065de59 100644 --- a/src/rfl/Generic.cpp +++ b/src/rfl/Generic.cpp @@ -34,19 +34,33 @@ Generic::Generic(Generic&& _other) noexcept = default; Generic::Generic(const Generic& _other) = default; -Generic::Generic(const ReflectionType& _value) : value_(_value) {} +Generic::Generic(const VariantType& _value) : value_(_value) {} -Generic::Generic(ReflectionType&& _value) noexcept - : value_(std::move(_value)) {} +Generic::Generic(VariantType&& _value) noexcept : value_(std::move(_value)) {} + +Generic::Generic(const ReflectionType& _r) : value_(from_reflection_type(_r)) {} Generic::~Generic() = default; -Generic& Generic::operator=(const ReflectionType& _value) { +Generic::VariantType Generic::from_reflection_type( + const ReflectionType& _r) noexcept { + if (!_r) { + return std::nullopt; + } else { + return std::visit([](const auto& _v) -> VariantType { return _v; }, *_r); + } +} + +bool Generic::is_null() const noexcept { + return std::get_if(&value_) && true; +} + +Generic& Generic::operator=(const VariantType& _value) { value_ = _value; return *this; } -Generic& Generic::operator=(ReflectionType&& _value) noexcept { +Generic& Generic::operator=(VariantType&& _value) noexcept { value_ = std::move(_value); return *this; } @@ -55,6 +69,11 @@ Generic& Generic::operator=(const Generic& _other) = default; Generic& Generic::operator=(Generic&& _other) = default; +Generic::ReflectionType Generic::reflection() const noexcept { + return std::visit([](const auto& _v) -> ReflectionType { return _v; }, + value_); +} + Result Generic::to_array() const noexcept { if (const auto* ptr = std::get_if(&value_)) { return *ptr; @@ -66,7 +85,7 @@ Result Generic::to_array() const noexcept { } Result Generic::to_bool() const noexcept { - if (const auto* ptr = std::get_if(&value_)) { + if (const bool* ptr = std::get_if(&value_)) { return *ptr; } else { return Error( @@ -75,7 +94,7 @@ Result Generic::to_bool() const noexcept { } Result Generic::to_double() const noexcept { - if (const auto* ptr = std::get_if(&value_)) { + if (const double* ptr = std::get_if(&value_)) { return *ptr; } else { return Error( @@ -84,7 +103,7 @@ Result Generic::to_double() const noexcept { } Result Generic::to_int() const noexcept { - if (const auto* ptr = std::get_if(&value_)) { + if (const int* ptr = std::get_if(&value_)) { return *ptr; } else { return Error( @@ -102,6 +121,16 @@ Result Generic::to_object() const noexcept { } } +Result Generic::to_null() const noexcept { + if (const auto* ptr = std::get_if(&value_)) { + return *ptr; + } else { + return Error( + "rfl::Generic: Could not cast the underlying value to " + "rfl::Generic::Null."); + } +} + Result Generic::to_string() const noexcept { if (const auto* ptr = std::get_if(&value_)) { return *ptr; diff --git a/src/rfl/generic/Reader.cpp b/src/rfl/generic/Reader.cpp new file mode 100644 index 00000000..e49000ef --- /dev/null +++ b/src/rfl/generic/Reader.cpp @@ -0,0 +1,58 @@ +/* + +MIT License + +Copyright (c) 2023-2024 Code17 GmbH + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +*/ + +#include "rfl/generic/Reader.hpp" + +namespace rfl::generic { + +rfl::Result Reader::get_field_from_array( + const size_t _idx, const InputArrayType& _arr) const noexcept { + if (_idx >= _arr.size()) { + return rfl::Error("Index " + std::to_string(_idx) + " of of bounds."); + } + return _arr[_idx]; +} + +rfl::Result Reader::get_field_from_object( + const std::string& _name, const InputObjectType& _obj) const noexcept { + return _obj.get(_name); +} + +bool Reader::is_empty(const InputVarType& _var) const noexcept { + return _var.is_null(); +} + +rfl::Result Reader::to_array( + const InputVarType& _var) const noexcept { + return _var.to_array(); +} + +rfl::Result Reader::to_object( + const InputVarType& _var) const noexcept { + return _var.to_object(); +} + +} // namespace rfl::generic diff --git a/src/rfl/generic/Writer.cpp b/src/rfl/generic/Writer.cpp new file mode 100644 index 00000000..4992ec6d --- /dev/null +++ b/src/rfl/generic/Writer.cpp @@ -0,0 +1,90 @@ +/* + +MIT License + +Copyright (c) 2023-2024 Code17 GmbH + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +*/ + +#include "rfl/generic/Writer.hpp" + +namespace rfl::generic { + +Writer::OutputArrayType Writer::array_as_root( + const size_t _size) const noexcept { + root_ = Generic::Array(); + return OutputArray{get_if(&root_.variant())}; +} + +Writer::OutputObjectType Writer::object_as_root( + const size_t _size) const noexcept { + root_ = Generic::Object(); + return OutputObject{get_if(&root_.variant())}; +} + +Writer::OutputVarType Writer::null_as_root() const noexcept { + root_ = Generic::Null; + return root_; +} + +Writer::OutputArrayType Writer::add_array_to_array( + const size_t _size, OutputArrayType* _parent) const noexcept { + _parent->val_->push_back(Generic(Generic::Array())); + return OutputArrayType{ + get_if(&_parent->val_->rbegin()->variant())}; +} + +Writer::OutputArrayType Writer::add_array_to_object( + const std::string_view& _name, const size_t _size, + OutputObjectType* _parent) const noexcept { + _parent->val_->insert(_name, Generic(Generic::Array())); + return OutputArrayType{ + get_if(&_parent->val_->rbegin()->second.variant())}; +} + +Writer::OutputObjectType Writer::add_object_to_array( + const size_t _size, OutputArrayType* _parent) const noexcept { + _parent->val_->push_back(Generic(Generic::Object())); + return OutputObjectType{ + get_if(&_parent->val_->rbegin()->variant())}; +} + +Writer::OutputObjectType Writer::add_object_to_object( + const std::string_view& _name, const size_t _size, + OutputObjectType* _parent) const noexcept { + _parent->val_->insert(_name, Generic(Generic::Object())); + return OutputObjectType{ + get_if(&_parent->val_->rbegin()->second.variant())}; +} + +Writer::OutputVarType Writer::add_null_to_array( + OutputArrayType* _parent) const noexcept { + _parent->val_->push_back(Generic(Generic::Null)); + return Generic::Null; +} + +Writer::OutputVarType Writer::add_null_to_object( + const std::string_view& _name, OutputObjectType* _parent) const noexcept { + _parent->val_->insert(_name, Generic(Generic::Null)); + return Generic::Null; +} + +} // namespace rfl::generic diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 277f6238..edcc9808 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -7,6 +7,7 @@ else() endif() if (REFLECTCPP_JSON) + add_subdirectory(generic) add_subdirectory(json) add_subdirectory(json_c_arrays_and_inheritance) endif () diff --git a/tests/generic/CMakeLists.txt b/tests/generic/CMakeLists.txt new file mode 100644 index 00000000..7c7ac4b4 --- /dev/null +++ b/tests/generic/CMakeLists.txt @@ -0,0 +1,18 @@ +project(reflect-cpp-generic-tests) + +file(GLOB_RECURSE SOURCES CONFIGURE_DEPENDS "*.cpp") + +add_executable( + reflect-cpp-generic-tests + ${SOURCES} + "${VCPKG_INSTALLED_DIR}/${VCPKG_TARGET_TRIPLET}/src/gtest_main.cc" +) + +target_include_directories(reflect-cpp-generic-tests SYSTEM PRIVATE "${VCPKG_INSTALLED_DIR}/${VCPKG_TARGET_TRIPLET}/include") + +target_link_libraries( + reflect-cpp-generic-tests + PRIVATE + reflectcpp + "${REFLECT_CPP_GTEST_LIB}" +) diff --git a/tests/generic/test_add_struct_name.cpp b/tests/generic/test_add_struct_name.cpp new file mode 100644 index 00000000..c077e7ab --- /dev/null +++ b/tests/generic/test_add_struct_name.cpp @@ -0,0 +1,46 @@ +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_add_struct_name { + +using Age = rfl::Validator, rfl::Maximum<130>>; + +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name = "Simpson"; + std::string town = "Springfield"; + rfl::Timestamp<"%Y-%m-%d"> birthday; + Age age; + rfl::Email email; + std::vector children; +}; + +TEST(generic, test_add_struct_name) { + 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); +} +} // namespace test_add_struct_name diff --git a/tests/generic/test_array.cpp b/tests/generic/test_array.cpp new file mode 100644 index 00000000..42da200e --- /dev/null +++ b/tests/generic/test_array.cpp @@ -0,0 +1,31 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_array { + +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name = "Simpson"; + std::unique_ptr> children = nullptr; +}; + +TEST(generic, test_array) { + auto bart = Person{.first_name = "Bart"}; + + auto lisa = Person{.first_name = "Lisa"}; + + auto maggie = Person{.first_name = "Maggie"}; + + const auto homer = Person{ + .first_name = "Homer", + .children = std::make_unique>(std::array{ + std::move(bart), std::move(lisa), std::move(maggie)})}; + + write_and_read(homer); +} +} // namespace test_array diff --git a/tests/generic/test_box.cpp b/tests/generic/test_box.cpp new file mode 100644 index 00000000..2e819e8d --- /dev/null +++ b/tests/generic/test_box.cpp @@ -0,0 +1,44 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_box { + +struct DecisionTree { + struct Leaf { + using Tag = rfl::Literal<"Leaf">; + double value; + }; + + struct Node { + using Tag = rfl::Literal<"Node">; + rfl::Rename<"criticalValue", double> critical_value; + rfl::Box lesser; + rfl::Box greater; + }; + + using LeafOrNode = rfl::TaggedUnion<"type", Leaf, Node>; + + rfl::Field<"leafOrNode", LeafOrNode> leaf_or_node; +}; + +TEST(generic, test_box) { + auto leaf1 = DecisionTree::Leaf{.value = 3.0}; + + auto leaf2 = DecisionTree::Leaf{.value = 5.0}; + + auto node = DecisionTree::Node{ + .critical_value = 10.0, + .lesser = rfl::make_box(DecisionTree{leaf1}), + .greater = rfl::make_box(DecisionTree{leaf2})}; + + const DecisionTree tree{.leaf_or_node = std::move(node)}; + + write_and_read(tree); + +} +} // namespace test_box diff --git a/tests/generic/test_combined_processors.cpp b/tests/generic/test_combined_processors.cpp new file mode 100644 index 00000000..640ff064 --- /dev/null +++ b/tests/generic/test_combined_processors.cpp @@ -0,0 +1,49 @@ +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_combined_processors { + +using Age = rfl::Validator, rfl::Maximum<130>>; + +struct Person { + std::string first_name; + std::string last_name = "Simpson"; + std::string town = "Springfield"; + rfl::Timestamp<"%Y-%m-%d"> birthday; + Age age; + rfl::Email email; + std::vector children; +}; + +TEST(generic, test_combined_processors) { + 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})}; + + using Processors = + rfl::Processors>; + + write_and_read(homer); +} +} // namespace test_combined_processors diff --git a/tests/generic/test_custom_class1.cpp b/tests/generic/test_custom_class1.cpp new file mode 100644 index 00000000..5691923e --- /dev/null +++ b/tests/generic/test_custom_class1.cpp @@ -0,0 +1,36 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_custom_class1 { + +struct Person { + struct PersonImpl { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name = "Simpson"; + std::vector children; + }; + + using ReflectionType = PersonImpl; + + Person(const PersonImpl& _impl) : impl(_impl) {} + + Person(const std::string& _first_name) + : impl(PersonImpl{.first_name = _first_name}) {} + + const ReflectionType& reflection() const { return impl; }; + + private: + PersonImpl impl; +}; + +TEST(generic, test_custom_class1) { + const auto bart = Person("Bart"); + + write_and_read(bart); +} +} // namespace test_custom_class1 diff --git a/tests/generic/test_custom_class3.cpp b/tests/generic/test_custom_class3.cpp new file mode 100644 index 00000000..278ecba3 --- /dev/null +++ b/tests/generic/test_custom_class3.cpp @@ -0,0 +1,64 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_custom_class3 { + +struct Person { + Person(const std::string& _first_name, const std::string& _last_name, + const int _age) + : first_name_(_first_name), last_name_(_last_name), age_(_age) {} + + const auto& first_name() const { return first_name_; } + + const auto& last_name() const { return last_name_; } + + auto age() const { return age_; } + + private: + std::string first_name_; + std::string last_name_; + int age_; +}; + +struct PersonImpl { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + int age; + + static PersonImpl from_class(const Person& _p) noexcept { + return PersonImpl{.first_name = _p.first_name(), + .last_name = _p.last_name(), + .age = _p.age()}; + } + + Person to_class() const { return Person(first_name(), last_name(), age); } +}; +} // namespace test_custom_class3 + +namespace rfl { +namespace parsing { + +template +struct Parser + : public CustomParser {}; + +} // namespace parsing +} // namespace rfl + +namespace test_custom_class3 { + +TEST(generic, test_custom_class3) { + const auto bart = Person("Bart", "Simpson", 10); + + write_and_read(bart); +} + +} // namespace test_custom_class3 diff --git a/tests/generic/test_custom_class4.cpp b/tests/generic/test_custom_class4.cpp new file mode 100644 index 00000000..bf97dbac --- /dev/null +++ b/tests/generic/test_custom_class4.cpp @@ -0,0 +1,65 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_custom_class4 { + +struct Person { + Person(const std::string& _first_name, + const rfl::Box& _last_name, int _age) + : first_name_(_first_name), + last_name_(rfl::make_box(*_last_name)), + age_(_age) {} + + const auto& first_name() const { return first_name_; } + + const auto& last_name() const { return last_name_; } + + auto age() const { return age_; } + + private: + std::string first_name_; + rfl::Box last_name_; + int age_; +}; + +struct PersonImpl { + rfl::Field<"firstName", std::string> first_name; + rfl::Field<"lastName", rfl::Box> last_name; + rfl::Field<"age", int> age; + + static PersonImpl from_class(const Person& _p) noexcept { + return PersonImpl{.first_name = _p.first_name(), + .last_name = rfl::make_box(*_p.last_name()), + .age = _p.age()}; + } +}; + +} // namespace test_custom_class4 + +namespace rfl { +namespace parsing { + +template +struct Parser + : public CustomParser {}; + +} // namespace parsing +} // namespace rfl + +namespace test_custom_class4 { + +TEST(generic, test_custom_class4) { + const auto bart = test_custom_class4::Person( + "Bart", rfl::make_box("Simpson"), 10); + + write_and_read(bart); +} +} // namespace test_custom_class4 diff --git a/tests/generic/test_default_values.cpp b/tests/generic/test_default_values.cpp new file mode 100644 index 00000000..5ceee9ee --- /dev/null +++ b/tests/generic/test_default_values.cpp @@ -0,0 +1,27 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_default_values { + +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name = "Simpson"; + std::vector children; +}; + +TEST(generic, test_default_values) { + const auto bart = Person{.first_name = "Bart"}; + const auto lisa = Person{.first_name = "Lisa"}; + const auto maggie = Person{.first_name = "Maggie"}; + const auto homer = + Person{.first_name = "Homer", + .children = std::vector({bart, lisa, maggie})}; + + write_and_read(homer); +} +} // namespace test_default_values diff --git a/tests/generic/test_deque.cpp b/tests/generic/test_deque.cpp new file mode 100644 index 00000000..f272b19c --- /dev/null +++ b/tests/generic/test_deque.cpp @@ -0,0 +1,28 @@ +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_deque { + +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name = "Simpson"; + std::unique_ptr> children; +}; + +TEST(generic, test_default_values) { + auto children = std::make_unique>(); + children->emplace_back(Person{.first_name = "Bart"}); + children->emplace_back(Person{.first_name = "Lisa"}); + children->emplace_back(Person{.first_name = "Maggie"}); + + const auto homer = + Person{.first_name = "Homer", .children = std::move(children)}; + + write_and_read(homer); + +} +} // namespace test_deque diff --git a/tests/generic/test_enum.cpp b/tests/generic/test_enum.cpp new file mode 100644 index 00000000..60608b51 --- /dev/null +++ b/tests/generic/test_enum.cpp @@ -0,0 +1,24 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_enum { + +enum class Color { red, green, blue, yellow }; + +struct Circle { + float radius; + Color color; +}; + +TEST(generic, test_enum) { + const auto circle = Circle{.radius = 2.0, .color = Color::green}; + + write_and_read(circle); +} + +} // namespace test_enum diff --git a/tests/generic/test_field_variant.cpp b/tests/generic/test_field_variant.cpp new file mode 100644 index 00000000..5855c369 --- /dev/null +++ b/tests/generic/test_field_variant.cpp @@ -0,0 +1,34 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_field_variant { + +struct Circle { + double radius; +}; + +struct Rectangle { + double height; + double width; +}; + +struct Square { + double width; +}; + +using Shapes = rfl::Variant, + rfl::Field<"rectangle", Rectangle>, + rfl::Field<"square", rfl::Box>>; + +TEST(generic, test_field_variant) { + const Shapes r = + rfl::make_field<"rectangle">(Rectangle{.height = 10, .width = 5}); + + write_and_read(r); +} +} // namespace test_field_variant diff --git a/tests/generic/test_flag_enum.cpp b/tests/generic/test_flag_enum.cpp new file mode 100644 index 00000000..9b914db2 --- /dev/null +++ b/tests/generic/test_flag_enum.cpp @@ -0,0 +1,35 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_flag_enum { + +enum class Color { + red = 256, + green = 512, + blue = 1024, + yellow = 2048, + orange = (256 | 2048) // red + yellow = orange +}; + +inline Color operator|(Color c1, Color c2) { + return static_cast(static_cast(c1) | static_cast(c2)); +} + +struct Circle { + float radius; + Color color; +}; + +TEST(generic, test_flag_enum) { + const auto circle = + Circle{.radius = 2.0, .color = Color::blue | Color::orange}; + + write_and_read(circle); +} + +} // namespace test_flag_enum diff --git a/tests/generic/test_flag_enum_with_int.cpp b/tests/generic/test_flag_enum_with_int.cpp new file mode 100644 index 00000000..ec77a1a6 --- /dev/null +++ b/tests/generic/test_flag_enum_with_int.cpp @@ -0,0 +1,34 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_flag_enum_with_int { + +enum class Color { + red = 256, + green = 512, + blue = 1024, + yellow = 2048, + orange = (256 | 2048) // red + yellow = orange +}; + +inline Color operator|(Color c1, Color c2) { + return static_cast(static_cast(c1) | static_cast(c2)); +} + +struct Circle { + float radius; + Color color; +}; + +TEST(generic, test_flag_enum_with_int) { + const auto circle = Circle{.radius = 2.0, .color = static_cast(10000)}; + + write_and_read(circle); +} + +} // namespace test_flag_enum_with_int diff --git a/tests/generic/test_flatten.cpp b/tests/generic/test_flatten.cpp new file mode 100644 index 00000000..caecb3f7 --- /dev/null +++ b/tests/generic/test_flatten.cpp @@ -0,0 +1,33 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_flatten { + +struct Person { + rfl::Field<"firstName", std::string> first_name; + rfl::Field<"lastName", rfl::Box> last_name; + rfl::Field<"age", int> age; +}; + +struct Employee { + rfl::Flatten person; + rfl::Field<"employer", rfl::Box> employer; + rfl::Field<"salary", float> salary; +}; + +TEST(generic, test_flatten) { + const auto employee = Employee{ + .person = Person{.first_name = "Homer", + .last_name = rfl::make_box("Simpson"), + .age = 45}, + .employer = rfl::make_box("Mr. Burns"), + .salary = 60000.0}; + + write_and_read(employee); +} +} // namespace test_flatten diff --git a/tests/generic/test_flatten_anonymous.cpp b/tests/generic/test_flatten_anonymous.cpp new file mode 100644 index 00000000..908e381b --- /dev/null +++ b/tests/generic/test_flatten_anonymous.cpp @@ -0,0 +1,34 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_flatten_anonymous { + +struct Person { + std::string first_name; + rfl::Box last_name; + int age; +}; + +struct Employee { + rfl::Flatten person; + rfl::Box employer; + float salary; +}; + +TEST(generic, test_flatten_anonymous) { + const auto employee = Employee{ + .person = Person{.first_name = "Homer", + .last_name = rfl::make_box("Simpson"), + .age = 45}, + .employer = rfl::make_box("Mr. Burns"), + .salary = 60000.0}; + + write_and_read(employee); +} + +} // namespace test_flatten_anonymous diff --git a/tests/generic/test_forward_list.cpp b/tests/generic/test_forward_list.cpp new file mode 100644 index 00000000..0dc273d2 --- /dev/null +++ b/tests/generic/test_forward_list.cpp @@ -0,0 +1,28 @@ +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_forward_list { + +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name = "Simpson"; + std::unique_ptr> children; +}; + +TEST(generic, test_forward_list) { + auto children = std::make_unique>(); + children->emplace_front(Person{.first_name = "Maggie"}); + children->emplace_front(Person{.first_name = "Lisa"}); + children->emplace_front(Person{.first_name = "Bart"}); + + const auto homer = + Person{.first_name = "Homer", .children = std::move(children)}; + + write_and_read(homer); + +} +} // namespace test_forward_list diff --git a/tests/generic/test_literal.cpp b/tests/generic/test_literal.cpp new file mode 100644 index 00000000..07c2f340 --- /dev/null +++ b/tests/generic/test_literal.cpp @@ -0,0 +1,25 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_literal { + +using FirstName = rfl::Literal<"Homer", "Marge", "Bart", "Lisa", "Maggie">; +using LastName = rfl::Literal<"Simpson">; + +struct Person { + rfl::Rename<"firstName", FirstName> first_name; + rfl::Rename<"lastName", LastName> last_name; + std::vector children; +}; + +TEST(generic, test_literal) { + const auto bart = Person{.first_name = FirstName::make<"Bart">()}; + + write_and_read(bart); +} +} // namespace test_literal diff --git a/tests/generic/test_literal_map.cpp b/tests/generic/test_literal_map.cpp new file mode 100644 index 00000000..29398f66 --- /dev/null +++ b/tests/generic/test_literal_map.cpp @@ -0,0 +1,23 @@ +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_literal_map { + +using FieldName = rfl::Literal<"firstName", "lastName">; + +TEST(generic, test_literal_map) { + std::map> homer; + homer.insert(std::make_pair(FieldName::make<"firstName">(), + std::make_unique("Homer"))); + homer.insert(std::make_pair(FieldName::make<"lastName">(), + std::make_unique("Simpson"))); + + write_and_read(homer); +} +} // namespace test_literal_map diff --git a/tests/generic/test_map.cpp b/tests/generic/test_map.cpp new file mode 100644 index 00000000..2d93c09c --- /dev/null +++ b/tests/generic/test_map.cpp @@ -0,0 +1,27 @@ +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_map { + +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name = "Simpson"; + std::map children; +}; + +TEST(generic, test_map) { + auto children = std::map(); + children.insert(std::make_pair("child1", Person{.first_name = "Bart"})); + children.insert(std::make_pair("child2", Person{.first_name = "Lisa"})); + children.insert(std::make_pair("child3", Person{.first_name = "Maggie"})); + + const auto homer = + Person{.first_name = "Homer", .children = std::move(children)}; + + write_and_read(homer); +} +} // namespace test_map diff --git a/tests/generic/test_map_with_key_validation.cpp b/tests/generic/test_map_with_key_validation.cpp new file mode 100644 index 00000000..51ea916b --- /dev/null +++ b/tests/generic/test_map_with_key_validation.cpp @@ -0,0 +1,28 @@ +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_map_with_key_validation { + +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name = "Simpson"; + std::unique_ptr> children; +}; + +TEST(generic, test_map_with_key_validation) { + auto children = std::make_unique>(); + + children->insert(std::make_pair("Bart", Person{.first_name = "Bart"})); + children->insert(std::make_pair("Lisa", Person{.first_name = "Lisa"})); + children->insert(std::make_pair("Maggie", Person{.first_name = "Maggie"})); + + const auto homer = + Person{.first_name = "Homer", .children = std::move(children)}; + + write_and_read(homer); +} +} // namespace test_map_with_key_validation diff --git a/tests/generic/test_monster_example.cpp b/tests/generic/test_monster_example.cpp new file mode 100644 index 00000000..e2b78d7b --- /dev/null +++ b/tests/generic/test_monster_example.cpp @@ -0,0 +1,59 @@ +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_monster_example { + +using Color = rfl::Literal<"Red", "Green", "Blue">; + +struct Weapon { + std::string name; + short damage; +}; + +using Equipment = rfl::Variant>; + +struct Vec3 { + float x; + float y; + float z; +}; + +struct Monster { + Vec3 pos; + short mana = 150; + short hp = 100; + std::string name; + bool friendly = false; + std::vector inventory; + Color color = Color::make<"Blue">(); + std::vector weapons; + Equipment equipped; + std::vector path; +}; + +TEST(generic, test_monster_example) { + const auto sword = Weapon{.name = "Sword", .damage = 3}; + const auto axe = Weapon{.name = "Axe", .damage = 5}; + + const auto weapons = std::vector({sword, axe}); + + const auto position = Vec3{1.0f, 2.0f, 3.0f}; + + const auto inventory = std::vector({0, 1, 2, 3, 4, 5, 6, 7, 8, 9}); + + const auto orc = Monster{.pos = position, + .mana = 150, + .hp = 80, + .name = "MyMonster", + .inventory = inventory, + .color = Color::make<"Red">(), + .weapons = weapons, + .equipped = rfl::make_field<"weapon">(axe)}; + + write_and_read(orc); +} +} // namespace test_monster_example diff --git a/tests/generic/test_readme_example.cpp b/tests/generic/test_readme_example.cpp new file mode 100644 index 00000000..ae633bff --- /dev/null +++ b/tests/generic/test_readme_example.cpp @@ -0,0 +1,46 @@ +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_readme_example { + +using Age = rfl::Validator, rfl::Maximum<130>>; + +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name = "Simpson"; + std::string town = "Springfield"; + rfl::Timestamp<"%Y-%m-%d"> birthday; + Age age; + rfl::Email email; + std::vector child; +}; + +TEST(generic, test_readme_example) { + 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", + .child = std::vector({bart, lisa, maggie})}; + + write_and_read(homer); +} +} // namespace test_readme_example diff --git a/tests/generic/test_readme_example2.cpp b/tests/generic/test_readme_example2.cpp new file mode 100644 index 00000000..9c07de1b --- /dev/null +++ b/tests/generic/test_readme_example2.cpp @@ -0,0 +1,22 @@ +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_readme_example2 { + +struct Person { + std::string first_name; + std::string last_name; + int age; +}; + +TEST(generic, test_readme_example2) { + const auto homer = + Person{.first_name = "Homer", .last_name = "Simpson", .age = 45}; + + write_and_read(homer); +} +} // namespace test_readme_example2 diff --git a/tests/generic/test_ref.cpp b/tests/generic/test_ref.cpp new file mode 100644 index 00000000..135e4a3b --- /dev/null +++ b/tests/generic/test_ref.cpp @@ -0,0 +1,44 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_ref { + +struct DecisionTree { + struct Leaf { + using Tag = rfl::Literal<"Leaf">; + double value; + }; + + struct Node { + using Tag = rfl::Literal<"Node">; + rfl::Rename<"criticalValue", double> critical_value; + rfl::Ref lesser; + rfl::Ref greater; + }; + + using LeafOrNode = rfl::TaggedUnion<"type", Leaf, Node>; + + rfl::Field<"leafOrNode", LeafOrNode> leaf_or_node; +}; + +TEST(generic, test_ref) { + const auto leaf1 = DecisionTree::Leaf{.value = 3.0}; + + const auto leaf2 = DecisionTree::Leaf{.value = 5.0}; + + auto node = DecisionTree::Node{ + .critical_value = 10.0, + .lesser = rfl::make_ref(DecisionTree{leaf1}), + .greater = rfl::make_ref(DecisionTree{leaf2})}; + + const DecisionTree tree{.leaf_or_node = std::move(node)}; + + write_and_read(tree); + +} +} // namespace test_ref diff --git a/tests/generic/test_set.cpp b/tests/generic/test_set.cpp new file mode 100644 index 00000000..23b1db3e --- /dev/null +++ b/tests/generic/test_set.cpp @@ -0,0 +1,25 @@ +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_set { + +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name = "Simpson"; + std::unique_ptr> children; +}; + +TEST(generic, test_set) { + auto children = std::make_unique>( + std::set({"Bart", "Lisa", "Maggie"})); + + const auto homer = + Person{.first_name = "Homer", .children = std::move(children)}; + + write_and_read(homer); +} +} // namespace test_set diff --git a/tests/generic/test_size.cpp b/tests/generic/test_size.cpp new file mode 100644 index 00000000..4725afa4 --- /dev/null +++ b/tests/generic/test_size.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_size { + +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + rfl::Timestamp<"%Y-%m-%d"> birthday; + rfl::Validator, + rfl::Size, rfl::EqualTo<3>>>> + children; +}; + +TEST(generic, test_size) { + const auto bart = Person{ + .first_name = "Bart", .last_name = "Simpson", .birthday = "1987-04-19"}; + + const auto lisa = Person{ + .first_name = "Lisa", .last_name = "Simpson", .birthday = "1987-04-19"}; + + const auto maggie = Person{ + .first_name = "Maggie", .last_name = "Simpson", .birthday = "1987-04-19"}; + + const auto homer = + Person{.first_name = "Homer", + .last_name = "Simpson", + .birthday = "1987-04-19", + .children = std::vector({bart, lisa, maggie})}; + + write_and_read(homer); +} +} // namespace test_size diff --git a/tests/generic/test_snake_case_to_camel_case.cpp b/tests/generic/test_snake_case_to_camel_case.cpp new file mode 100644 index 00000000..3c4df29d --- /dev/null +++ b/tests/generic/test_snake_case_to_camel_case.cpp @@ -0,0 +1,34 @@ +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_snake_case_to_camel_case { + +struct Person { + std::string first_name; + std::string last_name; + rfl::Timestamp<"%Y-%m-%d"> birthday; + std::vector children; +}; + +TEST(generic, test_snake_case_to_camel_case) { + const auto bart = Person{ + .first_name = "Bart", .last_name = "Simpson", .birthday = "1987-04-19"}; + + const auto lisa = Person{ + .first_name = "Lisa", .last_name = "Simpson", .birthday = "1987-04-19"}; + + const auto maggie = Person{ + .first_name = "Maggie", .last_name = "Simpson", .birthday = "1987-04-19"}; + + const auto homer = + Person{.first_name = "Homer", + .last_name = "Simpson", + .birthday = "1987-04-19", + .children = std::vector({bart, lisa, maggie})}; + + write_and_read(homer); +} +} // namespace test_snake_case_to_camel_case diff --git a/tests/generic/test_snake_case_to_pascal_case.cpp b/tests/generic/test_snake_case_to_pascal_case.cpp new file mode 100644 index 00000000..c709445c --- /dev/null +++ b/tests/generic/test_snake_case_to_pascal_case.cpp @@ -0,0 +1,34 @@ +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_snake_case_to_pascal_case { + +struct Person { + std::string first_name; + std::string last_name; + rfl::Timestamp<"%Y-%m-%d"> birthday; + std::vector children; +}; + +TEST(bson, test_snake_case_to_pascal_case) { + const auto bart = Person{ + .first_name = "Bart", .last_name = "Simpson", .birthday = "1987-04-19"}; + + const auto lisa = Person{ + .first_name = "Lisa", .last_name = "Simpson", .birthday = "1987-04-19"}; + + const auto maggie = Person{ + .first_name = "Maggie", .last_name = "Simpson", .birthday = "1987-04-19"}; + + const auto homer = + Person{.first_name = "Homer", + .last_name = "Simpson", + .birthday = "1987-04-19", + .children = std::vector({bart, lisa, maggie})}; + + write_and_read(homer); +} +} // namespace test_snake_case_to_pascal_case diff --git a/tests/generic/test_string_map.cpp b/tests/generic/test_string_map.cpp new file mode 100644 index 00000000..13cd03cb --- /dev/null +++ b/tests/generic/test_string_map.cpp @@ -0,0 +1,19 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_string_map { +TEST(generic, test_string_map) { + std::map> homer; + homer.insert( + std::make_pair("firstName", std::make_unique("Homer"))); + homer.insert( + std::make_pair("lastName", std::make_unique("Simpson"))); + + write_and_read(homer); +} +} // namespace test_string_map diff --git a/tests/generic/test_tagged_union.cpp b/tests/generic/test_tagged_union.cpp new file mode 100644 index 00000000..2b677109 --- /dev/null +++ b/tests/generic/test_tagged_union.cpp @@ -0,0 +1,30 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_tagged_union { + +struct Circle { + double radius; +}; + +struct Rectangle { + double height; + double width; +}; + +struct Square { + double width; +}; + +using Shapes = rfl::TaggedUnion<"shape", Circle, Square, Rectangle>; + +TEST(generic, test_tagged_union) { + const Shapes r = Rectangle{.height = 10, .width = 5}; + write_and_read(r); +} +} // namespace test_tagged_union diff --git a/tests/generic/test_timestamp.cpp b/tests/generic/test_timestamp.cpp new file mode 100644 index 00000000..e6b86bdc --- /dev/null +++ b/tests/generic/test_timestamp.cpp @@ -0,0 +1,31 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_timestamp { + +using TS = rfl::Timestamp<"%Y-%m-%d">; + +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name = "Simpson"; + TS birthday; +}; + +TEST(generic, test_timestamp) { + const auto result = TS::from_string("nonsense"); + + if (result) { + std::cout << "Failed: Expected an error, but got none." << std::endl; + return; + } + + const auto bart = Person{.first_name = "Bart", .birthday = "1987-04-19"}; + + write_and_read(bart); +} +} // namespace test_timestamp diff --git a/tests/generic/test_unique_ptr.cpp b/tests/generic/test_unique_ptr.cpp new file mode 100644 index 00000000..38748000 --- /dev/null +++ b/tests/generic/test_unique_ptr.cpp @@ -0,0 +1,28 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_unique_ptr { + +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name = "Simpson"; + std::unique_ptr> children; +}; + +TEST(generic, test_unique_ptr) { + auto children = std::make_unique>(); + children->emplace_back(Person{.first_name = "Bart"}); + children->emplace_back(Person{.first_name = "Lisa"}); + children->emplace_back(Person{.first_name = "Maggie"}); + + const auto homer = + Person{.first_name = "Homer", .children = std::move(children)}; + + write_and_read(homer); +} +} // namespace test_unique_ptr diff --git a/tests/generic/test_unique_ptr2.cpp b/tests/generic/test_unique_ptr2.cpp new file mode 100644 index 00000000..6ec7eaa2 --- /dev/null +++ b/tests/generic/test_unique_ptr2.cpp @@ -0,0 +1,43 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_unique_ptr2 { + +struct DecisionTree { + struct Leaf { + using Tag = rfl::Literal<"Leaf">; + double value; + }; + + struct Node { + using Tag = rfl::Literal<"Node">; + rfl::Rename<"criticalValue", double> critical_value; + std::unique_ptr lesser; + std::unique_ptr greater; + }; + + using LeafOrNode = rfl::TaggedUnion<"type", Leaf, Node>; + + rfl::Field<"leafOrNode", LeafOrNode> leaf_or_node; +}; + +TEST(generic, test_unique_ptr2) { + auto leaf1 = DecisionTree::Leaf{.value = 3.0}; + + auto leaf2 = DecisionTree::Leaf{.value = 5.0}; + + auto node = DecisionTree::Node{ + .critical_value = 10.0, + .lesser = std::make_unique(DecisionTree{leaf1}), + .greater = std::make_unique(DecisionTree{leaf2})}; + + const DecisionTree tree{.leaf_or_node = std::move(node)}; + + write_and_read(tree); +} +} // namespace test_unique_ptr2 diff --git a/tests/generic/test_variant.cpp b/tests/generic/test_variant.cpp new file mode 100644 index 00000000..3767b020 --- /dev/null +++ b/tests/generic/test_variant.cpp @@ -0,0 +1,31 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_variant { + +struct Circle { + double radius; +}; + +struct Rectangle { + double height; + double width; +}; + +struct Square { + double width; +}; + +using Shapes = std::variant>; + +TEST(generic, test_variant) { + const Shapes r = Rectangle{.height = 10, .width = 5}; + + write_and_read(r); +} +} // namespace test_variant diff --git a/tests/generic/test_wstring.cpp b/tests/generic/test_wstring.cpp new file mode 100644 index 00000000..a11ca8fa --- /dev/null +++ b/tests/generic/test_wstring.cpp @@ -0,0 +1,21 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +struct TestStruct { + std::string theNormalString; + std::wstring theWiderString; +}; + +namespace test_wstring { +TEST(generic, test_wstring) { + const auto test = TestStruct{.theNormalString = "The normal string", + .theWiderString = L"The wider string"}; + + write_and_read(test); +} +} // namespace test_wstring diff --git a/tests/generic/write_and_read.hpp b/tests/generic/write_and_read.hpp new file mode 100644 index 00000000..7aa0e7da --- /dev/null +++ b/tests/generic/write_and_read.hpp @@ -0,0 +1,22 @@ +#ifndef WRITE_AND_READ_ +#define WRITE_AND_READ_ + +#include + +#include +#include +#include + +template +void write_and_read(const auto& _struct) { + using T = std::remove_cvref_t; + const auto serialized1 = rfl::to_generic(_struct); + EXPECT_EQ(rfl::json::write(serialized1), rfl::json::write(_struct)); + const auto res = rfl::from_generic(serialized1); + EXPECT_TRUE(res && true) << "Test failed on read. Error: " + << res.error().value().what(); + EXPECT_EQ(rfl::json::write(serialized1), + rfl::json::write(res.value())); +} + +#endif diff --git a/tests/json/test_json_schema.cpp b/tests/json/test_json_schema.cpp index 800641f5..2fb8de88 100644 --- a/tests/json/test_json_schema.cpp +++ b/tests/json/test_json_schema.cpp @@ -68,7 +68,7 @@ TEST(json, test_json_schema) { Person>>(); const std::string expected = - R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/definitions/test_json_schema__Person","description":"JSON schema that describes the required attributes for the person class.","definitions":{"rfl__Generic":{"anyOf":[{"type":"boolean"},{"type":"integer"},{"type":"number"},{"type":"string"},{"type":"object","additionalProperties":{"$ref":"#/definitions/rfl__Generic"}},{"type":"array","items":{"$ref":"#/definitions/rfl__Generic"}}]},"test_json_schema__Circle":{"type":"object","properties":{"radius":{"type":"number"}},"required":["radius"]},"test_json_schema__Circle__tagged":{"type":"object","properties":{"radius":{"type":"number"},"shape":{"type":"string","enum":["Circle"]}},"required":["radius","shape"]},"test_json_schema__Person":{"type":"object","properties":{"age":{"allOf":[{"minimum":0,"type":"integer"},{"maximum":130,"type":"integer"}]},"children":{"type":"array","description":"The person's children. Pass an empty array for no children.","items":{"$ref":"#/definitions/test_json_schema__Person"}},"color":{"type":"string","enum":["red","green","blue"]},"email":{"type":"string","description":"Must be a proper email in the form xxx@xxx.xxx.","pattern":"^[a-zA-Z0-9._%+\\-]+@[a-zA-Z0-9.\\-]+\\.[a-zA-Z]{2,}$"},"fieldVariant":{"anyOf":[{"type":"object","properties":{"rectangle":{"$ref":"#/definitions/test_json_schema__Rectangle"}},"required":["rectangle"]},{"type":"object","properties":{"square":{"$ref":"#/definitions/test_json_schema__Square"}},"required":["square"]},{"type":"object","properties":{"circle":{"$ref":"#/definitions/test_json_schema__Circle"}},"required":["circle"]}]},"firstName":{"type":"string"},"generic":{"$ref":"#/definitions/rfl__Generic"},"lastName":{"type":"string"},"salary":{"type":"number"},"taggedUnion":{"anyOf":[{"$ref":"#/definitions/test_json_schema__Rectangle__tagged"},{"$ref":"#/definitions/test_json_schema__Square__tagged"},{"$ref":"#/definitions/test_json_schema__Circle__tagged"}]},"town":{"type":"string"},"tuple":{"type":"array","prefixItems":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/definitions/test_json_schema__Person"}},{"type":"integer"}],"items":false},"variant":{"anyOf":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/definitions/test_json_schema__Person"}},{"type":"integer"}]},"with_extra_fields":{"$ref":"#/definitions/test_json_schema__WithExtraFields"}},"required":["age","children","color","email","fieldVariant","firstName","generic","lastName","salary","taggedUnion","town","tuple","variant","with_extra_fields"]},"test_json_schema__Rectangle":{"type":"object","properties":{"height":{"type":"number"},"width":{"type":"number"}},"required":["height","width"]},"test_json_schema__Rectangle__tagged":{"type":"object","properties":{"height":{"type":"number"},"shape":{"type":"string","enum":["Rectangle"]},"width":{"type":"number"}},"required":["height","shape","width"]},"test_json_schema__Square":{"type":"object","properties":{"width":{"type":"number"}},"required":["width"]},"test_json_schema__Square__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Square"]},"width":{"type":"number"}},"required":["shape","width"]},"test_json_schema__WithExtraFields":{"type":"object","properties":{"f1":{"type":"string"},"f2":{"type":"string"}},"required":["f1","f2"],"additionalProperties":{"type":"string"}}}})"; + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/definitions/test_json_schema__Person","description":"JSON schema that describes the required attributes for the person class.","definitions":{"rfl__Generic":{"anyOf":[{"anyOf":[{"type":"boolean"},{"type":"integer"},{"type":"number"},{"type":"string"},{"type":"object","additionalProperties":{"$ref":"#/definitions/rfl__Generic"}},{"type":"array","items":{"$ref":"#/definitions/rfl__Generic"}}]},{"type":"null"}]},"test_json_schema__Circle":{"type":"object","properties":{"radius":{"type":"number"}},"required":["radius"]},"test_json_schema__Circle__tagged":{"type":"object","properties":{"radius":{"type":"number"},"shape":{"type":"string","enum":["Circle"]}},"required":["radius","shape"]},"test_json_schema__Person":{"type":"object","properties":{"age":{"allOf":[{"minimum":0,"type":"integer"},{"maximum":130,"type":"integer"}]},"children":{"type":"array","description":"The person's children. Pass an empty array for no children.","items":{"$ref":"#/definitions/test_json_schema__Person"}},"color":{"type":"string","enum":["red","green","blue"]},"email":{"type":"string","description":"Must be a proper email in the form xxx@xxx.xxx.","pattern":"^[a-zA-Z0-9._%+\\-]+@[a-zA-Z0-9.\\-]+\\.[a-zA-Z]{2,}$"},"fieldVariant":{"anyOf":[{"type":"object","properties":{"rectangle":{"$ref":"#/definitions/test_json_schema__Rectangle"}},"required":["rectangle"]},{"type":"object","properties":{"square":{"$ref":"#/definitions/test_json_schema__Square"}},"required":["square"]},{"type":"object","properties":{"circle":{"$ref":"#/definitions/test_json_schema__Circle"}},"required":["circle"]}]},"firstName":{"type":"string"},"generic":{"$ref":"#/definitions/rfl__Generic"},"lastName":{"type":"string"},"salary":{"type":"number"},"taggedUnion":{"anyOf":[{"$ref":"#/definitions/test_json_schema__Rectangle__tagged"},{"$ref":"#/definitions/test_json_schema__Square__tagged"},{"$ref":"#/definitions/test_json_schema__Circle__tagged"}]},"town":{"type":"string"},"tuple":{"type":"array","prefixItems":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/definitions/test_json_schema__Person"}},{"type":"integer"}],"items":false},"variant":{"anyOf":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/definitions/test_json_schema__Person"}},{"type":"integer"}]},"with_extra_fields":{"$ref":"#/definitions/test_json_schema__WithExtraFields"}},"required":["age","children","color","email","fieldVariant","firstName","generic","lastName","salary","taggedUnion","town","tuple","variant","with_extra_fields"]},"test_json_schema__Rectangle":{"type":"object","properties":{"height":{"type":"number"},"width":{"type":"number"}},"required":["height","width"]},"test_json_schema__Rectangle__tagged":{"type":"object","properties":{"height":{"type":"number"},"shape":{"type":"string","enum":["Rectangle"]},"width":{"type":"number"}},"required":["height","shape","width"]},"test_json_schema__Square":{"type":"object","properties":{"width":{"type":"number"}},"required":["width"]},"test_json_schema__Square__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Square"]},"width":{"type":"number"}},"required":["shape","width"]},"test_json_schema__WithExtraFields":{"type":"object","properties":{"f1":{"type":"string"},"f2":{"type":"string"}},"required":["f1","f2"],"additionalProperties":{"type":"string"}}}})"; EXPECT_EQ(json_schema, expected); } diff --git a/tests/json/test_rfl_variant_get_if.cpp b/tests/json/test_rfl_variant_get_if.cpp index 3339a339..2dd4a160 100644 --- a/tests/json/test_rfl_variant_get_if.cpp +++ b/tests/json/test_rfl_variant_get_if.cpp @@ -26,7 +26,7 @@ using Shapes = rfl::Variant>; TEST(json, test_rfl_variant_get_if) { const Shapes r = Rectangle{.height = 10, .width = 5}; - EXPECT_TRUE(rfl::get_if<1>(r) && true); - EXPECT_FALSE(rfl::get_if<0>(r) && true); + EXPECT_TRUE(rfl::get_if<1>(&r) && true); + EXPECT_FALSE(rfl::get_if<0>(&r) && true); } } // namespace test_rfl_variant_get_if