diff --git a/.gitignore b/.gitignore index 801e1bf5..eb6cda5f 100644 --- a/.gitignore +++ b/.gitignore @@ -41,6 +41,7 @@ **/build_clang/** # Output files +*.avro *.bson *.cbor *.json diff --git a/CMakeLists.txt b/CMakeLists.txt index ffcbbbb1..8824fa04 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3,6 +3,7 @@ cmake_minimum_required(VERSION 3.23) option(REFLECTCPP_BUILD_SHARED "Build shared library" ${BUILD_SHARED_LIBS}) option(REFLECTCPP_JSON "Enable JSON support" ON) # enabled by default +option(REFLECTCPP_AVRO "Enable AVRO support" OFF) option(REFLECTCPP_BSON "Enable BSON support" OFF) option(REFLECTCPP_CBOR "Enable CBOR support" OFF) option(REFLECTCPP_FLEXBUFFERS "Enable flexbuffers support" OFF) @@ -21,6 +22,7 @@ set(REFLECTCPP_USE_VCPKG_DEFAULT OFF) if(REFLECTCPP_BUILD_BENCHMARKS) set(REFLECTCPP_JSON ON CACHE BOOL "" FORCE) + set(REFLECTCPP_AVRO ON CACHE BOOL "" FORCE) set(REFLECTCPP_BSON ON CACHE BOOL "" FORCE) set(REFLECTCPP_CBOR ON CACHE BOOL "" FORCE) set(REFLECTCPP_FLEXBUFFERS ON CACHE BOOL "" FORCE) @@ -32,7 +34,7 @@ if(REFLECTCPP_BUILD_BENCHMARKS) endif() if (REFLECTCPP_BUILD_TESTS OR REFLECTCPP_BUILD_BENCHMARKS OR - (REFLECTCPP_JSON AND NOT REFLECTCPP_USE_BUNDLED_DEPENDENCIES) OR + (REFLECTCPP_JSON AND NOT REFLECTCPP_USE_BUNDLED_DEPENDENCIES) OR REFLECTCPP_AVRO OR REFLECTCPP_BSON OR REFLECTCPP_CBOR OR REFLECTCPP_FLEXBUFFERS OR REFLECTCPP_MSGPACK OR REFLECTCPP_XML OR REFLECTCPP_TOML OR REFLECTCPP_UBJSON OR REFLECTCPP_YAML) # enable vcpkg per default if require features other than JSON set(REFLECTCPP_USE_VCPKG_DEFAULT ON) @@ -101,6 +103,22 @@ if (REFLECTCPP_JSON) endif () endif () +if (REFLECTCPP_AVRO) + list(APPEND REFLECT_CPP_SOURCES + src/reflectcpp_avro.cpp + ) + find_package(jansson CONFIG REQUIRED) + if(REFLECTCPP_USE_VCPKG) + target_include_directories(reflectcpp SYSTEM PRIVATE "${VCPKG_INSTALLED_DIR}/${VCPKG_TARGET_TRIPLET}/include") + if (MSVC) + target_link_libraries(reflectcpp PRIVATE "${VCPKG_INSTALLED_DIR}/${VCPKG_TARGET_TRIPLET}/lib/avro${CMAKE_STATIC_LIBRARY_SUFFIX}") + else () + target_link_libraries(reflectcpp PRIVATE "${VCPKG_INSTALLED_DIR}/${VCPKG_TARGET_TRIPLET}/lib/libavro${CMAKE_STATIC_LIBRARY_SUFFIX}") + endif () + endif() + target_link_libraries(reflectcpp PRIVATE jansson::jansson) +endif () + if (REFLECTCPP_BSON) list(APPEND REFLECT_CPP_SOURCES src/reflectcpp_bson.cpp diff --git a/README.md b/README.md index 6cfb786a..0223d5aa 100644 --- a/README.md +++ b/README.md @@ -8,15 +8,7 @@ [![Generic badge](https://img.shields.io/badge/MSVC-17+-blue.svg)](https://shields.io/) [![Conan Center](https://img.shields.io/conan/v/reflect-cpp)](https://conan.io/center/recipes/reflect-cpp) - -**📖 Documentation**: https://rfl.getml.com — **👨‍💻 Source Code**: https://github.com/getml/reflect-cpp - ->
**📣 From the Author (12.11.2024):** Hi everyone, Patrick ([liuzicheng1987](https://github.com/liuzicheng1987)) here. With reflect-cpp reaching the 1k-star milestone, we’re excited to roll out an overhauled documentation site at [https://rfl.getml.com](https://rfl.getml.com/), giving it a permanent place in our company. Initially developed as an internal tool for our machine learning library, [getML](https://getml.com), reflect-cpp has grown into something much larger. -
A big thank you to all contributors for helping us reach this point! Your feedback, ideas, and dedication have been invaluable. -
As we look to the project’s future, I would like to hear your thoughts on potential new directions, discuss ideas to expand our user base, or learn more about what you’re building with it. For the next month, I am opening a few slots in my calendar for anyone who wants to [connect (link)](https://calendar.app.google/AaeziooCNierbwAZ8). -
*— Best, Patrick* -
  - +**📖 Documentation**: https://rfl.getml.com ![image](banner1.png) @@ -71,6 +63,7 @@ The following table lists the serialization formats currently supported by refle | Format | Library | Version | License | Remarks | |--------------|------------------------------------------------------|--------------|------------| -----------------------------------------------------| | JSON | [yyjson](https://github.com/ibireme/yyjson) | >= 0.8.0 | MIT | out-of-the-box support, included in this repository | +| Avro | [avro-c](https://avro.apache.org/docs/1.11.1/api/c/) | >= 1.11.3 | Apache 2.0 | Schemaful binary format | | BSON | [libbson](https://github.com/mongodb/mongo-c-driver) | >= 1.25.1 | Apache 2.0 | JSON-like binary format | | CBOR | [tinycbor](https://github.com/intel/tinycbor) | >= 0.6.0 | MIT | JSON-like binary format | | flexbuffers | [flatbuffers](https://github.com/google/flatbuffers) | >= 23.5.26 | Apache 2.0 | Schema-less version of flatbuffers, binary format | @@ -153,6 +146,7 @@ This will work for just about any example in the entire documentation and any supported format, except where explicitly noted otherwise: ```cpp +rfl::avro::write(homer); rfl::bson::write(homer); rfl::cbor::write(homer); rfl::flexbuf::write(homer); @@ -161,6 +155,7 @@ rfl::toml::write(homer); rfl::ubjson::write(homer); rfl::xml::write(homer); +rfl::avro::read(avro_bytes); rfl::bson::read(bson_bytes); rfl::cbor::read(cbor_bytes); rfl::flexbuf::read(flexbuf_bytes); diff --git a/benchmarks/all/canada_read.cpp b/benchmarks/all/canada_read.cpp index f3fb2158..21574752 100644 --- a/benchmarks/all/canada_read.cpp +++ b/benchmarks/all/canada_read.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -47,6 +48,18 @@ static FeatureCollection load_data() { // ---------------------------------------------------------------------------- +static void BM_canada_read_reflect_cpp_avro(benchmark::State &state) { + const auto schema = rfl::avro::to_schema(); + const auto data = rfl::avro::write(load_data(), schema); + for (auto _ : state) { + const auto res = rfl::avro::read(data, schema); + if (!res) { + std::cout << res.error()->what() << std::endl; + } + } +} +BENCHMARK(BM_canada_read_reflect_cpp_avro); + static void BM_canada_read_reflect_cpp_bson(benchmark::State &state) { const auto data = rfl::bson::write(load_data()); for (auto _ : state) { diff --git a/benchmarks/all/canada_write.cpp b/benchmarks/all/canada_write.cpp index bb5a9c3e..88c37282 100644 --- a/benchmarks/all/canada_write.cpp +++ b/benchmarks/all/canada_write.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -47,6 +48,18 @@ static FeatureCollection load_data() { // ---------------------------------------------------------------------------- +static void BM_canada_write_reflect_cpp_avro(benchmark::State &state) { + const auto schema = rfl::avro::to_schema(); + const auto data = load_data(); + for (auto _ : state) { + const auto output = rfl::avro::write(data, schema); + if (output.size() == 0) { + std::cout << "No output" << std::endl; + } + } +} +BENCHMARK(BM_canada_write_reflect_cpp_avro); + static void BM_canada_write_reflect_cpp_bson(benchmark::State &state) { const auto data = load_data(); for (auto _ : state) { diff --git a/benchmarks/all/licenses_read.cpp b/benchmarks/all/licenses_read.cpp index 3606aa41..7b53cd56 100644 --- a/benchmarks/all/licenses_read.cpp +++ b/benchmarks/all/licenses_read.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -63,6 +64,18 @@ static Licenses load_data() { // ---------------------------------------------------------------------------- +static void BM_licenses_read_reflect_cpp_avro(benchmark::State &state) { + const auto schema = rfl::avro::to_schema(); + const auto data = rfl::avro::write(load_data(), schema); + for (auto _ : state) { + const auto res = rfl::avro::read(data, schema); + if (!res) { + std::cout << res.error()->what() << std::endl; + } + } +} +BENCHMARK(BM_licenses_read_reflect_cpp_avro); + static void BM_licenses_read_reflect_cpp_bson(benchmark::State &state) { const auto data = rfl::bson::write(load_data()); for (auto _ : state) { diff --git a/benchmarks/all/licenses_write.cpp b/benchmarks/all/licenses_write.cpp index 282af309..ba68d917 100644 --- a/benchmarks/all/licenses_write.cpp +++ b/benchmarks/all/licenses_write.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -63,6 +64,18 @@ static Licenses load_data() { // ---------------------------------------------------------------------------- +static void BM_licenses_write_reflect_cpp_avro(benchmark::State &state) { + const auto schema = rfl::avro::to_schema(); + const auto data = load_data(); + for (auto _ : state) { + const auto output = rfl::avro::write(data, schema); + if (output.size() == 0) { + std::cout << "No output" << std::endl; + } + } +} +BENCHMARK(BM_licenses_write_reflect_cpp_avro); + static void BM_licenses_write_reflect_cpp_bson(benchmark::State &state) { const auto data = load_data(); for (auto _ : state) { diff --git a/benchmarks/all/person_read.cpp b/benchmarks/all/person_read.cpp index 13d02e00..0fae1193 100644 --- a/benchmarks/all/person_read.cpp +++ b/benchmarks/all/person_read.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -42,6 +43,18 @@ static Person load_data() { // ---------------------------------------------------------------------------- +static void BM_person_read_reflect_cpp_avro(benchmark::State &state) { + const auto schema = rfl::avro::to_schema(); + const auto data = rfl::avro::write(load_data(), schema); + for (auto _ : state) { + const auto res = rfl::avro::read(data, schema); + if (!res) { + std::cout << res.error()->what() << std::endl; + } + } +} +BENCHMARK(BM_person_read_reflect_cpp_avro); + static void BM_person_read_reflect_cpp_bson(benchmark::State &state) { const auto data = rfl::bson::write(load_data()); for (auto _ : state) { diff --git a/benchmarks/all/person_write.cpp b/benchmarks/all/person_write.cpp index 73110db8..fdf6f95b 100644 --- a/benchmarks/all/person_write.cpp +++ b/benchmarks/all/person_write.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -43,6 +44,18 @@ static Person load_data() { // ---------------------------------------------------------------------------- +static void BM_person_write_reflect_cpp_avro(benchmark::State &state) { + const auto schema = rfl::avro::to_schema(); + const auto data = load_data(); + for (auto _ : state) { + const auto output = rfl::avro::write(data, schema); + if (output.size() == 0) { + std::cout << "No output" << std::endl; + } + } +} +BENCHMARK(BM_person_write_reflect_cpp_avro); + static void BM_person_write_reflect_cpp_bson(benchmark::State &state) { const auto data = load_data(); for (auto _ : state) { diff --git a/docs/concepts/custom_classes.md b/docs/concepts/custom_classes.md index 7e44613d..99082c05 100644 --- a/docs/concepts/custom_classes.md +++ b/docs/concepts/custom_classes.md @@ -12,6 +12,9 @@ If you want your class to be supported by reflect-cpp, it needs to have the foll If you class fulfills these three conditions, then it is fully supported by all serialization and deserialization routines in reflect-cpp. +Please be aware that due to limitations of the Avro format, it is a good idea to always have a struct as your +`ReflectionType` when using Avro to avoid infinite recursions. + If you absolutely do not want to make any changes to your original class, you can implement a [custom parser](https://github.com/getml/reflect-cpp/blob/main/docs/custom_parser.md). ## Example 1: Using an Impl struct diff --git a/docs/generic.md b/docs/generic.md index 55759b27..8af89a30 100644 --- a/docs/generic.md +++ b/docs/generic.md @@ -5,6 +5,8 @@ reflect-cpp is intended to be used to directly parse into structs. Doing this is But in some cases, we simply cannot anticipate the complete structure of the data at compile time. For these cases, we have `rfl::Generic`. +Note that generics are not supported for Avro. + `rfl::Generic` is a convenience wrapper around the following type: ```cpp diff --git a/docs/index.md b/docs/index.md index 258fd149..8586af6e 100644 --- a/docs/index.md +++ b/docs/index.md @@ -18,17 +18,7 @@ hide: [![Generic badge](https://img.shields.io/badge/MSVC-17+-blue.svg)](https://shields.io/) [![Conan Center](https://img.shields.io/conan/v/reflect-cpp)](https://conan.io/center/recipes/reflect-cpp) -**📖 Documentation**: [https://rfl.getml.com](https://rfl.getml.com) — **👨‍💻 Source Code**: [https://github.com/getml/reflect-cpp](https://github.com/getml/reflect-cpp) - - - ->
**📣 From the Author (01.11.2024):** Hi everyone, Patrick ([liuzicheng1987](https://github.com/liuzicheng1987)) here. With reflect-cpp reaching the 1k-star milestone, we’re excited to roll out an overhauled documentation site at [https://rfl.getml.com](https://rfl.getml.com/), giving it a permanent place in our company. Initially developed as an internal tool for our machine learning library, [getML](https://getml.com), reflect-cpp has grown into something much larger. -
A big thank you to all contributors for helping us reach this point! Your feedback, ideas, and dedication have been invaluable. -
As we look to the project’s future, I would like to hear your thoughts on potential new directions, discuss ideas to expand our user base, or learn more about what you’re building with it. For the next month, I am opening a few slots in my calendar for anyone who wants to [connect (link)](https://calendar.app.google/AaeziooCNierbwAZ8). -
*— Best, Patrick* -
  - -
+ **💻 Source Code**: [https://github.com/getml/reflect-cpp](https://github.com/getml/reflect-cpp) **reflect-cpp** is a C++-20 library for **fast serialization, deserialization and validation** using reflection, similar to [pydantic](https://github.com/pydantic/pydantic) in Python, [serde](https://github.com/serde-rs) in Rust, [encoding](https://github.com/golang/go/tree/master/src/encoding) in Go or [aeson](https://github.com/haskell/aeson/tree/master) in Haskell. diff --git a/docs/install.md b/docs/install.md index 3196a136..c1e7c17e 100644 --- a/docs/install.md +++ b/docs/install.md @@ -68,6 +68,7 @@ To use reflect-cpp in your project: ```cmake add_subdirectory(reflect-cpp) # Add this project as a subdirectory +set(REFLECTCPP_AVRO ON) # Optional set(REFLECTCPP_BSON ON) # Optional set(REFLECTCPP_CBOR ON) # Optional set(REFLECTCPP_FLEXBUFFERS ON) # Optional @@ -110,7 +111,7 @@ conan build . --build=missing -s compiler.cppstd=gnu20 You can call `conan inspect .` to get an overview of the supported options. -If you want to include all supported formats, do the following: +If you want to include all formats supported on Conan, do the following: ```bash conan build . --build=missing -s compiler.cppstd=gnu20 -o *:with_cbor=True -o *:with_flatbuffers=True -o *:with_msgpack=True -o *:with_toml=True -o *:with_ubjson=True -o *:with_xml=True -o *:with_yaml=True diff --git a/docs/rfl_skip.md b/docs/rfl_skip.md index e256e206..2e53bb5b 100644 --- a/docs/rfl_skip.md +++ b/docs/rfl_skip.md @@ -2,6 +2,8 @@ It is possible to skip the serialization and deserialization of fields using `rfl::Skip`. +Note that `rfl::Skip` is unsupported by all schemaful formats, like Avro. + ```cpp struct Person { rfl::Rename<"firstName", std::string> first_name; diff --git a/docs/supported_formats/avro.md b/docs/supported_formats/avro.md new file mode 100644 index 00000000..4ceeeff0 --- /dev/null +++ b/docs/supported_formats/avro.md @@ -0,0 +1,133 @@ +# Avro + +For Avro support, you must also include the header `` and link to the `avro-c` library (https://avro.apache.org/docs/1.6.3/api/c/index.html). + +Avro is a schemaful binary format. This sets it apart from most other formats supported by reflect-cpp, which are schemaless. + +## Reading and writing + +Suppose you have a struct like this: + +```cpp +struct Person { + std::string first_name; + std::string last_name; + rfl::Timestamp<"%Y-%m-%d"> birthday; + std::vector children; +}; +``` + +A `Person` struct can be serialized to a bytes vector like this: + +```cpp +const auto person = Person{...}; +const std::vector bytes = rfl::avro::write(person); +``` + +You can parse bytes like this: + +```cpp +const rfl::Result result = rfl::avro::read(bytes); +``` + +## The schema + +However, Avro is a schemaful format, so before you serialize or +deserialize, you have to declare a schema. In the two function calls +above, this is abstracted away. + +But if you are repeated serializing or deserializing the same struct, +it is more efficient to generate the schema explicitly: + +```cpp +const auto schema = rfl::avro::to_schema(); + +const auto person = Person{...}; +const std::vector bytes = rfl::avro::write(person, schema); + +const rfl::Result result = rfl::avro::read(bytes, schema); +``` + +Avro schemas are created using a JSON-based schema language. You can +retrieve the JSON representation like this: + +```cpp +// Both calls are equivalent. +schema.json_str(); +schema.str(); +``` + +In this case, the resulting JSON schema representation looks like this: + +```json +{"type":"record","name":"Person","fields":[{"name":"first_name","type":{"type":"string"}},{"name":"last_name","type":{"type":"string"}},{"name":"birthday","type":{"type":"string"}},{"name":"children","type":{"type":"array","items":{"type":"Person"},"default":[]}}]} +``` + +## Loading and saving + +You can also load and save to disc using a very similar syntax: + +```cpp +const rfl::Result result = rfl::avro::load("/path/to/file.avro"); + +const auto person = Person{...}; +rfl::avro::save("/path/to/file.avro", person); +``` + +## Reading from and writing into streams + +You can also read from and write into any `std::istream` and `std::ostream` respectively. + +```cpp +const rfl::Result result = rfl::avro::read(my_istream); + +const auto person = Person{...}; +rfl::avro::write(person, my_ostream); +``` + +Note that `std::cout` is also an ostream, so this works as well: + +```cpp +rfl::avro::write(person, std::cout) << std::endl; +``` + +(Since Avro is a binary format, the readability of this will be limited, but it might be useful for debugging). + +## Custom constructors + +One of the great things about C++ is that it gives you control over +when and how you code is compiled. + +For large and complex systems of structs, it is often a good idea to split up +your code into smaller compilation units. You can do so using custom constructors. + +For the Avro format, these must be a static function on your struct or class called +`from_avro` that take a `rfl::avro::Reader::InputVarType` as input and return +the class or the class wrapped in `rfl::Result`. + +In your header file you can write something like this: + +```cpp +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + rfl::Timestamp<"%Y-%m-%d"> birthday; + + using InputVarType = typename rfl::avro::Reader::InputVarType; + static rfl::Result from_avro(const InputVarType& _obj); +}; +``` + +And in your source file, you implement `from_avro` as follows: + +```cpp +rfl::Result Person::from_avro(const InputVarType& _obj) { + const auto from_nt = [](auto&& _nt) { + return rfl::from_named_tuple(std::move(_nt)); + }; + return rfl::avro::read>(_obj) + .transform(from_nt); +} +``` + +This will force the compiler to only compile the Avro parsing when the source file is compiled. diff --git a/docs/supported_formats/supporting_your_own_format.md b/docs/supported_formats/supporting_your_own_format.md index 39557f7a..c6a85ac3 100644 --- a/docs/supported_formats/supporting_your_own_format.md +++ b/docs/supported_formats/supporting_your_own_format.md @@ -181,11 +181,13 @@ struct Reader { /// Retrieves a particular field from an array. /// Returns an rfl::Error if the index is out of bounds. + /// If your format is schemaful, you do not need this. rfl::Result get_field_from_array( const size_t _idx, const InputArrayType _arr) const noexcept {...} /// Retrieves a particular field from an object. /// Returns an rfl::Error if the field cannot be found. + /// If your format is schemaful, you do not need this. rfl::Result get_field_from_object( const std::string& _name, const InputObjectType& _obj) const noexcept {...} @@ -261,3 +263,178 @@ void read(const std::string_view& _name, 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`. + +## Additional requirements for schemaful formats + +Schemaful formats, like Apache Avro or Cap'n Proto, +are somewhat more complicated than schemaless ones. There are additional factors +to consider which do not apply schemaless formats: + +1. Schemaful formats needs to differentiate between *objects*, for which + the field names are known at compile time and *maps*, for which the + field names are not known at compile time. In schemaless formats, there + is no differentiation. + +2. Schemaful formats needs an explicit union types. This also means that + many of the problems we have with serializing `std::variant` which + requires us to develop concepts like `rfl::TaggedUnion` simply do not + apply to schemaful formats - the problem is already solved. + +### Additional requirements for schemaful writers + +Any schemaful reader additionally needs to define the following: + +1) An `OutputMapType`, which must contain key-value pairs. +2) An `OutputUnionType`, which represents an explicit union. + +```cpp +struct Writer { + using OutputArrayType = ...; + using OutputMapType = ...; + using OutputObjectType = ...; + using OutputUnionType = ...; + using OutputVarType = ...; + + /// Sets an empty map as the root element of the document. + /// Some serialization formats require you to pass the expected size in + /// advance. If you are not working with such a format, you can ignore the + /// parameter `size`. Returns the new array for further modification. + OutputMapType map_as_root(const size_t _size) const noexcept; + + /// Sets an empty union as the root element of the document. + OutputUnionType union_as_root() const noexcept; + + /// Adds an empty array to an existing map. Returns the new + /// array for further modification. + OutputArrayType add_array_to_map(const std::string_view& _name, + const size_t _size, + OutputMapType* _parent) const noexcept; + + /// Adds an empty array to an existing union. + /// The index refers to the index of the element in the union. + /// Returns the new array for further modification. + OutputArrayType add_array_to_union(const size_t _index, const size_t _size, + OutputUnionType* _parent) const noexcept; + + /// Adds an empty map to an existing array. Returns the new + /// map for further modification. + OutputMapType add_map_to_array(const size_t _size, + OutputArrayType* _parent) const noexcept; + + /// Adds an empty map to an existing map. The key or name of the field + /// is signified by `name`. Returns the new map for further modification. + OutputMapType add_map_to_map(const std::string_view& _name, + const size_t _size, + OutputMapType* _parent) const noexcept; + + /// Adds an empty map to an existing object. The key or name of the field + /// is signified by `name`. Returns the new map for further modification. + OutputMapType add_map_to_object(const std::string_view& _name, + const size_t _size, + OutputObjectType* _parent) const noexcept; + + /// Adds an empty map to an existing union. + /// The index refers to the index of the element in the union. + /// Returns the new map for further modification. + OutputMapType add_map_to_union(const size_t _index, const size_t _size, + OutputUnionType* _parent) const noexcept; + + /// Adds an empty object to an existing map. The key or name of the field + /// is signified by `name`. Returns the new object for further modification. + OutputObjectType add_object_to_map(const std::string_view& _name, + const size_t _size, + OutputMapType* _parent) const noexcept; + + /// Adds an empty object to an existing union. + /// The index refers to the index of the element in the union. + /// Returns the new object for further modification. + OutputObjectType add_object_to_union(const size_t _index, const size_t _size, + OutputUnionType* _parent) const noexcept; + + /// Adds an empty union to an existing array. Returns the new + /// union for further modification. + OutputUnionType add_union_to_array(OutputArrayType* _parent) const noexcept; + + /// Adds an empty union to an existing map. The key or name of the field + /// is signified by `name`. Returns the new union for further modification. + OutputUnionType add_union_to_map(const std::string_view& _name, + OutputMapType* _parent) const noexcept; + + /// Adds an empty union to an existing object. The key or name of the field + /// is signified by `name`. Returns the new union for further modification. + OutputUnionType add_union_to_object(const std::string_view& _name, + OutputObjectType* _parent) const noexcept; + + /// Adds an empty union to an existing union. + /// The index refers to the index of the element in the union. + /// Returns the new union for further modification. + OutputUnionType add_union_to_union(const size_t _index, + OutputUnionType* _parent) const noexcept; + + /// Adds a null value to a map. Returns an + /// OutputVarType containing the null value. + OutputVarType add_null_to_map(const std::string_view& _name, + OutputMapType* _parent) const noexcept; + + /// Adds a null value to a union. Returns an + /// OutputVarType containing the null value. + OutputVarType add_null_to_union(const size_t _index, + OutputUnionType* _parent) const noexcept; + + /// Adds a basic value (bool, numeric, string) to an existing map. The key + /// or name of the field is signified by `name`. Returns an + /// OutputVarType containing the new value. + template + OutputVarType add_value_to_map(const std::string_view& _name, const T& _var, + OutputMapType* _parent) const noexcept; + + /// Adds a basic value (bool, numeric, string) to an existing union. The key + /// or name of the field is signified by `name`. Returns an + /// OutputVarType containing the new value. + template + OutputVarType add_value_to_union(const size_t _index, const T& _var, + OutputUnionType* _parent) const noexcept; + + /// Signifies to the writer that we do not want to add any further elements to + /// this map. Some serialization formats require this. If you are working + /// with a serialization format that doesn't, just leave the function empty. + void end_map(OutputMapType* _obj) const noexcept; + +}; +``` + +### Additional requirements for schemaful readers + +Any schemaful reader additionally needs to define the following: + +1) An `InputMapType`, which must contain key-value pairs. +2) An `InputUnionType`, which represents an explicit union. + +```cpp +struct Reader { + using InputArrayType = ...; + using InputObjectType = ...; + using InputMapType = ...; + using InputUnionType = ...; + using InputVarType = ...; + + /// A schemaful reader needs to differentiate between objects, for which + /// the field names are known at compile time and maps, for which the + /// field names are not known at compile time. + rfl::Result to_map(const InputVarType& _var) const noexcept; + + /// read_map works exactly the same as read_object in schemaless formats. + template + std::optional read_map(const MapReader& _map_reader, + const InputMapType& _map) const noexcept; + + /// A schemaful reader needs an explicit union type. + rfl::Result to_union(const InputVarType& _var) const noexcept; + + /// read_union needs to be able to take an InputUnionType and return the corresponding + /// variant (like std::variant or rfl::Variant). + template + rfl::Result read_union( + const InputUnionType& _union) const noexcept; +}; +``` diff --git a/include/rfl/avro.hpp b/include/rfl/avro.hpp new file mode 100644 index 00000000..7678afb4 --- /dev/null +++ b/include/rfl/avro.hpp @@ -0,0 +1,15 @@ +#ifndef RFL_AVRO_HPP_ +#define RFL_AVRO_HPP_ + +#include "../rfl.hpp" +#include "avro/Parser.hpp" +#include "avro/Reader.hpp" +#include "avro/Schema.hpp" +#include "avro/Writer.hpp" +#include "avro/load.hpp" +#include "avro/read.hpp" +#include "avro/save.hpp" +#include "avro/to_schema.hpp" +#include "avro/write.hpp" + +#endif diff --git a/include/rfl/avro/Parser.hpp b/include/rfl/avro/Parser.hpp new file mode 100644 index 00000000..73276631 --- /dev/null +++ b/include/rfl/avro/Parser.hpp @@ -0,0 +1,111 @@ +#ifndef RFL_AVRO_PARSER_HPP_ +#define RFL_AVRO_PARSER_HPP_ + +#include "../Generic.hpp" +#include "../Tuple.hpp" +#include "../always_false.hpp" +#include "../parsing/Parser.hpp" +#include "Reader.hpp" +#include "Writer.hpp" + +namespace rfl { +namespace parsing { + +/// AVRO requires us to explicitly set all fields. Because +/// of that, we require all of the fields and then set them to nullptr, if +/// necessary. +template + requires AreReaderAndWriter> +struct Parser, + ProcessorsType> + : public NamedTupleParser< + avro::Reader, avro::Writer, + /*_ignore_empty_containers=*/false, + /*_all_required=*/true, + /*_no_field_names=*/ProcessorsType::no_field_names_, ProcessorsType, + FieldTypes...> {}; + +template + requires AreReaderAndWriter> +struct Parser, ProcessorsType> + : public TupleParser> {}; + +template + requires AreReaderAndWriter> +struct Parser, ProcessorsType> + : public TupleParser> {}; + +template + requires AreReaderAndWriter +struct Parser { + template + static Result read(const avro::Reader&, const T&) noexcept { + static_assert(always_false_v, "Generics are unsupported in Avro."); + return Error("Unsupported"); + } + + template + static void write(const avro::Writer&, const Generic&, const P&) noexcept { + static_assert(always_false_v

, "Generics are unsupported in Avro."); + } + + template + static schema::Type to_schema(T*) { + static_assert(always_false_v, "Generics are unsupported in Avro."); + return schema::Type{}; + } +}; + +template + requires AreReaderAndWriter< + avro::Reader, avro::Writer, + internal::Skip> +struct Parser, + ProcessorsType> { + using R = avro::Reader; + using W = avro::Writer; + + template + static Result> + read(const R&, const U&) noexcept { + static_assert(always_false_v, "rfl::Skip is unsupported in Avro."); + return Error("Unsupported"); + } + + template + static void write(const W& _w, + const internal::Skip& _skip, + const P& _parent) noexcept { + static_assert(always_false_v

, "rfl::Skip is unsupported in Avro."); + } + + template + static schema::Type to_schema(U* _definitions) { + static_assert(always_false_v, "rfl::Skip is unsupported in Avro."); + return schema::Type{}; + } +}; + +} // namespace parsing +} // namespace rfl + +namespace rfl { +namespace avro { + +template +using Parser = parsing::Parser; + +} +} // namespace rfl + +#endif diff --git a/include/rfl/avro/Reader.hpp b/include/rfl/avro/Reader.hpp new file mode 100644 index 00000000..528d1c51 --- /dev/null +++ b/include/rfl/avro/Reader.hpp @@ -0,0 +1,215 @@ +#ifndef RFL_AVRO_READER_HPP_ +#define RFL_AVRO_READER_HPP_ + +#include + +#include +#include +#include +#include +#include +#include + +#include "../Bytestring.hpp" +#include "../Result.hpp" +#include "../always_false.hpp" +#include "../internal/is_literal.hpp" + +namespace rfl::avro { + +struct Reader { + struct AVROInputArray { + const avro_value_t* val_; + }; + + struct AVROInputObject { + const avro_value_t* val_; + }; + + struct AVROInputMap { + const avro_value_t* val_; + }; + + struct AVROInputUnion { + const avro_value_t* val_; + }; + + struct AVROInputVar { + const avro_value_t* val_; + }; + + using InputArrayType = AVROInputArray; + using InputObjectType = AVROInputObject; + using InputMapType = AVROInputMap; + using InputUnionType = AVROInputUnion; + using InputVarType = AVROInputVar; + + template + static constexpr bool has_custom_constructor = + (requires(InputVarType var) { T::from_avro_obj(var); }); + + bool is_empty(const InputVarType& _var) const noexcept; + + template + rfl::Result to_basic_type(const InputVarType& _var) const noexcept { + const auto type = avro_value_get_type(_var.val_); + if constexpr (std::is_same, std::string>()) { + const char* c_str = nullptr; + size_t size = 0; + const auto err = avro_value_get_string(_var.val_, &c_str, &size); + if (err) { + return Error("Could not cast to string."); + } + if (size == 0) { + return std::string(""); + } + return std::string(c_str, size - 1); + } else if constexpr (std::is_same, + rfl::Bytestring>()) { + const void* ptr = nullptr; + size_t size = 0; + const auto err = avro_value_get_bytes(_var.val_, &ptr, &size); + if (err) { + return Error("Could not cast to bytestring."); + } + return rfl::Bytestring(static_cast(ptr), size - 1); + } else if constexpr (std::is_same, bool>()) { + if (type != AVRO_BOOLEAN) { + return rfl::Error("Could not cast to boolean."); + } + int result = 0; + avro_value_get_boolean(_var.val_, &result); + return (result != 0); + + } else if constexpr (std::is_floating_point>() || + std::is_integral>()) { + if (type == AVRO_DOUBLE) { + double result = 0.0; + const auto err = avro_value_get_double(_var.val_, &result); + if (err) { + return Error("Could not cast to double."); + } + return static_cast(result); + } else if (type == AVRO_INT32) { + int32_t result = 0; + const auto err = avro_value_get_int(_var.val_, &result); + if (err) { + return Error("Could not cast to int32."); + } + return static_cast(result); + } else if (type == AVRO_INT64) { + int64_t result = 0; + const auto err = avro_value_get_long(_var.val_, &result); + if (err) { + return Error("Could not cast to int64."); + } + return static_cast(result); + } else if (type == AVRO_FLOAT) { + float result = 0.0; + const auto err = avro_value_get_float(_var.val_, &result); + if (err) { + return Error("Could not cast to float."); + } + return static_cast(result); + } + return rfl::Error( + "Could not cast to numeric value. The type must be integral, float " + "or double."); + + } else if constexpr (internal::is_literal_v) { + int value = 0; + const auto err = avro_value_get_enum(_var.val_, &value); + if (err) { + return Error("Could not cast to enum."); + } + return std::remove_cvref_t::from_value( + static_cast::ValueType>(value)); + + } else { + static_assert(rfl::always_false_v, "Unsupported type."); + } + } + + rfl::Result to_array(const InputVarType& _var) const noexcept; + + rfl::Result to_object( + const InputVarType& _var) const noexcept; + + rfl::Result to_map(const InputVarType& _var) const noexcept; + + rfl::Result to_union(const InputVarType& _var) const noexcept; + + template + std::optional read_array(const ArrayReader& _array_reader, + const InputArrayType& _arr) const noexcept { + size_t size = 0; + avro_value_get_size(_arr.val_, &size); + for (size_t ix = 0; ix < size; ++ix) { + avro_value_t element; + avro_value_get_by_index(_arr.val_, ix, &element, nullptr); + const auto err = _array_reader.read(InputVarType{&element}); + if (err) { + return err; + } + } + return std::nullopt; + } + + template + std::optional read_map(const MapReader& _map_reader, + const InputMapType& _map) const noexcept { + size_t size = 0; + avro_value_get_size(_map.val_, &size); + for (size_t ix = 0; ix < size; ++ix) { + avro_value_t element; + const char* key = nullptr; + avro_value_get_by_index(_map.val_, ix, &element, &key); + _map_reader.read(std::string_view(key), InputVarType{&element}); + } + return std::nullopt; + } + + template + std::optional read_object(const ObjectReader& _object_reader, + const InputObjectType& _obj) const noexcept { + size_t size = 0; + avro_value_get_size(_obj.val_, &size); + for (size_t ix = 0; ix < size; ++ix) { + avro_value_t element; + avro_value_get_by_index(_obj.val_, ix, &element, nullptr); + _object_reader.read(static_cast(ix), InputVarType{&element}); + } + return std::nullopt; + } + + template + rfl::Result read_union( + const InputUnionType& _union) const noexcept { + int disc = 0; + auto err = avro_value_get_discriminant(_union.val_, &disc); + if (err) { + return Error("Could not get the discriminant."); + } + avro_value_t value; + err = avro_value_get_current_branch(_union.val_, &value); + if (err) { + return Error("Could not cast the union type."); + } + return UnionReaderType::read(*this, static_cast(disc), + InputVarType{&value}); + } + + template + rfl::Result use_custom_constructor( + const InputVarType& _var) const noexcept { + try { + return T::from_avro_obj(_var); + } catch (std::exception& e) { + return rfl::Error(e.what()); + } + } +}; + +} // namespace rfl::avro + +#endif diff --git a/include/rfl/avro/Schema.hpp b/include/rfl/avro/Schema.hpp new file mode 100644 index 00000000..0b4fb2d6 --- /dev/null +++ b/include/rfl/avro/Schema.hpp @@ -0,0 +1,43 @@ +#ifndef RFL_AVRO_SCHEMA_HPP_ +#define RFL_AVRO_SCHEMA_HPP_ + +#include + +#include "../Ref.hpp" +#include "SchemaImpl.hpp" + +namespace rfl::avro { + +template +class Schema { + public: + using Type = std::remove_cvref_t; + + Schema(const std::string& _json_str) + : impl_(Ref::make(_json_str)) {} + + static Result> from_json(const std::string& _json_str) noexcept { + try { + return Schema(_json_str); + } catch (std::exception& e) { + return Error(e.what()); + } + } + + /// The JSON string used to create this schema. + const std::string& json_str() const { return impl_->json_str(); } + + /// The JSON string used to create this schema. + const std::string& str() const { return impl_->json_str(); } + + /// The interface used to create new values. + avro_value_iface_t* iface() const { return impl_->iface(); }; + + private: + /// We are using the "pimpl"-pattern + Ref impl_; +}; + +} // namespace rfl::avro + +#endif diff --git a/include/rfl/avro/SchemaImpl.hpp b/include/rfl/avro/SchemaImpl.hpp new file mode 100644 index 00000000..2f2fa50f --- /dev/null +++ b/include/rfl/avro/SchemaImpl.hpp @@ -0,0 +1,46 @@ +#ifndef RFL_AVRO_SCHEMAIMPL_HPP_ +#define RFL_AVRO_SCHEMAIMPL_HPP_ + +#include + +#include + +#include "../Box.hpp" +#include "../Result.hpp" + +namespace rfl::avro { + +class SchemaImpl { + public: + SchemaImpl(const std::string& _json_str); + + ~SchemaImpl(); + + SchemaImpl(const SchemaImpl& _other) = delete; + + SchemaImpl(SchemaImpl&& _other) noexcept; + + SchemaImpl& operator=(const SchemaImpl& _other) = delete; + + SchemaImpl& operator=(SchemaImpl&& _other) noexcept; + + /// The JSON string used to create this schema. + const std::string& json_str() const { return json_str_; } + + /// The interface used to create new values. + avro_value_iface_t* iface() const { return iface_; }; + + private: + /// The JSON string used to create the schema. + std::string json_str_; + + /// The actual schema + Box schema_; + + /// The interface used to create new, generic classes. + avro_value_iface_t* iface_; +}; + +} // namespace rfl::avro + +#endif diff --git a/include/rfl/avro/Writer.hpp b/include/rfl/avro/Writer.hpp new file mode 100644 index 00000000..a55637b4 --- /dev/null +++ b/include/rfl/avro/Writer.hpp @@ -0,0 +1,216 @@ +#ifndef RFL_AVRO_WRITER_HPP_ +#define RFL_AVRO_WRITER_HPP_ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../Box.hpp" +#include "../Bytestring.hpp" +#include "../Ref.hpp" +#include "../Result.hpp" +#include "../always_false.hpp" +#include "../internal/is_literal.hpp" + +namespace rfl::avro { + +class Writer { + public: + struct AVROOutputArray { + avro_value_t val_; + }; + + struct AVROOutputMap { + avro_value_t val_; + }; + + struct AVROOutputObject { + avro_value_t val_; + }; + + struct AVROOutputUnion { + avro_value_t val_; + }; + + struct AVROOutputVar { + avro_value_t val_; + }; + + using OutputArrayType = AVROOutputArray; + using OutputMapType = AVROOutputMap; + using OutputObjectType = AVROOutputObject; + using OutputUnionType = AVROOutputUnion; + using OutputVarType = AVROOutputVar; + + Writer(avro_value_t* _root); + + ~Writer(); + + OutputArrayType array_as_root(const size_t _size) const noexcept; + + OutputMapType map_as_root(const size_t _size) const noexcept; + + OutputObjectType object_as_root(const size_t _size) const noexcept; + + OutputVarType null_as_root() const noexcept; + + OutputUnionType union_as_root() const noexcept; + + template + OutputVarType value_as_root(const T& _var) const noexcept { + set_value(_var, root_); + return OutputVarType{*root_}; + } + + OutputArrayType add_array_to_array(const size_t _size, + OutputArrayType* _parent) const noexcept; + + OutputArrayType add_array_to_map(const std::string_view& _name, + const size_t _size, + OutputMapType* _parent) const noexcept; + + OutputArrayType add_array_to_object(const std::string_view& _name, + const size_t _size, + OutputObjectType* _parent) const noexcept; + + OutputArrayType add_array_to_union(const size_t _index, const size_t _size, + OutputUnionType* _parent) const noexcept; + + OutputMapType add_map_to_array(const size_t _size, + OutputArrayType* _parent) const noexcept; + + OutputMapType add_map_to_map(const std::string_view& _name, + const size_t _size, + OutputMapType* _parent) const noexcept; + + OutputMapType add_map_to_object(const std::string_view& _name, + const size_t _size, + OutputObjectType* _parent) const noexcept; + + OutputMapType add_map_to_union(const size_t _index, const size_t _size, + OutputUnionType* _parent) const noexcept; + + OutputObjectType add_object_to_array(const size_t _size, + OutputArrayType* _parent) const noexcept; + + OutputObjectType add_object_to_map(const std::string_view& _name, + const size_t _size, + OutputMapType* _parent) const noexcept; + + OutputObjectType add_object_to_object( + const std::string_view& _name, const size_t _size, + OutputObjectType* _parent) const noexcept; + + OutputObjectType add_object_to_union(const size_t _index, const size_t _size, + OutputUnionType* _parent) const noexcept; + + OutputUnionType add_union_to_array(OutputArrayType* _parent) const noexcept; + + OutputUnionType add_union_to_map(const std::string_view& _name, + OutputMapType* _parent) const noexcept; + + OutputUnionType add_union_to_object(const std::string_view& _name, + OutputObjectType* _parent) const noexcept; + + OutputUnionType add_union_to_union(const size_t _index, + OutputUnionType* _parent) const noexcept; + + OutputVarType add_null_to_array(OutputArrayType* _parent) const noexcept; + + OutputVarType add_null_to_map(const std::string_view& _name, + OutputMapType* _parent) const noexcept; + + OutputVarType add_null_to_object(const std::string_view& _name, + OutputObjectType* _parent) const noexcept; + + OutputVarType add_null_to_union(const size_t _index, + OutputUnionType* _parent) const noexcept; + + template + OutputVarType add_value_to_array(const T& _var, + OutputArrayType* _parent) const noexcept { + avro_value_t new_value; + avro_value_append(&_parent->val_, &new_value, nullptr); + set_value(_var, &new_value); + return OutputVarType{new_value}; + } + + template + OutputVarType add_value_to_map(const std::string_view& _name, const T& _var, + OutputMapType* _parent) const noexcept { + avro_value_t new_value; + avro_value_add(&_parent->val_, _name.data(), &new_value, nullptr, nullptr); + set_value(_var, &new_value); + return OutputVarType{new_value}; + } + + template + OutputVarType add_value_to_object(const std::string_view& _name, + const T& _var, + OutputObjectType* _parent) const noexcept { + avro_value_t new_value; + avro_value_get_by_name(&_parent->val_, _name.data(), &new_value, nullptr); + set_value(_var, &new_value); + return OutputVarType{new_value}; + } + + template + OutputVarType add_value_to_union(const size_t _index, const T& _var, + OutputUnionType* _parent) const noexcept { + avro_value_t new_value; + avro_value_set_branch(&_parent->val_, static_cast(_index), &new_value); + set_value(_var, &new_value); + return OutputVarType{new_value}; + } + + void end_array(OutputArrayType* _arr) const noexcept {} + + void end_map(OutputMapType* _obj) const noexcept {} + + void end_object(OutputObjectType* _obj) const noexcept {} + + private: + template + void set_value(const T& _var, avro_value_t* _val) const noexcept { + if constexpr (std::is_same, std::string>()) { + avro_value_set_string_len(_val, _var.c_str(), _var.size() + 1); + + } else if constexpr (std::is_same, + rfl::Bytestring>()) { + auto var = _var; + avro_value_set_bytes(_val, var.data(), var.size() + 1); + + } else if constexpr (std::is_same, bool>()) { + avro_value_set_boolean(_val, _var); + + } else if constexpr (std::is_floating_point>()) { + avro_value_set_double(_val, static_cast(_var)); + + } else if constexpr (std::is_integral>()) { + avro_value_set_long(_val, static_cast(_var)); + + } else if constexpr (internal::is_literal_v) { + avro_value_set_enum(_val, static_cast(_var.value())); + + } else { + static_assert(rfl::always_false_v, "Unsupported type."); + } + } + + private: + avro_value_t* root_; +}; + +} // namespace rfl::avro + +#endif diff --git a/include/rfl/avro/load.hpp b/include/rfl/avro/load.hpp new file mode 100644 index 00000000..b62ec2e2 --- /dev/null +++ b/include/rfl/avro/load.hpp @@ -0,0 +1,23 @@ +#ifndef RFL_AVRO_LOAD_HPP_ +#define RFL_AVRO_LOAD_HPP_ + +#include "../Processors.hpp" +#include "../Result.hpp" +#include "../io/load_bytes.hpp" +#include "read.hpp" + +namespace rfl { +namespace avro { + +template +Result load(const std::string& _fname) { + const auto read_bytes = [](const auto& _bytes) { + return read(_bytes); + }; + return rfl::io::load_bytes(_fname).and_then(read_bytes); +} + +} // namespace avro +} // namespace rfl + +#endif diff --git a/include/rfl/avro/read.hpp b/include/rfl/avro/read.hpp new file mode 100644 index 00000000..c3964e75 --- /dev/null +++ b/include/rfl/avro/read.hpp @@ -0,0 +1,78 @@ +#ifndef RFL_AVRO_READ_HPP_ +#define RFL_AVRO_READ_HPP_ + +#include + +#include +#include +#include +#include + +#include "../Processors.hpp" +#include "../internal/wrap_in_rfl_array_t.hpp" +#include "Parser.hpp" +#include "Reader.hpp" +#include "Schema.hpp" +#include "to_schema.hpp" + +namespace rfl::avro { + +using InputObjectType = typename Reader::InputObjectType; +using InputVarType = typename Reader::InputVarType; + +/// Parses an object from a AVRO var. +template +auto read(const InputVarType& _obj) { + const auto r = Reader(); + return Parser>::read(r, _obj); +} + +/// Parses an object from AVRO using reflection. +template +Result> read( + const char* _bytes, const size_t _size, const Schema& _schema) noexcept { + avro_reader_t avro_reader = avro_reader_memory(_bytes, _size); + avro_value_t root; + avro_generic_value_new(_schema.iface(), &root); + auto err = avro_value_read(avro_reader, &root); + if (err) { + avro_value_decref(&root); + avro_reader_free(avro_reader); + return Error(std::string("Could not read root value: ") + avro_strerror()); + } + auto result = read(InputVarType{&root}); + avro_value_decref(&root); + avro_reader_free(avro_reader); + return result; +} + +/// Parses an object from AVRO using reflection. +template +auto read(const char* _bytes, const size_t _size) noexcept { + const auto schema = to_schema, Ps...>(); + return read(_bytes, _size, schema); +} + +/// Parses an object from AVRO using reflection. +template +auto read(const std::vector& _bytes, const Schema& _schema) { + return read(_bytes.data(), _bytes.size(), _schema); +} + +/// Parses an object from AVRO using reflection. +template +auto read(const std::vector& _bytes) { + return read(_bytes.data(), _bytes.size()); +} + +/// Parses an object from a stream. +template +auto read(std::istream& _stream) { + std::istreambuf_iterator begin(_stream), end; + auto bytes = std::vector(begin, end); + return read(bytes.data(), bytes.size()); +} + +} // namespace rfl::avro + +#endif diff --git a/include/rfl/avro/save.hpp b/include/rfl/avro/save.hpp new file mode 100644 index 00000000..6bd37967 --- /dev/null +++ b/include/rfl/avro/save.hpp @@ -0,0 +1,25 @@ +#ifndef RFL_AVRO_SAVE_HPP_ +#define RFL_AVRO_SAVE_HPP_ + +#include +#include +#include + +#include "../Result.hpp" +#include "../io/save_bytes.hpp" +#include "write.hpp" + +namespace rfl::avro { + +template +Result save(const std::string& _fname, const auto& _obj) { + const auto write_func = [](const auto& _obj, + std::ostream& _stream) -> std::ostream& { + return write(_obj, _stream); + }; + return rfl::io::save_bytes(_fname, _obj, write_func); +} + +} // namespace rfl::avro + +#endif diff --git a/include/rfl/avro/schema/Type.hpp b/include/rfl/avro/schema/Type.hpp new file mode 100644 index 00000000..2ec25522 --- /dev/null +++ b/include/rfl/avro/schema/Type.hpp @@ -0,0 +1,96 @@ +#ifndef RFL_AVRO_SCHEMA_TYPE_HPP_ +#define RFL_AVRO_SCHEMA_TYPE_HPP_ + +#include +#include +#include +#include + +#include "../../Literal.hpp" +#include "../../Object.hpp" +#include "../../Rename.hpp" +#include "../../Variant.hpp" + +namespace rfl::avro::schema { + +struct Type { + struct Null { + Literal<"null"> type; + }; + + struct Boolean { + Literal<"boolean"> type; + }; + + struct Int { + Literal<"int"> type; + }; + + struct Long { + Literal<"long"> type; + }; + + struct Float { + Literal<"float"> type; + }; + + struct Double { + Literal<"float"> type; + }; + + struct Bytes { + Literal<"bytes"> type; + }; + + struct String { + Literal<"string"> type; + }; + + struct RecordField { + std::string name; + rfl::Ref type; + }; + + struct Record { + Literal<"record"> type; + std::string name; + std::vector fields; + std::optional doc; + }; + + struct Enum { + Literal<"enum"> type; + std::string name; + std::vector symbols; + }; + + struct Array { + Literal<"array"> type; + rfl::Ref items; + Rename<"default", std::vector> default_; + }; + + struct Map { + Literal<"map"> type; + rfl::Ref values; + Rename<"default", std::map> default_; + }; + + struct Reference { + std::string type; + }; + + using ReflectionType = + rfl::Variant>; + + const auto& reflection() const { return value; } + + Type with_name(const std::string& _name) const; + + ReflectionType value; +}; + +} // namespace rfl::avro::schema + +#endif diff --git a/include/rfl/avro/to_schema.hpp b/include/rfl/avro/to_schema.hpp new file mode 100644 index 00000000..1eb04dfb --- /dev/null +++ b/include/rfl/avro/to_schema.hpp @@ -0,0 +1,35 @@ +#ifndef RFL_AVRO_TOSCHEMA_HPP_ +#define RFL_AVRO_TOSCHEMA_HPP_ + +#include +#include +#include + +#include "../Literal.hpp" +#include "../Processors.hpp" +#include "../Variant.hpp" +#include "../json.hpp" +#include "../parsing/schema/Type.hpp" +#include "../parsing/schema/ValidationType.hpp" +#include "../parsing/schema/make.hpp" +#include "Reader.hpp" +#include "Schema.hpp" +#include "Writer.hpp" +#include "schema/Type.hpp" + +namespace rfl::avro { + +std::string to_json_representation( + const parsing::schema::Definition& internal_schema); + +/// Returns the Avro schema for a class. +template +Schema to_schema() noexcept { + const auto internal_schema = + parsing::schema::make>(); + const auto json_str = to_json_representation(internal_schema); + return std::move(Schema::from_json(json_str).value()); +} +} // namespace rfl::avro + +#endif diff --git a/include/rfl/avro/write.hpp b/include/rfl/avro/write.hpp new file mode 100644 index 00000000..7440238b --- /dev/null +++ b/include/rfl/avro/write.hpp @@ -0,0 +1,63 @@ +#ifndef RFL_AVRO_WRITE_HPP_ +#define RFL_AVRO_WRITE_HPP_ + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "../parsing/Parent.hpp" +#include "Parser.hpp" +#include "Schema.hpp" +#include "Writer.hpp" +#include "to_schema.hpp" + +namespace rfl::avro { + +/// Returns AVRO bytes. +template +std::vector write(const auto& _obj, const auto& _schema) noexcept { + using T = std::remove_cvref_t; + using U = typename std::remove_cvref_t::Type; + using ParentType = parsing::Parent; + static_assert(std::is_same(), + "The schema must be compatible with the type to write."); + avro_value_t root; + avro_generic_value_new(_schema.iface(), &root); + const auto writer = Writer(&root); + Parser>::write(writer, _obj, + typename ParentType::Root{}); + size_t size = 0; + avro_value_sizeof(&root, &size); + std::vector buffer(size); + avro_writer_t avro_writer = avro_writer_memory(buffer.data(), buffer.size()); + avro_value_write(avro_writer, &root); + avro_value_decref(&root); + avro_writer_free(avro_writer); + return buffer; +} + +/// Returns AVRO bytes. +template +std::vector write(const auto& _obj) noexcept { + using T = std::remove_cvref_t; + const auto schema = to_schema(); + return write(_obj, schema); +} + +/// Writes a AVRO into an ostream. +template +std::ostream& write(const auto& _obj, std::ostream& _stream) noexcept { + auto buffer = write(_obj); + _stream.write(buffer.data(), buffer.size()); + return _stream; +} + +} // namespace rfl::avro + +#endif diff --git a/include/rfl/internal/enums/StringConverter.hpp b/include/rfl/internal/enums/StringConverter.hpp index c7b36fe5..f5ee9a16 100644 --- a/include/rfl/internal/enums/StringConverter.hpp +++ b/include/rfl/internal/enums/StringConverter.hpp @@ -14,9 +14,7 @@ #include "get_enum_names.hpp" #include "is_flag_enum.hpp" -namespace rfl { -namespace internal { -namespace enums { +namespace rfl ::internal ::enums { template class StringConverter { @@ -125,8 +123,6 @@ class StringConverter { } }; -} // namespace enums -} // namespace internal -} // namespace rfl +} // namespace rfl::internal::enums #endif diff --git a/include/rfl/json/schema/Type.hpp b/include/rfl/json/schema/Type.hpp index 849ce452..964354d8 100644 --- a/include/rfl/json/schema/Type.hpp +++ b/include/rfl/json/schema/Type.hpp @@ -7,6 +7,7 @@ #include #include "../../Literal.hpp" +#include "../../Object.hpp" #include "../../Rename.hpp" #include "../../Variant.hpp" @@ -88,7 +89,7 @@ struct Type { struct Object { Literal<"object"> type; std::optional description; - std::map properties; + rfl::Object properties; std::vector required; std::shared_ptr additionalProperties; }; diff --git a/include/rfl/parsing/IsReader.hpp b/include/rfl/parsing/IsReader.hpp index f0c35395..11b78a03 100644 --- a/include/rfl/parsing/IsReader.hpp +++ b/include/rfl/parsing/IsReader.hpp @@ -12,6 +12,8 @@ #include "../Result.hpp" #include "../internal/is_basic_type.hpp" #include "../internal/wrap_in_rfl_array_t.hpp" +#include "SupportsTaggedUnions.hpp" +#include "schemaful/IsSchemafulReader.hpp" namespace rfl { namespace parsing { @@ -25,71 +27,64 @@ struct MockArrayReader { template struct MockObjectReader { - void read(const std::string_view&, - typename R::InputVarType&) const {} + void read(const std::string_view&, typename R::InputVarType&) const {} }; template -concept IsReader = requires(R r, std::string name, - std::function fct, - MockArrayReader array_reader, - MockObjectReader object_reader, - typename R::InputArrayType arr, - typename R::InputObjectType obj, - typename R::InputVarType var, size_t idx) { - /// Any Reader needs to define the following: - /// - /// 1) An InputArrayType, which must be an array-like data structure. - /// 2) An InputObjectType, which must contain key-value pairs. - /// 3) An InputVarType, which must be able to represent either - /// InputArrayType, InputObjectType or a basic type (bool, integral, - /// floating point, std::string). - /// 4) A static constexpr bool has_custom_constructor, that determines - /// whether the class in question as a custom constructor, which might - /// be called something like from_json_obj(...). +concept IsReader = + (SupportsTaggedUnions || schemaful::IsSchemafulReader) && + requires(R r, std::string name, + std::function fct, + MockArrayReader array_reader, MockObjectReader object_reader, + typename R::InputArrayType arr, typename R::InputObjectType obj, + typename R::InputVarType var, size_t idx) { + /// Any Reader needs to define the following: + /// + /// 1) An InputArrayType, which must be an array-like data structure. + /// 2) An InputObjectType, which must contain key-value pairs. + /// 3) An InputVarType, which must be able to represent either + /// InputArrayType, InputObjectType or a basic type (bool, integral, + /// floating point, std::string). + /// 4) A static constexpr bool has_custom_constructor, that determines + /// whether the class in question as a custom constructor, which might + /// be called something like from_json_obj(...). - /// Retrieves a particular field from an array. - { - r.get_field_from_array(idx, arr) - } -> std::same_as>; + /// Determines whether a variable is empty (the NULL type). + { r.is_empty(var) } -> std::same_as; - /// Retrieves a particular field from an object. - { - r.get_field_from_object(name, obj) - } -> std::same_as>; + /// Iterates through an array and writes the contained vars into + /// an array reader. + { r.read_array(array_reader, arr) } -> std::same_as>; - /// 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 an + /// object reader. 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>; - /// Iterates through an array and writes the contained vars into - /// an array reader. - { r.read_array(array_reader, arr) } -> std::same_as>; + /// Transforms var to a basic type (bool, integral, + /// floating point, std::string) + { + r.template to_basic_type>(var) + } -> std::same_as>>; - /// Iterates through an object and writes the key-value pairs into an object - /// reader. 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>; + /// Casts var as an InputArrayType. + { + r.to_array(var) + } -> std::same_as>; - /// Transforms var to a basic type (bool, integral, - /// floating point, std::string) - { - r.template to_basic_type>(var) - } -> std::same_as>>; + /// Casts var as an InputObjectType. + { + r.to_object(var) + } -> std::same_as>; - /// Casts var as an InputArrayType. - { r.to_array(var) } -> std::same_as>; - - /// Casts var as an InputObjectType. - { - r.to_object(var) - } -> std::same_as>; - - /// Uses the custom constructor, if it has been determined that T has one - /// (see above). - { - r.template use_custom_constructor>(var) - } -> std::same_as>>; -}; + /// Uses the custom constructor, if it has been determined that T has one + /// (see above). + { + r.template use_custom_constructor>(var) + } -> std::same_as>>; + }; } // namespace parsing } // namespace rfl diff --git a/include/rfl/parsing/MapParser.hpp b/include/rfl/parsing/MapParser.hpp index c8b03fcb..65805266 100644 --- a/include/rfl/parsing/MapParser.hpp +++ b/include/rfl/parsing/MapParser.hpp @@ -13,13 +13,15 @@ #include "Parent.hpp" #include "Parser_base.hpp" #include "schema/Type.hpp" +#include "schemaful/IsSchemafulReader.hpp" +#include "schemaful/IsSchemafulWriter.hpp" #include "to_single_error_message.hpp" namespace rfl { namespace parsing { template -requires AreReaderAndWriter + requires AreReaderAndWriter struct MapParser { public: using InputObjectType = typename R::InputObjectType; @@ -35,11 +37,94 @@ struct MapParser { const auto to_map = [&](auto obj) -> Result { return make_map(_r, obj); }; - return _r.to_object(_var).and_then(to_map); + if constexpr (schemaful::IsSchemafulReader) { + return _r.to_map(_var).and_then(to_map); + } else { + return _r.to_object(_var).and_then(to_map); + } } template static void write(const W& _w, const MapType& _m, const P& _parent) noexcept { + if constexpr (schemaful::IsSchemafulWriter) { + write_map(_w, _m, _parent); + } else { + write_object(_w, _m, _parent); + } + } + + static schema::Type to_schema( + std::map* _definitions) { + return schema::Type{schema::Type::StringMap{Ref::make( + Parser::to_schema(_definitions))}}; + } + + private: + static Result make_map(const R& _r, const auto& _obj_or_map) { + MapType map; + std::vector errors; + const auto map_reader = + MapReader(&_r, &map, &errors); + if constexpr (schemaful::IsSchemafulReader) { + const auto err = _r.read_map(map_reader, _obj_or_map); + if (err) { + return *err; + } + } else { + const auto err = _r.read_object(map_reader, _obj_or_map); + if (err) { + return *err; + } + } + if (errors.size() != 0) { + return to_single_error_message(errors); + } + return map; + } + + template + static void write_map(const W& _w, const MapType& _m, + const P& _parent) noexcept { + auto m = ParentType::add_map(_w, _m.size(), _parent); + + using ParentMapType = + typename ParentType::template Map; + + for (const auto& [k, v] : _m) { + if constexpr (internal::has_reflection_type_v) { + using ReflT = typename KeyType::ReflectionType; + + if constexpr (std::is_integral_v || + std::is_floating_point_v) { + const auto name = std::to_string(k.reflection()); + const auto new_parent = ParentMapType{name, &m}; + Parser, ProcessorsType>::write( + _w, v, new_parent); + } else { + const auto name = k.reflection(); + const auto new_parent = ParentMapType{name, &m}; + Parser, ProcessorsType>::write( + _w, v, new_parent); + } + + } else if constexpr (std::is_integral_v || + std::is_floating_point_v) { + const auto name = std::to_string(k); + const auto new_parent = ParentMapType{name, &m}; + Parser, ProcessorsType>::write( + _w, v, new_parent); + } else { + const auto new_parent = ParentMapType{k, &m}; + Parser, ProcessorsType>::write( + _w, v, new_parent); + } + } + _w.end_map(&m); + } + + template + static void write_object(const W& _w, const MapType& _m, + const P& _parent) noexcept { auto obj = ParentType::add_object(_w, _m.size(), _parent); for (const auto& [k, v] : _m) { if constexpr (internal::has_reflection_type_v) { @@ -72,28 +157,6 @@ struct MapParser { } _w.end_object(&obj); } - - static schema::Type to_schema( - std::map* _definitions) { - return schema::Type{schema::Type::StringMap{Ref::make( - Parser::to_schema(_definitions))}}; - } - - private: - 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; - } - if (errors.size() != 0) { - return to_single_error_message(errors); - } - return map; - } }; } // namespace parsing diff --git a/include/rfl/parsing/Parent.hpp b/include/rfl/parsing/Parent.hpp index 7c0929f4..eb12698d 100644 --- a/include/rfl/parsing/Parent.hpp +++ b/include/rfl/parsing/Parent.hpp @@ -6,10 +6,10 @@ #include #include "../always_false.hpp" +#include "schemaful/IsSchemafulWriter.hpp" #include "supports_attributes.hpp" -namespace rfl { -namespace parsing { +namespace rfl::parsing { template struct Parent { @@ -21,6 +21,13 @@ struct Parent { OutputArrayType* arr_; }; + // For schemaful formats only. + template + struct Map { + std::string_view name_; + T* map_; + }; + struct Object { std::string_view name_; OutputObjectType* obj_; @@ -28,6 +35,13 @@ struct Parent { Object as_attribute() const { return Object{name_, obj_, true}; } }; + // For schemaful formats only. + template + struct Union { + size_t index_; + T* union_; + }; + struct Root {}; template @@ -36,10 +50,49 @@ struct Parent { using Type = std::remove_cvref_t; if constexpr (std::is_same()) { return _w.add_array_to_array(_size, _parent.arr_); + } else if constexpr (std::is_same()) { return _w.add_array_to_object(_parent.name_, _size, _parent.obj_); + } else if constexpr (std::is_same()) { return _w.array_as_root(_size); + + } else if constexpr (schemaful::IsSchemafulWriter) { + if constexpr (std::is_same>()) { + return _w.add_array_to_map(_parent.name_, _size, _parent.map_); + } else if constexpr (std::is_same>()) { + return _w.add_array_to_union(_parent.index_, _size, _parent.union_); + } else { + static_assert(always_false_v, "Unsupported option."); + } + + } else { + static_assert(always_false_v, "Unsupported option."); + } + } + + // For schemaful formats only. + template + static auto add_map(const W& _w, const size_t _size, + const ParentType& _parent) { + using Type = std::remove_cvref_t; + if constexpr (std::is_same()) { + return _w.add_map_to_array(_size, _parent.arr_); + + } else if constexpr (std::is_same>()) { + return _w.add_map_to_map(_parent.name_, _size, _parent.map_); + + } else if constexpr (std::is_same()) { + return _w.add_map_to_object(_parent.name_, _size, _parent.obj_); + + } else if constexpr (std::is_same>()) { + return _w.add_map_to_union(_parent.index_, _size, _parent.union_); + + } else if constexpr (std::is_same()) { + return _w.map_as_root(_size); + } else { static_assert(always_false_v, "Unsupported option."); } @@ -51,10 +104,23 @@ struct Parent { using Type = std::remove_cvref_t; if constexpr (std::is_same()) { return _w.add_object_to_array(_size, _parent.arr_); + } else if constexpr (std::is_same()) { return _w.add_object_to_object(_parent.name_, _size, _parent.obj_); + } else if constexpr (std::is_same()) { return _w.object_as_root(_size); + + } else if constexpr (schemaful::IsSchemafulWriter) { + if constexpr (std::is_same>()) { + return _w.add_object_to_map(_parent.name_, _size, _parent.map_); + } else if constexpr (std::is_same>()) { + return _w.add_object_to_union(_parent.index_, _size, _parent.union_); + } else { + static_assert(always_false_v, "Unsupported option."); + } + } else { static_assert(always_false_v, "Unsupported option."); } @@ -65,6 +131,7 @@ struct Parent { using Type = std::remove_cvref_t; if constexpr (std::is_same()) { return _w.add_null_to_array(_parent.arr_); + } else if constexpr (std::is_same()) { if constexpr (supports_attributes>) { return _w.add_null_to_object(_parent.name_, _parent.obj_, @@ -72,8 +139,45 @@ struct Parent { } else { return _w.add_null_to_object(_parent.name_, _parent.obj_); } + } else if constexpr (std::is_same()) { return _w.null_as_root(); + + } else if constexpr (schemaful::IsSchemafulWriter) { + if constexpr (std::is_same>()) { + return _w.add_null_to_map(_parent.name_, _parent.map_); + } else if constexpr (std::is_same>()) { + return _w.add_null_to_union(_parent.index_, _parent.union_); + } else { + static_assert(always_false_v, "Unsupported option."); + } + + } else { + static_assert(always_false_v, "Unsupported option."); + } + } + + // For schemaful formats only. + template + static auto add_union(const W& _w, const ParentType& _parent) { + using Type = std::remove_cvref_t; + if constexpr (std::is_same()) { + return _w.add_union_to_array(_parent.arr_); + + } else if constexpr (std::is_same>()) { + return _w.add_union_to_map(_parent.name_, _parent.map_); + + } else if constexpr (std::is_same()) { + return _w.add_union_to_object(_parent.name_, _parent.obj_); + + } else if constexpr (std::is_same>()) { + return _w.add_union_to_union(_parent.index_, _parent.union_); + + } else if constexpr (std::is_same()) { + return _w.union_as_root(); + } else { static_assert(always_false_v, "Unsupported option."); } @@ -85,6 +189,7 @@ struct Parent { using Type = std::remove_cvref_t; if constexpr (std::is_same()) { return _w.add_value_to_array(_var, _parent.arr_); + } else if constexpr (std::is_same()) { if constexpr (supports_attributes>) { return _w.add_value_to_object(_parent.name_, _var, _parent.obj_, @@ -92,15 +197,26 @@ struct Parent { } else { return _w.add_value_to_object(_parent.name_, _var, _parent.obj_); } + } else if constexpr (std::is_same()) { return _w.value_as_root(_var); + + } else if constexpr (schemaful::IsSchemafulWriter) { + if constexpr (std::is_same>()) { + return _w.add_value_to_map(_parent.name_, _var, _parent.map_); + } else if constexpr (std::is_same>()) { + return _w.add_value_to_union(_parent.index_, _var, _parent.union_); + } else { + static_assert(always_false_v, "Unsupported option."); + } + } else { static_assert(always_false_v, "Unsupported option."); } } }; -} // namespace parsing -} // namespace rfl +} // namespace rfl::parsing #endif diff --git a/include/rfl/parsing/Parser_default.hpp b/include/rfl/parsing/Parser_default.hpp index 88dd8422..38f4945c 100644 --- a/include/rfl/parsing/Parser_default.hpp +++ b/include/rfl/parsing/Parser_default.hpp @@ -5,6 +5,7 @@ #include #include +#include "../Bytestring.hpp" #include "../Result.hpp" #include "../always_false.hpp" #include "../from_named_tuple.hpp" @@ -28,9 +29,10 @@ #include "call_destructors_where_necessary.hpp" #include "is_tagged_union_wrapper.hpp" #include "schema/Type.hpp" +#include "schemaful/IsSchemafulReader.hpp" +#include "schemaful/IsSchemafulWriter.hpp" -namespace rfl { -namespace parsing { +namespace rfl ::parsing { /// Default case - anything that cannot be explicitly matched. template @@ -54,8 +56,14 @@ struct Parser { return Parser::ReflType, ProcessorsType>::read(_r, _var) .and_then(wrap_in_t); + + } else if constexpr (schemaful::IsSchemafulReader && + internal::is_literal_v) { + return _r.template to_basic_type(_var); + } else if constexpr (R::template has_custom_constructor) { return _r.template use_custom_constructor(_var); + } else { if constexpr (internal::has_reflection_type_v) { using ReflectionType = std::remove_cvref_t; @@ -68,14 +76,17 @@ struct Parser { }; return Parser::read(_r, _var) .and_then(wrap_in_t); + } else if constexpr (std::is_class_v && std::is_aggregate_v) { if constexpr (ProcessorsType::default_if_missing_) { return read_struct_with_default(_r, _var); } else { return read_struct(_r, _var); } + } else if constexpr (std::is_enum_v) { - if constexpr (ProcessorsType::underlying_enums_) { + if constexpr (ProcessorsType::underlying_enums_ || + schemaful::IsSchemafulReader) { return static_cast( *_r.template to_basic_type>(_var)); } else { @@ -83,6 +94,7 @@ struct Parser { return _r.template to_basic_type(_var).and_then( StringConverter::string_to_enum); } + } else { return _r.template to_basic_type>(_var); } @@ -94,6 +106,11 @@ struct Parser { if constexpr (internal::has_write_reflector) { Parser::ReflType, ProcessorsType>::write( _w, Reflector::from(_var), _parent); + + } else if constexpr (schemaful::IsSchemafulWriter && + internal::is_literal_v) { + ParentType::add_value(_w, _var, _parent); + } else if constexpr (internal::has_reflection_type_v) { using ReflectionType = std::remove_cvref_t; if constexpr (internal::has_reflection_method_v) { @@ -103,14 +120,17 @@ struct Parser { const auto& [r] = _var; Parser::write(_w, r, _parent); } + } else if constexpr (std::is_class_v && std::is_aggregate_v) { const auto ptr_named_tuple = ProcessorsType::template process( internal::to_ptr_named_tuple(_var)); using PtrNamedTupleType = std::remove_cvref_t; Parser::write( _w, ptr_named_tuple, _parent); + } else if constexpr (std::is_enum_v) { - if constexpr (ProcessorsType::underlying_enums_) { + if constexpr (ProcessorsType::underlying_enums_ || + schemaful::IsSchemafulWriter) { const auto val = static_cast>(_var); ParentType::add_value(_w, val, _parent); } else { @@ -118,6 +138,7 @@ struct Parser { const auto str = StringConverter::enum_to_string(_var); ParentType::add_value(_w, str, _parent); } + } else { ParentType::add_value(_w, _var, _parent); } @@ -131,6 +152,9 @@ struct Parser { if constexpr (std::is_same()) { return Type{Type::Boolean{}}; + } else if constexpr (std::is_same()) { + return Type{Type::Bytestring{}}; + } else if constexpr (std::is_same()) { return Type{Type::Int32{}}; @@ -195,7 +219,8 @@ struct Parser { std::map* _definitions) { using Type = schema::Type; using S = internal::enums::StringConverter; - if constexpr (ProcessorsType::underlying_enums_) { + if constexpr (ProcessorsType::underlying_enums_ || + schemaful::IsSchemafulReader) { return Type{Type::Integer{}}; } else if constexpr (S::is_flag_enum_) { return Type{Type::String{}}; @@ -296,7 +321,6 @@ struct Parser { } }; -} // namespace parsing -} // namespace rfl +} // namespace rfl::parsing #endif diff --git a/include/rfl/parsing/Parser_optional.hpp b/include/rfl/parsing/Parser_optional.hpp index 50e7a40d..029a897b 100644 --- a/include/rfl/parsing/Parser_optional.hpp +++ b/include/rfl/parsing/Parser_optional.hpp @@ -11,12 +11,15 @@ #include "Parent.hpp" #include "Parser_base.hpp" #include "schema/Type.hpp" +#include "schemaful/IsSchemafulReader.hpp" +#include "schemaful/IsSchemafulWriter.hpp" +#include "schemaful/OptionalReader.hpp" namespace rfl { namespace parsing { template -requires AreReaderAndWriter> + requires AreReaderAndWriter> struct Parser, ProcessorsType> { using InputVarType = typename R::InputVarType; @@ -24,23 +27,45 @@ struct Parser, ProcessorsType> { static Result> read(const R& _r, const InputVarType& _var) noexcept { - if (_r.is_empty(_var)) { - return std::optional(); + if constexpr (schemaful::IsSchemafulReader) { + using O = schemaful::OptionalReader, + ProcessorsType>; + const auto to_optional = [&](const auto& _u) -> Result> { + return _r.template read_union, O>(_u); + }; + return _r.to_union(_var).and_then(to_optional); + } else { + if (_r.is_empty(_var)) { + return std::optional(); + } + const auto to_opt = [](auto&& _t) { return std::make_optional(_t); }; + return Parser, ProcessorsType>::read(_r, + _var) + .transform(to_opt); } - const auto to_opt = [](auto&& _t) { return std::make_optional(_t); }; - return Parser, ProcessorsType>::read(_r, _var) - .transform(to_opt); } template static void write(const W& _w, const std::optional& _o, const P& _parent) noexcept { - if (!_o) { - ParentType::add_null(_w, _parent); - return; + if constexpr (schemaful::IsSchemafulWriter) { + auto u = ParentType::add_union(_w, _parent); + using UnionType = typename ParentType::template Union; + auto p = + UnionType{.index_ = static_cast(_o ? 0 : 1), .union_ = &u}; + if (_o) { + Parser, ProcessorsType>::write(_w, *_o, p); + } else { + ParentType::add_null(_w, p); + } + } else { + if (_o) { + Parser, ProcessorsType>::write(_w, *_o, + _parent); + } else { + ParentType::add_null(_w, _parent); + } } - Parser, ProcessorsType>::write(_w, *_o, - _parent); } static schema::Type to_schema( diff --git a/include/rfl/parsing/Parser_rfl_variant.hpp b/include/rfl/parsing/Parser_rfl_variant.hpp index a80a7391..c15acc86 100644 --- a/include/rfl/parsing/Parser_rfl_variant.hpp +++ b/include/rfl/parsing/Parser_rfl_variant.hpp @@ -13,20 +13,45 @@ #include "Parser_base.hpp" #include "VariantAlternativeWrapper.hpp" #include "schema/Type.hpp" +#include "schemaful/IsSchemafulReader.hpp" +#include "schemaful/IsSchemafulWriter.hpp" +#include "schemaful/VariantReader.hpp" namespace rfl::parsing { template -requires AreReaderAndWriter> + requires AreReaderAndWriter> class Parser, ProcessorsType> { + using ParentType = Parent; + public: using InputVarType = typename R::InputVarType; static Result> read( const R& _r, const InputVarType& _var) noexcept { if constexpr (internal::all_fields>()) { - return FieldVariantParser::read(_r, _var); + if constexpr (schemaful::IsSchemafulReader) { + using WrappedType = rfl::Variant...>; + return Parser::read(_r, _var) + .transform( + [](auto&& _variant) -> rfl::Variant { + return std::move(_variant).visit([](auto&& _named_tuple) { + return rfl::Variant(std::move( + std::move(_named_tuple).fields().template get<0>())); + }); + }); + + } else { + return FieldVariantParser::read(_r, _var); + } + + } else if constexpr (schemaful::IsSchemafulReader) { + using V = schemaful::VariantReader, + ProcessorsType, AlternativeTypes...>; + return _r.to_union(_var).and_then([&](const auto& _u) { + return _r.template read_union, V>(_u); + }); } else if constexpr (ProcessorsType::add_tags_to_variants_) { using FieldVariantType = @@ -64,8 +89,34 @@ class Parser, ProcessorsType> { const rfl::Variant& _variant, const P& _parent) noexcept { if constexpr (internal::all_fields>()) { - FieldVariantParser::write( - _w, _variant, _parent); + if constexpr (schemaful::IsSchemafulWriter) { + using WrappedType = rfl::Variant< + NamedTuple>...>; + const auto to_wrapped = [](const auto& _variant) -> WrappedType { + return _variant.visit([](const auto& _field) -> WrappedType { + return make_named_tuple(internal::to_ptr_field(_field)); + }); + }; + Parser::write( + _w, to_wrapped(_variant), _parent); + + } else { + FieldVariantParser::write( + _w, _variant, _parent); + } + + } else if constexpr (schemaful::IsSchemafulWriter) { + return rfl::visit( + [&](const auto& _v) { + using Type = std::remove_cvref_t; + auto u = ParentType::add_union(_w, _parent); + using UnionType = typename ParentType::template Union; + auto p = UnionType{.index_ = static_cast(_variant.index()), + .union_ = &u}; + Parser::write(_w, _v, p); + }, + _variant); } else if constexpr (ProcessorsType::add_tags_to_variants_) { using FieldVariantType = diff --git a/include/rfl/parsing/Parser_shared_ptr.hpp b/include/rfl/parsing/Parser_shared_ptr.hpp index 3fe93fe4..e7dcba02 100644 --- a/include/rfl/parsing/Parser_shared_ptr.hpp +++ b/include/rfl/parsing/Parser_shared_ptr.hpp @@ -11,11 +11,14 @@ #include "Parent.hpp" #include "Parser_base.hpp" #include "schema/Type.hpp" +#include "schemaful/IsSchemafulReader.hpp" +#include "schemaful/IsSchemafulWriter.hpp" +#include "schemaful/SharedPtrReader.hpp" namespace rfl::parsing { template -requires AreReaderAndWriter> + requires AreReaderAndWriter> struct Parser, ProcessorsType> { using InputVarType = typename R::InputVarType; @@ -23,25 +26,44 @@ struct Parser, ProcessorsType> { static Result> read(const R& _r, const InputVarType& _var) noexcept { - if (_r.is_empty(_var)) { - return std::shared_ptr(); + if constexpr (schemaful::IsSchemafulReader) { + using S = schemaful::SharedPtrReader, + ProcessorsType>; + const auto to_shared = [&](const auto& _u) -> Result> { + return _r.template read_union, S>(_u); + }; + return _r.to_union(_var).and_then(to_shared); + } else { + if (_r.is_empty(_var)) { + return std::shared_ptr(); + } + return Parser, ProcessorsType>::read(_r, + _var) + .transform([](T&& _t) { return std::make_shared(std::move(_t)); }); } - const auto to_ptr = [](auto&& _t) { - return std::make_shared(std::move(_t)); - }; - return Parser, ProcessorsType>::read(_r, _var) - .transform(to_ptr); } template static void write(const W& _w, const std::shared_ptr& _s, const P& _parent) noexcept { - if (!_s) { - ParentType::add_null(_w, _parent); - return; + if constexpr (schemaful::IsSchemafulWriter) { + auto u = ParentType::add_union(_w, _parent); + using UnionType = typename ParentType::template Union; + auto p = + UnionType{.index_ = static_cast(_s ? 0 : 1), .union_ = &u}; + if (_s) { + Parser, ProcessorsType>::write(_w, *_s, p); + } else { + ParentType::add_null(_w, p); + } + } else { + if (_s) { + Parser, ProcessorsType>::write(_w, *_s, + _parent); + } else { + ParentType::add_null(_w, _parent); + } } - Parser, ProcessorsType>::write(_w, *_s, - _parent); } static schema::Type to_schema( diff --git a/include/rfl/parsing/Parser_tagged_union.hpp b/include/rfl/parsing/Parser_tagged_union.hpp index e4314cd4..49c10695 100644 --- a/include/rfl/parsing/Parser_tagged_union.hpp +++ b/include/rfl/parsing/Parser_tagged_union.hpp @@ -14,15 +14,16 @@ #include "TaggedUnionWrapper.hpp" #include "is_tagged_union_wrapper.hpp" #include "schema/Type.hpp" +#include "schemaful/IsSchemafulReader.hpp" +#include "schemaful/IsSchemafulWriter.hpp" #include "tagged_union_wrapper_no_ptr.hpp" -namespace rfl { -namespace parsing { +namespace rfl::parsing { template -requires AreReaderAndWriter> + requires AreReaderAndWriter> struct Parser, ProcessorsType> { using ResultType = Result>; @@ -38,22 +39,32 @@ struct Parser, typename R::InputObjectType>; static ResultType read(const R& _r, const InputVarType& _var) noexcept { - const auto get_disc = - [&_r](InputObjectOrArrayType _obj_or_arr) -> Result { - return get_discriminator(_r, _obj_or_arr); - }; + if constexpr (schemaful::IsSchemafulReader) { + return Parser, ProcessorsType>::read( + _r, _var) + .transform([](auto&& _variant) { + return TaggedUnion<_discriminator, AlternativeTypes...>( + std::move(_variant)); + }); - const auto to_result = - [&_r, _var](const std::string& _disc_value) -> ResultType { - return find_matching_alternative( - _r, _disc_value, _var, - std::make_integer_sequence()); - }; - - if constexpr (no_field_names_) { - return _r.to_array(_var).and_then(get_disc).and_then(to_result); } else { - return _r.to_object(_var).and_then(get_disc).and_then(to_result); + const auto get_disc = + [&_r](InputObjectOrArrayType _obj_or_arr) -> Result { + return get_discriminator(_r, _obj_or_arr); + }; + + const auto to_result = + [&_r, _var](const std::string& _disc_value) -> ResultType { + return find_matching_alternative( + _r, _disc_value, _var, + std::make_integer_sequence()); + }; + + if constexpr (no_field_names_) { + return _r.to_array(_var).and_then(get_disc).and_then(to_result); + } else { + return _r.to_object(_var).and_then(get_disc).and_then(to_result); + } } } @@ -62,17 +73,26 @@ struct Parser, const W& _w, const TaggedUnion<_discriminator, AlternativeTypes...>& _tagged_union, const P& _parent) noexcept { - const auto handle = [&](const auto& _val) { - write_wrapped(_w, _val, _parent); - }; - rfl::visit(handle, _tagged_union.variant_); + if constexpr (schemaful::IsSchemafulWriter) { + Parser, ProcessorsType>::write( + _w, _tagged_union.variant(), _parent); + } else { + rfl::visit([&](const auto& _val) { write_wrapped(_w, _val, _parent); }, + _tagged_union.variant()); + } } static schema::Type to_schema( std::map* _definitions) noexcept { - using VariantType = std::variant), AlternativeTypes>...>; - return Parser::to_schema(_definitions); + if constexpr (schemaful::IsSchemafulReader && + schemaful::IsSchemafulWriter) { + return Parser, + ProcessorsType>::to_schema(_definitions); + } else { + using VariantType = std::variant), AlternativeTypes>...>; + return Parser::to_schema(_definitions); + } } private: @@ -215,7 +235,6 @@ struct Parser, } }; -} // namespace parsing -} // namespace rfl +} // namespace rfl::parsing #endif diff --git a/include/rfl/parsing/Parser_unique_ptr.hpp b/include/rfl/parsing/Parser_unique_ptr.hpp index 0e07cf39..b9d60587 100644 --- a/include/rfl/parsing/Parser_unique_ptr.hpp +++ b/include/rfl/parsing/Parser_unique_ptr.hpp @@ -11,12 +11,15 @@ #include "Parent.hpp" #include "Parser_base.hpp" #include "schema/Type.hpp" +#include "schemaful/IsSchemafulReader.hpp" +#include "schemaful/IsSchemafulWriter.hpp" +#include "schemaful/UniquePtrReader.hpp" namespace rfl { namespace parsing { template -requires AreReaderAndWriter> + requires AreReaderAndWriter> struct Parser, ProcessorsType> { using InputVarType = typename R::InputVarType; @@ -24,25 +27,44 @@ struct Parser, ProcessorsType> { static Result> read(const R& _r, const InputVarType& _var) noexcept { - if (_r.is_empty(_var)) { - return std::unique_ptr(); + if constexpr (schemaful::IsSchemafulReader) { + using S = schemaful::UniquePtrReader, + ProcessorsType>; + const auto to_unique = [&](const auto& _u) -> Result> { + return _r.template read_union, S>(_u); + }; + return _r.to_union(_var).and_then(to_unique); + } else { + if (_r.is_empty(_var)) { + return std::unique_ptr(); + } + return Parser, ProcessorsType>::read(_r, + _var) + .transform([](T&& _t) { return std::make_unique(std::move(_t)); }); } - const auto to_ptr = [](auto&& _t) { - return std::make_unique(std::move(_t)); - }; - return Parser, ProcessorsType>::read(_r, _var) - .transform(to_ptr); } template static void write(const W& _w, const std::unique_ptr& _s, const P& _parent) noexcept { - if (!_s) { - ParentType::add_null(_w, _parent); - return; + if constexpr (schemaful::IsSchemafulWriter) { + auto u = ParentType::add_union(_w, _parent); + using UnionType = typename ParentType::template Union; + auto p = + UnionType{.index_ = static_cast(_s ? 0 : 1), .union_ = &u}; + if (_s) { + Parser, ProcessorsType>::write(_w, *_s, p); + } else { + ParentType::add_null(_w, p); + } + } else { + if (_s) { + Parser, ProcessorsType>::write(_w, *_s, + _parent); + } else { + ParentType::add_null(_w, _parent); + } } - Parser, ProcessorsType>::write(_w, *_s, - _parent); } static schema::Type to_schema( diff --git a/include/rfl/parsing/Parser_variant.hpp b/include/rfl/parsing/Parser_variant.hpp index e60dc9d8..5663220c 100644 --- a/include/rfl/parsing/Parser_variant.hpp +++ b/include/rfl/parsing/Parser_variant.hpp @@ -6,41 +6,69 @@ #include #include +#include "../NamedTuple.hpp" #include "../Ref.hpp" #include "../Result.hpp" #include "../Variant.hpp" #include "../always_false.hpp" #include "../internal/to_ptr_field.hpp" #include "FieldVariantParser.hpp" +#include "Parent.hpp" #include "Parser_base.hpp" #include "VariantAlternativeWrapper.hpp" #include "schema/Type.hpp" +#include "schemaful/IsSchemafulReader.hpp" +#include "schemaful/IsSchemafulWriter.hpp" +#include "schemaful/VariantReader.hpp" #include "to_single_error_message.hpp" namespace rfl::parsing { template -requires AreReaderAndWriter> + requires AreReaderAndWriter> class Parser, ProcessorsType> { template using ptr_field_t = decltype(internal::to_ptr_field(std::declval())); + using ParentType = Parent; + public: using InputVarType = typename R::InputVarType; static Result> read( const R& _r, const InputVarType& _var) noexcept { if constexpr (internal::all_fields>()) { - const auto wrap = [](auto&& _v) { - return std::variant(std::move(_v)); - }; - const auto to_std_variant = [&](auto&& _v) { - return rfl::visit(wrap, std::move(_v)); - }; - return FieldVariantParser::read(_r, _var) - .transform(to_std_variant); + if constexpr (schemaful::IsSchemafulReader) { + using WrappedType = rfl::Variant...>; + return Parser::read(_r, _var) + .transform( + [](auto&& _variant) -> std::variant { + return std::move(_variant).visit([](auto&& _named_tuple) { + return std::variant(std::move( + std::move(_named_tuple).fields().template get<0>())); + }); + }); + + } else { + const auto wrap = [](auto&& _v) { + return std::variant(std::move(_v)); + }; + const auto to_std_variant = [&](auto&& _v) { + return rfl::visit(wrap, std::move(_v)); + }; + return FieldVariantParser::read(_r, _var) + .transform(to_std_variant); + } + + } else if constexpr (schemaful::IsSchemafulReader) { + using V = + schemaful::VariantReader, + ProcessorsType, AlternativeTypes...>; + return _r.to_union(_var).and_then([&](const auto& _u) { + return _r.template read_union, V>(_u); + }); } else if constexpr (ProcessorsType::add_tags_to_variants_) { using FieldVariantType = @@ -78,17 +106,47 @@ class Parser, ProcessorsType> { const std::variant& _variant, const P& _parent) noexcept { if constexpr (internal::all_fields>()) { - const auto wrap = [](const auto& _v) { - return rfl::Variant...>( - internal::to_ptr_field(_v)); - }; - const auto to_rfl_variant = [&](const auto& _v) { - return std::visit(wrap, _v); - }; - FieldVariantParser< - R, W, ProcessorsType, - ptr_field_t...>::write(_w, to_rfl_variant(_variant), - _parent); + if constexpr (schemaful::IsSchemafulWriter) { + using WrappedType = rfl::Variant< + NamedTuple>...>; + const auto to_wrapped = [](const auto& _variant) -> WrappedType { + return std::visit( + [](const auto& _field) -> WrappedType { + return make_named_tuple(internal::to_ptr_field(_field)); + }, + _variant); + }; + Parser::write( + _w, to_wrapped(_variant), _parent); + + } else { + const auto wrap = [](const auto& _v) { + return rfl::Variant...>( + internal::to_ptr_field(_v)); + }; + const auto to_rfl_variant = [&](const auto& _v) { + return std::visit(wrap, _v); + }; + FieldVariantParser< + R, W, ProcessorsType, + ptr_field_t...>::write(_w, + to_rfl_variant(_variant), + _parent); + } + + } else if constexpr (schemaful::IsSchemafulWriter) { + return std::visit( + [&](const auto& _v) { + using Type = std::remove_cvref_t; + auto u = ParentType::add_union(_w, _parent); + using UnionType = typename ParentType::template Union; + auto p = UnionType{.index_ = static_cast(_variant.index()), + .union_ = &u}; + Parser::write(_w, _v, p); + }, + _variant); + } else if constexpr (ProcessorsType::add_tags_to_variants_) { using FieldVariantType = rfl::Variant...>; diff --git a/include/rfl/parsing/SupportsTaggedUnions.hpp b/include/rfl/parsing/SupportsTaggedUnions.hpp new file mode 100644 index 00000000..5dc26c7e --- /dev/null +++ b/include/rfl/parsing/SupportsTaggedUnions.hpp @@ -0,0 +1,35 @@ +#ifndef RFL_PARSING_SUPPORTSTAGGEDUNIONS_HPP_ +#define RFL_PARSING_SUPPORTSTAGGEDUNIONS_HPP_ + +#include +#include +#include +#include +#include +#include +#include + +#include "../Result.hpp" +#include "../internal/is_basic_type.hpp" +#include "../internal/wrap_in_rfl_array_t.hpp" + +namespace rfl::parsing { + +template +concept SupportsTaggedUnions = requires( + R r, std::string name, typename R::InputArrayType arr, + typename R::InputObjectType obj, typename R::InputVarType var, size_t idx) { + /// Retrieves a particular field from an array. + { + r.get_field_from_array(idx, arr) + } -> std::same_as>; + + /// Retrieves a particular field from an object. + { + r.get_field_from_object(name, obj) + } -> std::same_as>; +}; + +} // namespace rfl::parsing + +#endif diff --git a/include/rfl/parsing/TupleParser.hpp b/include/rfl/parsing/TupleParser.hpp index 0ce06f4a..5e916b86 100644 --- a/include/rfl/parsing/TupleParser.hpp +++ b/include/rfl/parsing/TupleParser.hpp @@ -1,7 +1,6 @@ #ifndef RFL_PARSING_TUPLEPARSER_HPP_ #define RFL_PARSING_TUPLEPARSER_HPP_ -#include #include #include #include @@ -16,6 +15,10 @@ #include "TupleReader.hpp" #include "call_destructors_on_tuple_where_necessary.hpp" #include "schema/Type.hpp" +#include "schemaful/IsSchemafulReader.hpp" +#include "schemaful/IsSchemafulWriter.hpp" +#include "schemaful/tuple_to_named_tuple.hpp" +#include "schemaful/tuple_to_named_tuple_t.hpp" namespace rfl::parsing { @@ -31,38 +34,59 @@ struct TupleParser { static Result read(const R& _r, const InputVarType& _var) noexcept { - const auto parse = [&](const InputArrayType& _arr) -> Result { - alignas(TupleType) unsigned char buf[sizeof(TupleType)]{}; - auto ptr = internal::ptr_cast(&buf); - const auto tuple_reader = - TupleReader(&_r, ptr); - auto err = _r.read_array(tuple_reader, _arr); - if (err) { - call_destructors_on_tuple_where_necessary(tuple_reader.num_set(), ptr); - return *err; - } - err = tuple_reader.handle_missing_fields(); - if (err) { - call_destructors_on_tuple_where_necessary(tuple_reader.num_set(), ptr); - return *err; - } - auto res = Result(std::move(*ptr)); - call_destructors_on_tuple_where_necessary(tuple_reader.num_set(), ptr); - return res; - }; + if constexpr (schemaful::IsSchemafulReader) { + using NamedTupleType = schemaful::tuple_to_named_tuple_t; + const auto to_tuple = [](auto&& _named_tuple) { + return [&](std::integer_sequence) { + return TupleType(std::move(rfl::get<_is>(_named_tuple))...); + }(std::make_integer_sequence()); + }; + return Parser::read(_r, _var) + .transform(to_tuple); - return _r.to_array(_var).and_then(parse); + } else { + const auto parse = [&](const InputArrayType& _arr) -> Result { + alignas(TupleType) unsigned char buf[sizeof(TupleType)]; + auto ptr = internal::ptr_cast(&buf); + const auto tuple_reader = + TupleReader(&_r, ptr); + auto err = _r.read_array(tuple_reader, _arr); + if (err) { + call_destructors_on_tuple_where_necessary(tuple_reader.num_set(), + ptr); + return *err; + } + err = tuple_reader.handle_missing_fields(); + if (err) { + call_destructors_on_tuple_where_necessary(tuple_reader.num_set(), + ptr); + return *err; + } + auto res = Result(std::move(*ptr)); + call_destructors_on_tuple_where_necessary(tuple_reader.num_set(), ptr); + return res; + }; + + return _r.to_array(_var).and_then(parse); + } } template static void write(const W& _w, const TupleType& _tup, const P& _parent) noexcept { - constexpr auto size = rfl::tuple_size_v; - auto arr = ParentType::add_array(_w, size, _parent); - const auto new_parent = typename ParentType::Array{&arr}; - to_array(_w, _tup, new_parent, std::make_integer_sequence()); - _w.end_array(&arr); + if constexpr (schemaful::IsSchemafulWriter) { + const auto named_tuple = schemaful::tuple_to_named_tuple(_tup); + Parser, + ProcessorsType>::write(_w, named_tuple, _parent); + + } else { + constexpr auto size = rfl::tuple_size_v; + auto arr = ParentType::add_array(_w, size, _parent); + const auto new_parent = typename ParentType::Array{&arr}; + to_array(_w, _tup, new_parent, std::make_integer_sequence()); + _w.end_array(&arr); + } } static schema::Type to_schema( diff --git a/include/rfl/parsing/VectorParser.hpp b/include/rfl/parsing/VectorParser.hpp index 54ae5327..c95bb682 100644 --- a/include/rfl/parsing/VectorParser.hpp +++ b/include/rfl/parsing/VectorParser.hpp @@ -27,7 +27,7 @@ namespace parsing { /// but also includes map-like types, when the key is not of type /// std::string. template -requires AreReaderAndWriter + requires AreReaderAndWriter struct VectorParser { public: using InputArrayType = typename R::InputArrayType; @@ -85,10 +85,14 @@ struct VectorParser { /// Generates a schema for the underlying type. static schema::Type to_schema( std::map* _definitions) { - using Type = schema::Type; - return Type{Type::TypedArray{ - .type_ = Ref::make( - Parser::to_schema(_definitions))}}; + if constexpr (treat_as_map()) { + return MapParser::to_schema(_definitions); + } else { + using Type = schema::Type; + return Type{Type::TypedArray{ + .type_ = Ref::make( + Parser::to_schema(_definitions))}}; + } } private: diff --git a/include/rfl/parsing/ViewReader.hpp b/include/rfl/parsing/ViewReader.hpp index 2221f749..a9d97c82 100644 --- a/include/rfl/parsing/ViewReader.hpp +++ b/include/rfl/parsing/ViewReader.hpp @@ -12,6 +12,7 @@ #include "../Tuple.hpp" #include "../internal/is_array.hpp" #include "Parser_base.hpp" +#include "schemaful/IsSchemafulReader.hpp" namespace rfl::parsing { @@ -35,10 +36,28 @@ class ViewReader { std::make_integer_sequence()); } + /// Assigns the parsed version of _var to the field signified by _index, if + /// such a field exists in the underlying view. + /// Note that schemaful formats can assign by index. + void read(const int _index, const InputVarType& _var) const { + assign_to_matching_field(*r_, _index, _var, view_, errors_, found_, set_, + std::make_integer_sequence()); + } + private: + template + static bool is_matching(const int _current_index) { + return _current_index == i; + } + + template + static bool is_matching(const std::string_view& _current_name) { + return _current_name == FieldType::name(); + } + template static void assign_if_field_matches(const R& _r, - const std::string_view& _current_name, + const auto _current_name_or_index, const auto& _var, auto* _view, auto* _errors, auto* _found, auto* _set, bool* _already_assigned) { @@ -48,7 +67,7 @@ class ViewReader { std::remove_cvref_t>; constexpr auto name = FieldType::name(); if (!(*_already_assigned) && !std::get(*_found) && - _current_name == name) { + is_matching(_current_name_or_index)) { std::get(*_found) = true; *_already_assigned = true; auto res = Parser::read(_r, _var); @@ -96,26 +115,33 @@ class ViewReader { template static void assign_to_matching_field(const R& _r, - const std::string_view& _current_name, + const auto _current_name_or_index, const auto& _var, auto* _view, auto* _errors, auto* _found, auto* _set, std::integer_sequence) { bool already_assigned = false; - (assign_if_field_matches(_r, _current_name, _var, _view, _errors, - _found, _set, &already_assigned), + (assign_if_field_matches(_r, _current_name_or_index, _var, _view, + _errors, _found, _set, &already_assigned), ...); if constexpr (ViewType::pos_extra_fields() != -1) { + static_assert(!schemaful::IsSchemafulReader, + "rfl::ExtraFields are not supported for schemaful formats, " + "because schemaful formats cannot have extra fields."); constexpr int pos = ViewType::pos_extra_fields(); if (!already_assigned) { - assign_to_extra_fields(_r, _current_name, _var, _view, _errors, - _found, _set); + assign_to_extra_fields(_r, _current_name_or_index, _var, _view, + _errors, _found, _set); } } else if constexpr (ProcessorsType::no_extra_fields_) { + static_assert( + !schemaful::IsSchemafulReader, + "Passing rfl::NoExtraFields to a schemaful format does not make " + "sense, because schemaful formats cannot have extra fields."); if (!already_assigned) { std::stringstream stream; - stream << "Value named '" << _current_name + stream << "Value named '" << _current_name_or_index << "' not used. Remove the rfl::NoExtraFields processor or add " "rfl::ExtraFields to avoid this error message."; _errors->emplace_back(Error(stream.str())); diff --git a/include/rfl/parsing/schema/Type.hpp b/include/rfl/parsing/schema/Type.hpp index 5b2d27d3..a5372308 100644 --- a/include/rfl/parsing/schema/Type.hpp +++ b/include/rfl/parsing/schema/Type.hpp @@ -2,11 +2,11 @@ #define RFL_PARSING_SCHEMA_TYPE_HPP_ #include -#include #include #include #include +#include "../../Object.hpp" #include "../../Ref.hpp" #include "../../Variant.hpp" #include "ValidationType.hpp" @@ -16,6 +16,8 @@ namespace rfl::parsing::schema { struct Type { struct Boolean {}; + struct Bytestring {}; + struct Int32 {}; struct Int64 {}; @@ -51,7 +53,7 @@ struct Type { }; struct Object { - std::map types_; + rfl::Object types_; std::shared_ptr additional_properties_; }; @@ -86,10 +88,10 @@ struct Type { }; using VariantType = - rfl::Variant; + rfl::Variant; Type(); diff --git a/include/rfl/parsing/schemaful/IsSchemafulReader.hpp b/include/rfl/parsing/schemaful/IsSchemafulReader.hpp new file mode 100644 index 00000000..3b1eac2a --- /dev/null +++ b/include/rfl/parsing/schemaful/IsSchemafulReader.hpp @@ -0,0 +1,63 @@ +#ifndef RFL_PARSING_SCHEMAFUL_ISSCHEMAFULREADER_HPP_ +#define RFL_PARSING_SCHEMAFUL_ISSCHEMAFULREADER_HPP_ + +#include +#include +#include + +namespace rfl::parsing::schemaful { + +using MockVariantType = std::variant; + +template +struct MockMapReader { + void read(const std::string_view&, typename R::InputVarType&) const {} +}; + +template +struct MockObjectReader { + void read(const int, typename R::InputVarType&) const {} +}; + +template +struct MockUnionReader { + static rfl::Result read(const R&, const size_t, + typename R::InputVarType&) { + return Error("This is a mock type."); + } +}; + +template +concept IsSchemafulReader = + requires(R r, typename R::InputVarType var, typename R::InputObjectType obj, + typename R::InputMapType m, typename R::InputUnionType u, + MockMapReader map_reader, MockObjectReader object_reader) { + /// A schemaful reader needs to differentiate between objects, for which + /// the field names are known at compile time and maps, for which the + /// field names are not known at compile time. + { r.read_map(map_reader, m) } -> std::same_as>; + + /// A schemaful reader can read fields by order and does not have to + /// compare strings - the correct order of the fields is guaranteed by the + /// schema. + { + r.read_object(object_reader, obj) + } -> std::same_as>; + + /// A schemaful reader needs an explicit union type. + { + r.template read_union>(u) + } -> std::same_as>; + + /// It needs to be possible to transform variables to maps. + { r.to_map(var) } -> std::same_as>; + + /// It needs to be possible to transform variables to unions. + { + r.to_union(var) + } -> std::same_as>; + }; + +} // namespace rfl::parsing::schemaful + +#endif diff --git a/include/rfl/parsing/schemaful/IsSchemafulWriter.hpp b/include/rfl/parsing/schemaful/IsSchemafulWriter.hpp new file mode 100644 index 00000000..e19debb3 --- /dev/null +++ b/include/rfl/parsing/schemaful/IsSchemafulWriter.hpp @@ -0,0 +1,130 @@ +#ifndef RFL_PARSING_SCHEMAFUL_ISSCHEMAFULWRITER_HPP_ +#define RFL_PARSING_SCHEMAFUL_ISSCHEMAFULWRITER_HPP_ + +#include +#include +#include +#include + +namespace rfl::parsing::schemaful { + +template +concept IsSchemafulWriter = requires( + W w, typename W::OutputVarType var, typename W::OutputArrayType arr, + typename W::OutputMapType m, typename W::OutputObjectType obj, + typename W::OutputUnionType u, size_t index, size_t size, + std::string_view name, std::string val) { + /// A schemaful writer needs to know two additional types: + /// 1) Maps - unlike objects, their field names are not known at compile time. + /// 2) Unions - schemaful formats need explicit union types. + + /// Sets an empty map as the root element of the document. + /// Some serialization formats require you to pass the expected size in + /// advance. If you are not working with such a format, you can ignore the + /// parameter `size`. Returns the new array for further modification. + { w.map_as_root(size) } -> std::same_as; + + /// Sets an empty union as the root element of the document. + { w.union_as_root() } -> std::same_as; + + /// Adds an empty array to an existing map. Returns the new + /// array for further modification. + { + w.add_array_to_map(name, size, &m) + } -> std::same_as; + + /// Adds an empty array to an existing union. + /// The index refers to the index of the element in the union. + /// Returns the new array for further modification. + { + w.add_array_to_union(index, size, &u) + } -> std::same_as; + + /// Adds an empty map to an existing array. Returns the new + /// map for further modification. + { w.add_map_to_array(size, &arr) } -> std::same_as; + + /// Adds an empty map to an existing map. The key or name of the field + /// is signified by `name`. Returns the new map for further modification. + { + w.add_map_to_map(name, size, &m) + } -> std::same_as; + + /// Adds an empty map to an existing object. The key or name of the field + /// is signified by `name`. Returns the new map for further modification. + { + w.add_map_to_object(name, size, &obj) + } -> std::same_as; + + /// Adds an empty map to an existing union. + /// The index refers to the index of the element in the union. + /// Returns the new map for further modification. + { + w.add_map_to_union(index, size, &u) + } -> std::same_as; + + /// Adds an empty object to an existing map. The key or name of the field + /// is signified by `name`. Returns the new object for further modification. + { + w.add_object_to_map(name, size, &m) + } -> std::same_as; + + /// Adds an empty object to an existing union. + /// The index refers to the index of the element in the union. + /// Returns the new object for further modification. + { + w.add_object_to_union(index, size, &u) + } -> std::same_as; + + /// Adds an empty union to an existing array. Returns the new + /// union for further modification. + { w.add_union_to_array(&arr) } -> std::same_as; + + /// Adds an empty union to an existing map. The key or name of the field + /// is signified by `name`. Returns the new union for further modification. + { w.add_union_to_map(name, &m) } -> std::same_as; + + /// Adds an empty union to an existing object. The key or name of the field + /// is signified by `name`. Returns the new union for further modification. + { + w.add_union_to_object(name, &obj) + } -> std::same_as; + + /// Adds an empty union to an existing union. + /// The index refers to the index of the element in the union. + /// Returns the new union for further modification. + { + w.add_union_to_union(index, &u) + } -> std::same_as; + + /// Adds a null value to a map. Returns an + /// OutputVarType containing the null value. + { w.add_null_to_map(name, &m) } -> std::same_as; + + /// Adds a basic value (bool, numeric, string) to an existing map. The key + /// or name of the field is signified by `name`. Returns an + /// OutputVarType containing the new value. + { + w.add_value_to_map(name, val, &m) + } -> std::same_as; + + /// Adds a null value to a union. Returns an + /// OutputVarType containing the null value. + { w.add_null_to_union(index, &u) } -> std::same_as; + + /// Adds a basic value (bool, numeric, string) to an existing union. The key + /// or name of the field is signified by `name`. Returns an + /// OutputVarType containing the new value. + { + w.add_value_to_union(index, val, &u) + } -> std::same_as; + + /// Signifies to the writer that we do not want to add any further elements to + /// this map. Some serialization formats require this. If you are working + /// with a serialization format that doesn't, just leave the function empty. + { w.end_map(&m) } -> std::same_as; +}; + +} // namespace rfl::parsing::schemaful + +#endif diff --git a/include/rfl/parsing/schemaful/OptionalReader.hpp b/include/rfl/parsing/schemaful/OptionalReader.hpp new file mode 100644 index 00000000..2753f614 --- /dev/null +++ b/include/rfl/parsing/schemaful/OptionalReader.hpp @@ -0,0 +1,25 @@ +#ifndef RFL_PARSING_SCHEMAFUL_OPTIONALREADER_HPP_ +#define RFL_PARSING_SCHEMAFUL_OPTIONALREADER_HPP_ + +#include +#include + +#include "../../Result.hpp" + +namespace rfl::parsing::schemaful { + +template +struct OptionalReader { + static Result> read( + const R& _r, const size_t _index, + const typename R::InputVarType& _var) noexcept { + if (_index == 1) { + return std::optional(); + } + return Parser, ProcessorsType>::read(_r, _var); + } +}; + +} // namespace rfl::parsing::schemaful + +#endif diff --git a/include/rfl/parsing/schemaful/SharedPtrReader.hpp b/include/rfl/parsing/schemaful/SharedPtrReader.hpp new file mode 100644 index 00000000..baad5e53 --- /dev/null +++ b/include/rfl/parsing/schemaful/SharedPtrReader.hpp @@ -0,0 +1,26 @@ +#ifndef RFL_PARSING_SCHEMAFUL_SHAREDPTRREADER_HPP_ +#define RFL_PARSING_SCHEMAFUL_SHAREDPTRREADER_HPP_ + +#include +#include + +#include "../../Result.hpp" + +namespace rfl::parsing::schemaful { + +template +struct SharedPtrReader { + static Result> read( + const R& _r, const size_t _index, + const typename R::InputVarType& _var) noexcept { + if (_index == 1) { + return std::shared_ptr(); + } + return Parser, ProcessorsType>::read(_r, _var) + .transform([](T&& _t) { return std::make_shared(std::move(_t)); }); + } +}; + +} // namespace rfl::parsing::schemaful + +#endif diff --git a/include/rfl/parsing/schemaful/UniquePtrReader.hpp b/include/rfl/parsing/schemaful/UniquePtrReader.hpp new file mode 100644 index 00000000..888cf634 --- /dev/null +++ b/include/rfl/parsing/schemaful/UniquePtrReader.hpp @@ -0,0 +1,26 @@ +#ifndef RFL_PARSING_SCHEMAFUL_UNIQUEPTRREADER_HPP_ +#define RFL_PARSING_SCHEMAFUL_UNIQUEPTRREADER_HPP_ + +#include +#include + +#include "../../Result.hpp" + +namespace rfl::parsing::schemaful { + +template +struct UniquePtrReader { + static Result> read( + const R& _r, const size_t _index, + const typename R::InputVarType& _var) noexcept { + if (_index == 1) { + return std::unique_ptr(); + } + return Parser, ProcessorsType>::read(_r, _var) + .transform([](T&& _t) { return std::make_unique(std::move(_t)); }); + } +}; + +} // namespace rfl::parsing::schemaful + +#endif diff --git a/include/rfl/parsing/schemaful/VariantReader.hpp b/include/rfl/parsing/schemaful/VariantReader.hpp new file mode 100644 index 00000000..eb2f5f9d --- /dev/null +++ b/include/rfl/parsing/schemaful/VariantReader.hpp @@ -0,0 +1,44 @@ +#ifndef RFL_PARSING_SCHEMAFUL_VARIANTREADER_HPP_ +#define RFL_PARSING_SCHEMAFUL_VARIANTREADER_HPP_ + +#include +#include + +#include "../../Result.hpp" +#include "../../internal/nth_element_t.hpp" + +namespace rfl::parsing::schemaful { + +template +class VariantReader { + public: + static Result read( + const R& _r, const size_t _index, + const typename R::InputVarType& _var) noexcept { + return [&](std::integer_sequence) { + Result result = + Error("Could not parse union: Index out of bounds."); + (try_one_type<_is>(_r, _index, _var, &result), ...); + return result; + }(std::make_integer_sequence()); + } + + private: + template + static void try_one_type(const R& _r, const size_t _index, + const typename R::InputVarType& _var, + Result* _result) noexcept { + if (_index == _i) { + using T = internal::nth_element_t<_i, AlternativeTypes...>; + *_result = + Parser, ProcessorsType>::read(_r, _var) + .transform( + [](auto&& _val) -> VariantType { return std::move(_val); }); + } + } +}; + +} // namespace rfl::parsing::schemaful + +#endif diff --git a/include/rfl/parsing/schemaful/tuple_to_named_tuple.hpp b/include/rfl/parsing/schemaful/tuple_to_named_tuple.hpp new file mode 100644 index 00000000..70ea442e --- /dev/null +++ b/include/rfl/parsing/schemaful/tuple_to_named_tuple.hpp @@ -0,0 +1,53 @@ +#ifndef RFL_PARSING_SCHEMAFUL_TUPLETONAMEDTUPLE_HPP_ +#define RFL_PARSING_SCHEMAFUL_TUPLETONAMEDTUPLE_HPP_ + +#include +#include +#include + +#include "../../Field.hpp" +#include "../../Tuple.hpp" +#include "../../internal/StringLiteral.hpp" +#include "../../make_named_tuple.hpp" + +namespace rfl::parsing::schemaful { + +template +consteval auto to_field_name() { + return internal::StringLiteral<5>('f', + static_cast('0' + ((_i / 100) % 10)), + static_cast('0' + ((_i / 10) % 10)), + static_cast('0' + (_i % 10))); +} + +template +auto to_field(const auto& _t) { + using T = std::remove_cvref_t; + return rfl::Field(), const T*>(&_t); +} + +/// Schemaful formats often don't have an explicit tuple representation. +/// This is the required workaround. +template +auto tuple_to_named_tuple(const Tuple& _tup) { + static_assert(sizeof...(Ts) <= 1000, + "The tuple cannot contain more than 1000 elements."); + return [&](std::integer_sequence) { + return rfl::make_named_tuple(to_field<_is>(rfl::get<_is>(_tup))...); + }(std::make_integer_sequence()); +} + +/// Schemaful formats often don't have an explicit tuple representation. +/// This is the required workaround. +template +auto tuple_to_named_tuple(const std::tuple& _tup) { + static_assert(sizeof...(Ts) <= 1000, + "The tuple cannot contain more than 1000 elements."); + return [&](std::integer_sequence) { + return rfl::make_named_tuple(to_field<_is>(std::get<_is>(_tup))...); + }(std::make_integer_sequence()); +} + +} // namespace rfl::parsing::schemaful + +#endif diff --git a/include/rfl/parsing/schemaful/tuple_to_named_tuple_t.hpp b/include/rfl/parsing/schemaful/tuple_to_named_tuple_t.hpp new file mode 100644 index 00000000..3b369b33 --- /dev/null +++ b/include/rfl/parsing/schemaful/tuple_to_named_tuple_t.hpp @@ -0,0 +1,48 @@ +#ifndef RFL_PARSING_SCHEMAFUL_TUPLETONAMEDTUPLE_T_HPP_ +#define RFL_PARSING_SCHEMAFUL_TUPLETONAMEDTUPLE_T_HPP_ + +#include +#include +#include + +#include "../../NamedTuple.hpp" +#include "../../Tuple.hpp" +#include "tuple_to_named_tuple.hpp" + +namespace rfl::parsing::schemaful { + +template +struct ToNamedTuple; + +template +struct ToNamedTuple, Ts...> { + using Type = NamedTuple(), Ts>...>; +}; + +template +struct TupleToNamedTuple; + +template +struct TupleToNamedTuple> { + using Type = + typename ToNamedTuple, + Ts...>::Type; +}; + +template +struct TupleToNamedTuple> { + using Type = + typename ToNamedTuple, + Ts...>::Type; +}; + +/// Given +/// std::tuple or rfl::Tuple +/// return +/// NamedTuple, Field<"f001", T2>, Field<"f002", T3>, ...> +template +using tuple_to_named_tuple_t = typename TupleToNamedTuple::Type; + +} // namespace rfl::parsing::schemaful + +#endif diff --git a/include/rfl/parsing/schemaful/tuple_to_object.hpp b/include/rfl/parsing/schemaful/tuple_to_object.hpp new file mode 100644 index 00000000..a4cad6ad --- /dev/null +++ b/include/rfl/parsing/schemaful/tuple_to_object.hpp @@ -0,0 +1,28 @@ +#ifndef RFL_PARSING_SCHEMAFUL_TUPLETOOBJECT_HPP_ +#define RFL_PARSING_SCHEMAFUL_TUPLETOOBJECT_HPP_ + +#include + +#include "../schema/Type.hpp" + +namespace rfl::parsing::schemaful { + +std::string to_field_name(const size_t _i) { + return std::string({'f', static_cast('0' + ((_i / 100) % 10)), + static_cast('0' + ((_i / 10) % 10)), + static_cast('0' + (_i % 10))}); +} + +/// Schemaful formats often don't have an explicit tuple representation. +/// This is the required workaround. +schema::Type::Object tuple_to_object(const schema::Type::Tuple& _tup) { + auto obj = schema::Type::Object{}; + for (size_t i = 0; i < _tup.types_.size(); ++i) { + obj.types_[to_field_name(i)] = _tup.types_[i]; + } + return obj; +} + +} // namespace rfl::parsing::schemaful + +#endif diff --git a/src/reflectcpp_avro.cpp b/src/reflectcpp_avro.cpp new file mode 100644 index 00000000..d7b64f63 --- /dev/null +++ b/src/reflectcpp_avro.cpp @@ -0,0 +1,36 @@ +/* + +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. + +*/ + +// This file include all other source files, so that the user of the library +// don't need to add multiple source files into their build. +// Also, this speeds up compile time, compared to multiple separate .cpp files +// compilation. + +#include "rfl/avro/Reader.cpp" +#include "rfl/avro/SchemaImpl.cpp" +#include "rfl/avro/Type.cpp" +#include "rfl/avro/Writer.cpp" +#include "rfl/avro/to_schema.cpp" diff --git a/src/rfl/avro/Reader.cpp b/src/rfl/avro/Reader.cpp new file mode 100644 index 00000000..6d8bd18e --- /dev/null +++ b/src/rfl/avro/Reader.cpp @@ -0,0 +1,49 @@ +#include "rfl/avro/Reader.hpp" + +#include "rfl/parsing/schemaful/IsSchemafulReader.hpp" + +namespace rfl::avro { + +static_assert(parsing::schemaful::IsSchemafulReader, + "This must be a schemaful reader."); + +bool Reader::is_empty(const InputVarType& _var) const noexcept { + return avro_value_get_type(_var.val_) == AVRO_NULL; +} + +rfl::Result Reader::to_array( + const InputVarType& _var) const noexcept { + if (avro_value_get_type(_var.val_) != AVRO_ARRAY) { + return Error("Could not cast to an array."); + } + return InputArrayType{_var.val_}; +} + +rfl::Result Reader::to_object( + const InputVarType& _var) const noexcept { + const auto type = avro_value_get_type(_var.val_); + if (type != AVRO_RECORD) { + return Error("Could not cast to an object."); + } + return InputObjectType{_var.val_}; +} + +rfl::Result Reader::to_map( + const InputVarType& _var) const noexcept { + const auto type = avro_value_get_type(_var.val_); + if (type != AVRO_MAP) { + return Error("Could not cast to a map."); + } + return InputMapType{_var.val_}; +} + +rfl::Result Reader::to_union( + const InputVarType& _var) const noexcept { + const auto type = avro_value_get_type(_var.val_); + if (type != AVRO_UNION) { + return Error("Could not cast to a union."); + } + return InputUnionType{_var.val_}; +} + +} // namespace rfl::avro diff --git a/src/rfl/avro/SchemaImpl.cpp b/src/rfl/avro/SchemaImpl.cpp new file mode 100644 index 00000000..21786bc7 --- /dev/null +++ b/src/rfl/avro/SchemaImpl.cpp @@ -0,0 +1,44 @@ +#include "rfl/avro/SchemaImpl.hpp" + +namespace rfl::avro { + +SchemaImpl::SchemaImpl(const std::string& _json_str) + : json_str_(_json_str), + schema_(Box::make()), + iface_(nullptr) { + const auto err = avro_schema_from_json_length( + _json_str.c_str(), _json_str.size(), schema_.get()); + if (err) { + throw std::runtime_error( + "Cannot create schema from the following JSON: \"" + _json_str + + "\": " + avro_strerror()); + } + iface_ = avro_generic_class_from_schema(*schema_); +} + +SchemaImpl::~SchemaImpl() { + if (iface_) { + avro_value_iface_decref(iface_); + iface_ = nullptr; + avro_schema_decref(*schema_); + } +} + +SchemaImpl::SchemaImpl(SchemaImpl&& _other) noexcept + : json_str_(std::move(_other.json_str_)), + schema_(std::move(_other.schema_)), + iface_(_other.iface_) { + _other.iface_ = nullptr; +} + +SchemaImpl& SchemaImpl::operator=(SchemaImpl&& _other) noexcept { + if (this == &_other) { + return *this; + } + json_str_ = std::move(_other.json_str_); + schema_ = std::move(_other.schema_); + iface_ = _other.iface_; + return *this; +} + +} // namespace rfl::avro diff --git a/src/rfl/avro/Type.cpp b/src/rfl/avro/Type.cpp new file mode 100644 index 00000000..b4f850fb --- /dev/null +++ b/src/rfl/avro/Type.cpp @@ -0,0 +1,45 @@ +/* + +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/avro/schema/Type.hpp" + +namespace rfl::avro::schema { + +Type Type::with_name(const std::string& _name) const { + const auto set_name = [&](const auto& _v) -> ReflectionType { + using T = std::remove_cvref_t; + if constexpr (std::is_same() || std::is_same()) { + auto v_with_name = _v; + v_with_name.name = _name; + return v_with_name; + } else { + return _v; + } + }; + return Type{.value = value.visit(set_name)}; +} + +} // namespace rfl::avro::schema diff --git a/src/rfl/avro/Writer.cpp b/src/rfl/avro/Writer.cpp new file mode 100644 index 00000000..45ef4f71 --- /dev/null +++ b/src/rfl/avro/Writer.cpp @@ -0,0 +1,190 @@ +#include "rfl/avro/Writer.hpp" + +#include "rfl/parsing/schemaful/IsSchemafulWriter.hpp" + +namespace rfl::avro { + +static_assert(parsing::schemaful::IsSchemafulWriter, + "This must be a schemaful writer."); + +Writer::Writer(avro_value_t* _root) : root_(_root){}; + +Writer::~Writer() = default; + +Writer::OutputArrayType Writer::array_as_root( + const size_t _size) const noexcept { + return OutputArrayType{*root_}; +} + +Writer::OutputMapType Writer::map_as_root(const size_t _size) const noexcept { + return OutputMapType{*root_}; +} + +Writer::OutputObjectType Writer::object_as_root( + const size_t _size) const noexcept { + return OutputObjectType{*root_}; +} + +Writer::OutputVarType Writer::null_as_root() const noexcept { + avro_value_set_null(root_); + return OutputVarType{*root_}; +} + +Writer::OutputUnionType Writer::union_as_root() const noexcept { + return OutputUnionType{*root_}; +} + +Writer::OutputArrayType Writer::add_array_to_array( + const size_t _size, OutputArrayType* _parent) const noexcept { + avro_value_t new_array; + avro_value_append(&_parent->val_, &new_array, nullptr); + return OutputArrayType{new_array}; +} + +Writer::OutputArrayType Writer::add_array_to_map( + const std::string_view& _name, const size_t _size, + OutputMapType* _parent) const noexcept { + avro_value_t new_array; + avro_value_add(&_parent->val_, _name.data(), &new_array, nullptr, nullptr); + return OutputArrayType{new_array}; +} + +Writer::OutputArrayType Writer::add_array_to_object( + const std::string_view& _name, const size_t _size, + OutputObjectType* _parent) const noexcept { + avro_value_t new_array; + avro_value_get_by_name(&_parent->val_, _name.data(), &new_array, nullptr); + return OutputArrayType{new_array}; +} + +Writer::OutputArrayType Writer::add_array_to_union( + const size_t _index, const size_t _size, + OutputUnionType* _parent) const noexcept { + avro_value_t new_array; + avro_value_set_branch(&_parent->val_, static_cast(_index), &new_array); + return OutputArrayType{new_array}; +} + +Writer::OutputMapType Writer::add_map_to_array( + const size_t _size, OutputArrayType* _parent) const noexcept { + avro_value_t new_map; + avro_value_append(&_parent->val_, &new_map, nullptr); + return OutputMapType{new_map}; +} + +Writer::OutputMapType Writer::add_map_to_map( + const std::string_view& _name, const size_t _size, + OutputMapType* _parent) const noexcept { + avro_value_t new_map; + avro_value_add(&_parent->val_, _name.data(), &new_map, nullptr, nullptr); + return OutputMapType{new_map}; +} + +Writer::OutputMapType Writer::add_map_to_object( + const std::string_view& _name, const size_t _size, + OutputObjectType* _parent) const noexcept { + avro_value_t new_map; + avro_value_get_by_name(&_parent->val_, _name.data(), &new_map, nullptr); + return OutputMapType{new_map}; +} + +Writer::OutputMapType Writer::add_map_to_union( + const size_t _index, const size_t _size, + OutputUnionType* _parent) const noexcept { + avro_value_t new_map; + avro_value_set_branch(&_parent->val_, static_cast(_index), &new_map); + return OutputMapType{new_map}; +} + +Writer::OutputObjectType Writer::add_object_to_array( + const size_t _size, OutputArrayType* _parent) const noexcept { + avro_value_t new_object; + avro_value_append(&_parent->val_, &new_object, nullptr); + return OutputObjectType{new_object}; +} + +Writer::OutputObjectType Writer::add_object_to_map( + const std::string_view& _name, const size_t _size, + OutputMapType* _parent) const noexcept { + avro_value_t new_object; + avro_value_add(&_parent->val_, _name.data(), &new_object, nullptr, nullptr); + return OutputObjectType{new_object}; +} + +Writer::OutputObjectType Writer::add_object_to_object( + const std::string_view& _name, const size_t _size, + OutputObjectType* _parent) const noexcept { + avro_value_t new_object; + avro_value_get_by_name(&_parent->val_, _name.data(), &new_object, nullptr); + return OutputObjectType{new_object}; +} + +Writer::OutputObjectType Writer::add_object_to_union( + const size_t _index, const size_t _size, + OutputUnionType* _parent) const noexcept { + avro_value_t new_object; + avro_value_set_branch(&_parent->val_, static_cast(_index), &new_object); + return OutputObjectType{new_object}; +} + +Writer::OutputUnionType Writer::add_union_to_array( + OutputArrayType* _parent) const noexcept { + avro_value_t new_union; + avro_value_append(&_parent->val_, &new_union, nullptr); + return OutputUnionType{new_union}; +} + +Writer::OutputUnionType Writer::add_union_to_map( + const std::string_view& _name, OutputMapType* _parent) const noexcept { + avro_value_t new_union; + avro_value_add(&_parent->val_, _name.data(), &new_union, nullptr, nullptr); + return OutputUnionType{new_union}; +} + +Writer::OutputUnionType Writer::add_union_to_object( + const std::string_view& _name, OutputObjectType* _parent) const noexcept { + avro_value_t new_union; + avro_value_get_by_name(&_parent->val_, _name.data(), &new_union, nullptr); + return OutputUnionType{new_union}; +} + +Writer::OutputUnionType Writer::add_union_to_union( + const size_t _index, OutputUnionType* _parent) const noexcept { + avro_value_t new_union; + avro_value_set_branch(&_parent->val_, static_cast(_index), &new_union); + return OutputUnionType{new_union}; +} + +Writer::OutputVarType Writer::add_null_to_array( + OutputArrayType* _parent) const noexcept { + avro_value_t new_null; + avro_value_append(&_parent->val_, &new_null, nullptr); + avro_value_set_null(&new_null); + return OutputVarType{new_null}; +} + +Writer::OutputVarType Writer::add_null_to_map( + const std::string_view& _name, OutputMapType* _parent) const noexcept { + avro_value_t new_null; + avro_value_add(&_parent->val_, _name.data(), &new_null, nullptr, nullptr); + avro_value_set_null(&new_null); + return OutputVarType{new_null}; +} + +Writer::OutputVarType Writer::add_null_to_object( + const std::string_view& _name, OutputObjectType* _parent) const noexcept { + avro_value_t new_null; + avro_value_get_by_name(&_parent->val_, _name.data(), &new_null, nullptr); + avro_value_set_null(&new_null); + return OutputVarType{new_null}; +} + +Writer::OutputVarType Writer::add_null_to_union( + const size_t _index, OutputUnionType* _parent) const noexcept { + avro_value_t new_null; + avro_value_set_branch(&_parent->val_, static_cast(_index), &new_null); + avro_value_set_null(&new_null); + return OutputVarType{new_null}; +} + +} // namespace rfl::avro diff --git a/src/rfl/avro/to_schema.cpp b/src/rfl/avro/to_schema.cpp new file mode 100644 index 00000000..a9c86fc6 --- /dev/null +++ b/src/rfl/avro/to_schema.cpp @@ -0,0 +1,178 @@ +/* + +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/avro/to_schema.hpp" + +#include "rfl/avro/schema/Type.hpp" +#include "rfl/json.hpp" +#include "rfl/parsing/schemaful/tuple_to_object.hpp" + +namespace rfl::avro { + +inline bool is_named_type(const parsing::schema::Type& _type) { + return _type.variant_.visit([&](const auto& _v) -> bool { + using T = std::remove_cvref_t; + return std::is_same() || + std::is_same(); + }); +} + +schema::Type type_to_avro_schema_type( + const parsing::schema::Type& _type, + const std::map& _definitions, + std::set* _already_known, size_t* _num_unnamed) { + auto handle_variant = [&](const auto& _t) -> schema::Type { + using T = std::remove_cvref_t; + using Type = parsing::schema::Type; + if constexpr (std::is_same()) { + return schema::Type{.value = schema::Type::Boolean{}}; + + } else if constexpr (std::is_same()) { + return schema::Type{.value = schema::Type::Bytes{}}; + + } else if constexpr (std::is_same() || + std::is_same() || + std::is_same() || + std::is_same() || + std::is_same()) { + return schema::Type{.value = schema::Type::Int{}}; + + } else if constexpr (std::is_same() || + std::is_same() || + std::is_same()) { + return schema::Type{.value = schema::Type::Long{}}; + + } else if constexpr (std::is_same()) { + return schema::Type{.value = schema::Type::Float{}}; + + } else if constexpr (std::is_same()) { + return schema::Type{.value = schema::Type::Double{}}; + + } else if constexpr (std::is_same()) { + return schema::Type{.value = schema::Type::String{}}; + + } else if constexpr (std::is_same()) { + auto any_of = std::vector(); + for (const auto& t : _t.types_) { + any_of.emplace_back(type_to_avro_schema_type( + t, _definitions, _already_known, _num_unnamed)); + } + return schema::Type{.value = any_of}; + + } else if constexpr (std::is_same()) { + // TODO: Return descriptions + return type_to_avro_schema_type(*_t.type_, _definitions, _already_known, + _num_unnamed); + + } else if constexpr (std::is_same()) { + return schema::Type{ + .value = schema::Type::Array{ + .items = Ref::make(type_to_avro_schema_type( + *_t.type_, _definitions, _already_known, _num_unnamed))}}; + + } else if constexpr (std::is_same()) { + return schema::Type{ + .value = schema::Type::Enum{.name = std::string("unnamed_") + + std::to_string(++(*_num_unnamed)), + .symbols = _t.values_}}; + + } else if constexpr (std::is_same()) { + auto record = schema::Type::Record{ + .name = std::string("unnamed_") + std::to_string(++(*_num_unnamed))}; + for (const auto& [k, v] : _t.types_) { + record.fields.push_back(schema::Type::RecordField{ + .name = k, + .type = Ref::make(type_to_avro_schema_type( + v, _definitions, _already_known, _num_unnamed))}); + } + return schema::Type{.value = record}; + + } else if constexpr (std::is_same()) { + return schema::Type{ + .value = std::vector( + {type_to_avro_schema_type(*_t.type_, _definitions, _already_known, + _num_unnamed), + schema::Type{schema::Type::Null{}}})}; + + } else if constexpr (std::is_same()) { + if (_definitions.find(_t.name_) != _definitions.end() && + !is_named_type(_definitions.at(_t.name_))) { + return type_to_avro_schema_type(_definitions.at(_t.name_), _definitions, + _already_known, _num_unnamed); + + } else if (_already_known->find(_t.name_) != _already_known->end() || + _definitions.find(_t.name_) == _definitions.end()) { + return schema::Type{.value = schema::Type::Reference{.type = _t.name_}}; + + } else { + _already_known->insert(_t.name_); + return type_to_avro_schema_type(_definitions.at(_t.name_), _definitions, + _already_known, _num_unnamed) + .with_name(_t.name_); + } + + } else if constexpr (std::is_same()) { + return schema::Type{ + .value = schema::Type::Map{ + .values = Ref::make( + type_to_avro_schema_type(*_t.value_type_, _definitions, + _already_known, _num_unnamed))}}; + + } else if constexpr (std::is_same()) { + return type_to_avro_schema_type( + Type{parsing::schemaful::tuple_to_object(_t)}, _definitions, + _already_known, _num_unnamed); + + } else if constexpr (std::is_same()) { + return schema::Type{ + .value = schema::Type::Array{ + .items = Ref::make(type_to_avro_schema_type( + *_t.type_, _definitions, _already_known, _num_unnamed))}}; + + } else if constexpr (std::is_same()) { + // Avro knows no validation. + return type_to_avro_schema_type(*_t.type_, _definitions, _already_known, + _num_unnamed); + + } else { + static_assert(rfl::always_false_v, "Not all cases were covered."); + } + }; + + return rfl::visit(handle_variant, _type.variant_); +} + +std::string to_json_representation( + const parsing::schema::Definition& _internal_schema) { + std::set already_known; + size_t num_unnamed = 0; + const auto avro_schema = type_to_avro_schema_type( + _internal_schema.root_, _internal_schema.definitions_, &already_known, + &num_unnamed); + return rfl::json::write(avro_schema); +} + +} // namespace rfl::avro diff --git a/src/rfl/json/to_schema.cpp b/src/rfl/json/to_schema.cpp index bc1e87c7..e361562d 100644 --- a/src/rfl/json/to_schema.cpp +++ b/src/rfl/json/to_schema.cpp @@ -191,7 +191,8 @@ schema::Type type_to_json_schema_type(const parsing::schema::Type& _type) { std::is_same()) { return schema::Type{.value = schema::Type::Number{}}; - } else if constexpr (std::is_same()) { + } else if constexpr (std::is_same() || + std::is_same()) { return schema::Type{.value = schema::Type::String{}}; } else if constexpr (std::is_same()) { @@ -221,7 +222,7 @@ schema::Type type_to_json_schema_type(const parsing::schema::Type& _type) { schema::Type::StringEnum{.values = _t.values_}}; } else if constexpr (std::is_same()) { - auto properties = std::map(); + auto properties = rfl::Object(); auto required = std::vector(); for (const auto& [k, v] : _t.types_) { properties[k] = type_to_json_schema_type(v); diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 0ccde04c..d99a20a2 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -3,7 +3,7 @@ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -O2") if (MSVC) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std:c++20") else() - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O3 -Wall -Werror -ggdb -ftemplate-backtrace-limit=0") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O3 -Wall -ggdb -ftemplate-backtrace-limit=0") endif() if (REFLECTCPP_JSON) @@ -12,6 +12,10 @@ if (REFLECTCPP_JSON) add_subdirectory(json_c_arrays_and_inheritance) endif () +if (REFLECTCPP_AVRO) + add_subdirectory(avro) +endif() + if (REFLECTCPP_BSON) add_subdirectory(bson) endif() diff --git a/tests/README.md b/tests/README.md index 372dc312..3da3b66b 100644 --- a/tests/README.md +++ b/tests/README.md @@ -32,7 +32,7 @@ To run the tests, do the following: To compile the tests with serialization formats other than JSON, do the following: ```bash -cmake -S . -B build -DREFLECTCPP_BUILD_TESTS=ON -DREFLECTCPP_BSON=ON -DREFLECTCPP_CBOR=ON -DREFLECTCPP_FLEXBUFFERS=ON -DREFLECTCPP_MSGPACK=ON -DREFLECTCPP_XML=ON -DREFLECTCPP_TOML=ON -DREFLECTCPP_UBJSON=ON -DREFLECTCPP_YAML=ON -DCMAKE_BUILD_TYPE=Release +cmake -S . -B build -DREFLECTCPP_BUILD_TESTS=ON -DREFLECTCPP_AVRO=ON -DREFLECTCPP_BSON=ON -DREFLECTCPP_CBOR=ON -DREFLECTCPP_FLEXBUFFERS=ON -DREFLECTCPP_MSGPACK=ON -DREFLECTCPP_XML=ON -DREFLECTCPP_TOML=ON -DREFLECTCPP_UBJSON=ON -DREFLECTCPP_YAML=ON -DCMAKE_BUILD_TYPE=Release cmake --build build -j 4 # gcc, clang cmake --build build --config Release -j 4 # MSVC ``` @@ -40,6 +40,7 @@ cmake --build build --config Release -j 4 # MSVC To run the tests, do the following: ``` +./build/tests/avro/reflect-cpp-avro-tests ./build/tests/bson/reflect-cpp-bson-tests ./build/tests/cbor/reflect-cpp-cbor-tests ./build/tests/flexbuffers/reflect-cpp-flexbuffers-tests diff --git a/tests/avro/CMakeLists.txt b/tests/avro/CMakeLists.txt new file mode 100644 index 00000000..cf7972e9 --- /dev/null +++ b/tests/avro/CMakeLists.txt @@ -0,0 +1,19 @@ +project(reflect-cpp-avro-tests) + +file(GLOB_RECURSE SOURCES CONFIGURE_DEPENDS "*.cpp") + +add_executable( + reflect-cpp-avro-tests + ${SOURCES} +) +target_precompile_headers(reflect-cpp-avro-tests PRIVATE [["rfl.hpp"]] ) + + +target_link_libraries( + reflect-cpp-avro-tests + PRIVATE + "${REFLECT_CPP_GTEST_LIB}" +) + +find_package(GTest) +gtest_discover_tests(reflect-cpp-avro-tests) diff --git a/tests/avro/test_add_struct_name.cpp b/tests/avro/test_add_struct_name.cpp new file mode 100644 index 00000000..faf4caaf --- /dev/null +++ b/tests/avro/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(avro, 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/avro/test_array.cpp b/tests/avro/test_array.cpp new file mode 100644 index 00000000..2958983d --- /dev/null +++ b/tests/avro/test_array.cpp @@ -0,0 +1,35 @@ +#include +#include +#include +#include +#include + +// Make sure things still compile when +// rfl.hpp is included after rfl/avro.hpp. +#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(avro, 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/avro/test_box.cpp b/tests/avro/test_box.cpp new file mode 100644 index 00000000..529314f2 --- /dev/null +++ b/tests/avro/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(avro, 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/avro/test_bytestring.cpp b/tests/avro/test_bytestring.cpp new file mode 100644 index 00000000..52f6172e --- /dev/null +++ b/tests/avro/test_bytestring.cpp @@ -0,0 +1,21 @@ +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_bytestring { + +struct TestStruct { + rfl::Bytestring bytestring; +}; + +TEST(avro, test_bytestring) { + const auto test = + TestStruct{.bytestring = rfl::Bytestring({std::byte{13}, std::byte{14}, + std::byte{15}, std::byte{16}})}; + + write_and_read(test); +} +} // namespace test_bytestring diff --git a/tests/avro/test_combined_processors.cpp b/tests/avro/test_combined_processors.cpp new file mode 100644 index 00000000..b7480cee --- /dev/null +++ b/tests/avro/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(avro, 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/avro/test_custom_class1.cpp b/tests/avro/test_custom_class1.cpp new file mode 100644 index 00000000..75b62332 --- /dev/null +++ b/tests/avro/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(avro, test_custom_class1) { + const auto bart = Person("Bart"); + + write_and_read(bart); +} +} // namespace test_custom_class1 diff --git a/tests/avro/test_custom_class3.cpp b/tests/avro/test_custom_class3.cpp new file mode 100644 index 00000000..6433ba17 --- /dev/null +++ b/tests/avro/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(avro, test_custom_class3) { + const auto bart = Person("Bart", "Simpson", 10); + + write_and_read(bart); +} + +} // namespace test_custom_class3 diff --git a/tests/avro/test_custom_class4.cpp b/tests/avro/test_custom_class4.cpp new file mode 100644 index 00000000..afd507ce --- /dev/null +++ b/tests/avro/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(avro, 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/avro/test_default_values.cpp b/tests/avro/test_default_values.cpp new file mode 100644 index 00000000..83094716 --- /dev/null +++ b/tests/avro/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(avro, 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/avro/test_deque.cpp b/tests/avro/test_deque.cpp new file mode 100644 index 00000000..78237357 --- /dev/null +++ b/tests/avro/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(avro, 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/avro/test_enum.cpp b/tests/avro/test_enum.cpp new file mode 100644 index 00000000..60b2e67d --- /dev/null +++ b/tests/avro/test_enum.cpp @@ -0,0 +1,25 @@ +#include +#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(avro, test_enum) { + const auto circle = Circle{.radius = 2.0, .color = Color::green}; + + write_and_read(circle); +} + +} // namespace test_enum diff --git a/tests/avro/test_field_variant.cpp b/tests/avro/test_field_variant.cpp new file mode 100644 index 00000000..1001fe67 --- /dev/null +++ b/tests/avro/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(avro, test_field_variant_std) { + const Shapes r = + rfl::make_field<"rectangle">(Rectangle{.height = 10, .width = 5}); + + write_and_read(r); +} +} // namespace test_field_variant diff --git a/tests/avro/test_field_variant_std.cpp b/tests/avro/test_field_variant_std.cpp new file mode 100644 index 00000000..3424361c --- /dev/null +++ b/tests/avro/test_field_variant_std.cpp @@ -0,0 +1,34 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_field_variant_std { + +struct Circle { + double radius; +}; + +struct Rectangle { + double height; + double width; +}; + +struct Square { + double width; +}; + +using Shapes = std::variant, + rfl::Field<"rectangle", Rectangle>, + rfl::Field<"square", rfl::Box>>; + +TEST(avro, test_field_variant_std) { + const Shapes r = + rfl::make_field<"rectangle">(Rectangle{.height = 10, .width = 5}); + + write_and_read(r); +} +} // namespace test_field_variant_std diff --git a/tests/avro/test_flag_enum.cpp b/tests/avro/test_flag_enum.cpp new file mode 100644 index 00000000..7e086a69 --- /dev/null +++ b/tests/avro/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(avro, 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/avro/test_flag_enum_with_int.cpp b/tests/avro/test_flag_enum_with_int.cpp new file mode 100644 index 00000000..2dc0b5cf --- /dev/null +++ b/tests/avro/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(avro, 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/avro/test_flatten.cpp b/tests/avro/test_flatten.cpp new file mode 100644 index 00000000..c890ba84 --- /dev/null +++ b/tests/avro/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(avro, 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/avro/test_flatten_anonymous.cpp b/tests/avro/test_flatten_anonymous.cpp new file mode 100644 index 00000000..bbb160dc --- /dev/null +++ b/tests/avro/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(avro, 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/avro/test_forward_list.cpp b/tests/avro/test_forward_list.cpp new file mode 100644 index 00000000..ec831696 --- /dev/null +++ b/tests/avro/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(avro, 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/avro/test_literal.cpp b/tests/avro/test_literal.cpp new file mode 100644 index 00000000..9432b1fb --- /dev/null +++ b/tests/avro/test_literal.cpp @@ -0,0 +1,26 @@ +#include +#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(avro, test_literal) { + const auto bart = Person{.first_name = FirstName::make<"Bart">()}; + + write_and_read(bart); +} +} // namespace test_literal diff --git a/tests/avro/test_literal_map.cpp b/tests/avro/test_literal_map.cpp new file mode 100644 index 00000000..9714d7ce --- /dev/null +++ b/tests/avro/test_literal_map.cpp @@ -0,0 +1,22 @@ +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_literal_map { + +using FieldName = rfl::Literal<"firstName", "lastName">; + +TEST(avro, 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/avro/test_map.cpp b/tests/avro/test_map.cpp new file mode 100644 index 00000000..6b63322e --- /dev/null +++ b/tests/avro/test_map.cpp @@ -0,0 +1,28 @@ +#include +#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::unique_ptr> children; +}; + +TEST(avro, test_map) { + 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 diff --git a/tests/avro/test_map2.cpp b/tests/avro/test_map2.cpp new file mode 100644 index 00000000..51f1afa9 --- /dev/null +++ b/tests/avro/test_map2.cpp @@ -0,0 +1,28 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_map2 { + +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name = "Simpson"; + std::map children; +}; + +TEST(avro, test_map2) { + auto children = std::map(); + 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_map2 diff --git a/tests/avro/test_monster_example.cpp b/tests/avro/test_monster_example.cpp new file mode 100644 index 00000000..19a8bbdc --- /dev/null +++ b/tests/avro/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(avro, 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/avro/test_optional_fields.cpp b/tests/avro/test_optional_fields.cpp new file mode 100644 index 00000000..ef32c0a8 --- /dev/null +++ b/tests/avro/test_optional_fields.cpp @@ -0,0 +1,30 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_optional_fields { + +struct Person { + std::string first_name; + std::string last_name = "Simpson"; + std::optional> children; +}; + +TEST(avro, test_optional_fields) { + 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_optional_fields diff --git a/tests/avro/test_readme_example.cpp b/tests/avro/test_readme_example.cpp new file mode 100644 index 00000000..4a63f464 --- /dev/null +++ b/tests/avro/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(avro, 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/avro/test_readme_example2.cpp b/tests/avro/test_readme_example2.cpp new file mode 100644 index 00000000..69f8b8ed --- /dev/null +++ b/tests/avro/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(avro, 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/avro/test_readme_example3.cpp b/tests/avro/test_readme_example3.cpp new file mode 100644 index 00000000..169f6aed --- /dev/null +++ b/tests/avro/test_readme_example3.cpp @@ -0,0 +1,31 @@ +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_readme_example3 { + +struct Person { + std::string first_name; + std::string last_name; + rfl::Timestamp<"%Y-%m-%d"> birthday; + std::vector children; +}; + +TEST(avro, test_readme_example3) { + const auto bart = Person{.first_name = "Bart", .birthday = "1987-04-19"}; + + const auto lisa = Person{.first_name = "Lisa", .birthday = "1987-04-19"}; + + const auto maggie = Person{.first_name = "Maggie", .birthday = "1987-04-19"}; + + const auto homer = + Person{.first_name = "Homer", + .birthday = "1987-04-19", + .children = std::vector({bart, lisa, maggie})}; + + write_and_read(homer); +} +} // namespace test_readme_example3 diff --git a/tests/avro/test_ref.cpp b/tests/avro/test_ref.cpp new file mode 100644 index 00000000..a997193d --- /dev/null +++ b/tests/avro/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(avro, 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/avro/test_rfl_tuple.cpp b/tests/avro/test_rfl_tuple.cpp new file mode 100644 index 00000000..85641ffc --- /dev/null +++ b/tests/avro/test_rfl_tuple.cpp @@ -0,0 +1,33 @@ + +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_rfl_tuple { + +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name = "Simpson"; + std::unique_ptr> children = nullptr; +}; + +TEST(avro, test_rfl_tuple) { + 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>( + rfl::Tuple{ + std::move(bart), std::move(lisa), std::move(maggie)})}; + + write_and_read(homer); +} +} // namespace test_rfl_tuple diff --git a/tests/avro/test_rfl_variant.cpp b/tests/avro/test_rfl_variant.cpp new file mode 100644 index 00000000..b5e516ac --- /dev/null +++ b/tests/avro/test_rfl_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 = rfl::Variant>; + +TEST(avro, test_rfl_variant) { + const Shapes r = Rectangle{.height = 10, .width = 5}; + + write_and_read(r); +} +} // namespace test_variant diff --git a/tests/avro/test_save_load.cpp b/tests/avro/test_save_load.cpp new file mode 100644 index 00000000..0bc4d3dc --- /dev/null +++ b/tests/avro/test_save_load.cpp @@ -0,0 +1,61 @@ +#include +#include +#include +#include +#include +#include + +#include + +namespace test_save_load { + +using Age = rfl::Validator, rfl::Maximum<130>>>; + +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + rfl::Timestamp<"%Y-%m-%d"> birthday; + Age age; + rfl::Email email; + std::vector children; +}; + +TEST(avro, test_save_load) { + const auto bart = Person{.first_name = "Bart", + .last_name = "Simpson", + .birthday = "1987-04-19", + .age = 10, + .email = "bart@simpson.com", + .children = std::vector()}; + + const auto lisa = Person{.first_name = "Lisa", + .last_name = "Simpson", + .birthday = "1987-04-19", + .age = 8, + .email = "lisa@simpson.com"}; + + const auto maggie = Person{.first_name = "Maggie", + .last_name = "Simpson", + .birthday = "1987-04-19", + .age = 0, + .email = "maggie@simpson.com"}; + + const auto homer1 = + Person{.first_name = "Homer", + .last_name = "Simpson", + .birthday = "1987-04-19", + .age = 45, + .email = "homer@simpson.com", + .children = std::vector({bart, lisa, maggie})}; + + rfl::avro::save("homer.avro", homer1); + + const auto homer2 = rfl::avro::load("homer.avro").value(); + + const auto string1 = rfl::avro::write(homer1); + const auto string2 = rfl::avro::write(homer2); + + EXPECT_EQ(string1, string2); +} +} // namespace test_save_load diff --git a/tests/avro/test_set.cpp b/tests/avro/test_set.cpp new file mode 100644 index 00000000..cd5c778c --- /dev/null +++ b/tests/avro/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(avro, 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/avro/test_shared_ptr.cpp b/tests/avro/test_shared_ptr.cpp new file mode 100644 index 00000000..5e9fb6ba --- /dev/null +++ b/tests/avro/test_shared_ptr.cpp @@ -0,0 +1,29 @@ +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_shared_ptr { + +struct Person { + std::string first_name; + std::string last_name = "Simpson"; + std::shared_ptr> children; +}; + +TEST(avro, test_shared_ptr) { + auto children = std::make_shared>(); + 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_shared_ptr diff --git a/tests/avro/test_size.cpp b/tests/avro/test_size.cpp new file mode 100644 index 00000000..271ae64f --- /dev/null +++ b/tests/avro/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(avro, 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/avro/test_snake_case_to_camel_case.cpp b/tests/avro/test_snake_case_to_camel_case.cpp new file mode 100644 index 00000000..11e9e009 --- /dev/null +++ b/tests/avro/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(avro, 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/avro/test_snake_case_to_pascal_case.cpp b/tests/avro/test_snake_case_to_pascal_case.cpp new file mode 100644 index 00000000..1ddbe232 --- /dev/null +++ b/tests/avro/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(avro, 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/avro/test_string_map.cpp b/tests/avro/test_string_map.cpp new file mode 100644 index 00000000..7f650532 --- /dev/null +++ b/tests/avro/test_string_map.cpp @@ -0,0 +1,20 @@ +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_string_map { +TEST(avro, 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/avro/test_tagged_union.cpp b/tests/avro/test_tagged_union.cpp new file mode 100644 index 00000000..2ed9359f --- /dev/null +++ b/tests/avro/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", Rectangle, Circle, Square>; + +TEST(avro, test_tagged_union) { + const Shapes r = Rectangle{.height = 10, .width = 5}; + write_and_read(r); +} +} // namespace test_tagged_union diff --git a/tests/avro/test_timestamp.cpp b/tests/avro/test_timestamp.cpp new file mode 100644 index 00000000..27086911 --- /dev/null +++ b/tests/avro/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(avro, 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/avro/test_tuple.cpp b/tests/avro/test_tuple.cpp new file mode 100644 index 00000000..e9cd1233 --- /dev/null +++ b/tests/avro/test_tuple.cpp @@ -0,0 +1,33 @@ + +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_tuple { + +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name = "Simpson"; + std::unique_ptr> children = nullptr; +}; + +TEST(avro, test_tuple) { + 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::tuple{ + std::move(bart), std::move(lisa), std::move(maggie)})}; + + write_and_read(homer); +} +} // namespace test_tuple diff --git a/tests/avro/test_tutorial_example.cpp b/tests/avro/test_tutorial_example.cpp new file mode 100644 index 00000000..72ca6245 --- /dev/null +++ b/tests/avro/test_tutorial_example.cpp @@ -0,0 +1,46 @@ +#include + +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +/// The basic example from the Avro C tutorial. +namespace test_tutorial_example { + +const char PERSON_SCHEMA[] = + "{\"type\":\"record\",\ + \"name\":\"Person\",\ + \"fields\":[\ + {\"name\": \"ID\", \"type\": \"long\"},\ + {\"name\": \"First\", \"type\": \"string\"},\ + {\"name\": \"Last\", \"type\": \"string\"},\ + {\"name\": \"Phone\", \"type\": \"string\"},\ + {\"name\": \"Age\", \"type\": \"int\"}]}"; + +struct Person { + size_t ID; + std::string First; + std::string Last; + std::string Phone; + int Age; +}; + +TEST(avro, test_tutorial_example) { + const auto person = Person{.ID = 1, + .First = "Randal", + .Last = "Graves", + .Phone = "(555) 123-5678", + .Age = 30}; + const auto schema = rfl::avro::Schema::from_json(PERSON_SCHEMA); + const auto serialized1 = rfl::avro::write(person, schema.value()); + const auto res = rfl::avro::read(serialized1, schema.value()); + EXPECT_TRUE(res && true) << "Test failed on read. Error: " + << res.error().value().what(); + const auto serialized2 = rfl::avro::write(res.value(), schema.value()); + EXPECT_EQ(serialized1, serialized2); +} +} // namespace test_tutorial_example diff --git a/tests/avro/test_tutorial_example_automated_schema.cpp b/tests/avro/test_tutorial_example_automated_schema.cpp new file mode 100644 index 00000000..7d2af0f3 --- /dev/null +++ b/tests/avro/test_tutorial_example_automated_schema.cpp @@ -0,0 +1,30 @@ +#include + +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +/// The basic example from the Avro C tutorial. +namespace test_tutorial_example_automated_schema { + +struct Person { + size_t ID; + std::string First; + std::string Last; + std::string Phone; + int Age; +}; + +TEST(avro, test_tutorial_example_automated_schema) { + const auto person = Person{.ID = 1, + .First = "Randal", + .Last = "Graves", + .Phone = "(555) 123-5678", + .Age = 30}; + write_and_read(person); +} +} // namespace test_tutorial_example_automated_schema diff --git a/tests/avro/test_unique_ptr.cpp b/tests/avro/test_unique_ptr.cpp new file mode 100644 index 00000000..c2d50012 --- /dev/null +++ b/tests/avro/test_unique_ptr.cpp @@ -0,0 +1,29 @@ +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_unique_ptr { + +struct Person { + std::string first_name; + std::string last_name = "Simpson"; + std::unique_ptr> children; +}; + +TEST(avro, 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/avro/test_unique_ptr2.cpp b/tests/avro/test_unique_ptr2.cpp new file mode 100644 index 00000000..9f663a72 --- /dev/null +++ b/tests/avro/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(avro, 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/avro/test_variant.cpp b/tests/avro/test_variant.cpp new file mode 100644 index 00000000..72d7ed34 --- /dev/null +++ b/tests/avro/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(avro, test_variant) { + const Shapes r = Rectangle{.height = 10, .width = 5}; + + write_and_read(r); +} +} // namespace test_variant diff --git a/tests/avro/test_wstring.cpp b/tests/avro/test_wstring.cpp new file mode 100644 index 00000000..4cdf0b5b --- /dev/null +++ b/tests/avro/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(avro, 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/avro/write_and_read.hpp b/tests/avro/write_and_read.hpp new file mode 100644 index 00000000..20154fa5 --- /dev/null +++ b/tests/avro/write_and_read.hpp @@ -0,0 +1,20 @@ +#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::avro::write(_struct); + const auto res = rfl::avro::read(serialized1); + EXPECT_TRUE(res && true) << "Test failed on read. Error: " + << res.error().value().what(); + const auto serialized2 = rfl::avro::write(res.value()); + EXPECT_EQ(serialized1, serialized2); +} +#endif diff --git a/tests/json/test_json_schema.cpp b/tests/json/test_json_schema.cpp index 2fb8de88..bfbfe3dc 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":[{"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"}}}})"; + 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":{"shape":{"type":"string","enum":["Circle"]},"radius":{"type":"number"}},"required":["shape","radius"]},"test_json_schema__Person":{"type":"object","properties":{"firstName":{"type":"string"},"lastName":{"type":"string"},"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,}$"},"town":{"type":"string"},"color":{"type":"string","enum":["red","green","blue"]},"age":{"allOf":[{"minimum":0,"type":"integer"},{"maximum":130,"type":"integer"}]},"salary":{"type":"number"},"children":{"type":"array","description":"The person's children. Pass an empty array for no children.","items":{"$ref":"#/definitions/test_json_schema__Person"}},"variant":{"anyOf":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/definitions/test_json_schema__Person"}},{"type":"integer"}]},"tuple":{"type":"array","prefixItems":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/definitions/test_json_schema__Person"}},{"type":"integer"}],"items":false},"taggedUnion":{"anyOf":[{"$ref":"#/definitions/test_json_schema__Rectangle__tagged"},{"$ref":"#/definitions/test_json_schema__Square__tagged"},{"$ref":"#/definitions/test_json_schema__Circle__tagged"}]},"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"]}]},"generic":{"$ref":"#/definitions/rfl__Generic"},"with_extra_fields":{"$ref":"#/definitions/test_json_schema__WithExtraFields"}},"required":["firstName","lastName","email","town","color","age","salary","children","variant","tuple","taggedUnion","fieldVariant","generic","with_extra_fields"]},"test_json_schema__Rectangle":{"type":"object","properties":{"width":{"type":"number"},"height":{"type":"number"}},"required":["width","height"]},"test_json_schema__Rectangle__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Rectangle"]},"width":{"type":"number"},"height":{"type":"number"}},"required":["shape","width","height"]},"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_json_schema2.cpp b/tests/json/test_json_schema2.cpp index b9dd3a9a..3ab3a927 100644 --- a/tests/json/test_json_schema2.cpp +++ b/tests/json/test_json_schema2.cpp @@ -63,7 +63,7 @@ TEST(json, test_json_schema2) { rfl::json::to_schema(); const std::string expected = - R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/definitions/test_json_schema2__Person","description":"JSON schema that describes the required attributes for the person class.","definitions":{"test_json_schema2__Circle":{"type":"object","properties":{"radius":{"type":"number"}},"required":["radius"]},"test_json_schema2__Circle__tagged":{"type":"object","properties":{"radius":{"type":"number"},"shape":{"type":"string","enum":["Circle"]}},"required":["radius","shape"]},"test_json_schema2__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_schema2__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_schema2__Rectangle"}},"required":["rectangle"]},{"type":"object","properties":{"square":{"$ref":"#/definitions/test_json_schema2__Square"}},"required":["square"]},{"type":"object","properties":{"circle":{"$ref":"#/definitions/test_json_schema2__Circle"}},"required":["circle"]}]},"firstName":{"type":"string"},"lastName":{"type":"string"},"salary":{"type":"number"},"taggedUnion":{"anyOf":[{"$ref":"#/definitions/test_json_schema2__Rectangle__tagged"},{"$ref":"#/definitions/test_json_schema2__Square__tagged"},{"$ref":"#/definitions/test_json_schema2__Circle__tagged"}]},"town":{"type":"string"},"tuple":{"type":"array","prefixItems":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/definitions/test_json_schema2__Person"}},{"type":"integer"}],"items":false},"variant":{"anyOf":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/definitions/test_json_schema2__Person"}},{"type":"integer"}]}},"required":["age","children","color","email","fieldVariant","firstName","lastName","salary","taggedUnion","town","tuple","variant"]},"test_json_schema2__Rectangle":{"type":"object","properties":{"height":{"type":"number"},"width":{"type":"number"}},"required":["height","width"]},"test_json_schema2__Rectangle__tagged":{"type":"object","properties":{"height":{"type":"number"},"shape":{"type":"string","enum":["Rectangle"]},"width":{"type":"number"}},"required":["height","shape","width"]},"test_json_schema2__Square":{"type":"object","properties":{"width":{"type":"number"}},"required":["width"]},"test_json_schema2__Square__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Square"]},"width":{"type":"number"}},"required":["shape","width"]}}})"; + R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/definitions/test_json_schema2__Person","description":"JSON schema that describes the required attributes for the person class.","definitions":{"test_json_schema2__Circle":{"type":"object","properties":{"radius":{"type":"number"}},"required":["radius"]},"test_json_schema2__Circle__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Circle"]},"radius":{"type":"number"}},"required":["shape","radius"]},"test_json_schema2__Person":{"type":"object","properties":{"firstName":{"type":"string"},"lastName":{"type":"string"},"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,}$"},"town":{"type":"string"},"color":{"type":"string","enum":["red","green","blue"]},"age":{"allOf":[{"minimum":0,"type":"integer"},{"maximum":130,"type":"integer"}]},"salary":{"type":"number"},"children":{"type":"array","description":"The person's children. Pass an empty array for no children.","items":{"$ref":"#/definitions/test_json_schema2__Person"}},"variant":{"anyOf":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/definitions/test_json_schema2__Person"}},{"type":"integer"}]},"tuple":{"type":"array","prefixItems":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/definitions/test_json_schema2__Person"}},{"type":"integer"}],"items":false},"taggedUnion":{"anyOf":[{"$ref":"#/definitions/test_json_schema2__Rectangle__tagged"},{"$ref":"#/definitions/test_json_schema2__Square__tagged"},{"$ref":"#/definitions/test_json_schema2__Circle__tagged"}]},"fieldVariant":{"anyOf":[{"type":"object","properties":{"rectangle":{"$ref":"#/definitions/test_json_schema2__Rectangle"}},"required":["rectangle"]},{"type":"object","properties":{"square":{"$ref":"#/definitions/test_json_schema2__Square"}},"required":["square"]},{"type":"object","properties":{"circle":{"$ref":"#/definitions/test_json_schema2__Circle"}},"required":["circle"]}]}},"required":["firstName","lastName","email","town","color","age","salary","children","variant","tuple","taggedUnion","fieldVariant"]},"test_json_schema2__Rectangle":{"type":"object","properties":{"width":{"type":"number"},"height":{"type":"number"}},"required":["width","height"]},"test_json_schema2__Rectangle__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Rectangle"]},"width":{"type":"number"},"height":{"type":"number"}},"required":["shape","width","height"]},"test_json_schema2__Square":{"type":"object","properties":{"width":{"type":"number"}},"required":["width"]},"test_json_schema2__Square__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Square"]},"width":{"type":"number"}},"required":["shape","width"]}}})"; EXPECT_EQ(json_schema, expected); } diff --git a/vcpkg.json b/vcpkg.json index 4c41c9e2..ceaa1802 100644 --- a/vcpkg.json +++ b/vcpkg.json @@ -3,6 +3,10 @@ "version-string": "0.16.0", "builtin-baseline": "cd124b84feb0c02a24a2d90981e8358fdee0e077", "dependencies": [ + { + "name": "avro-c", + "version>=": "1.11.3" + }, { "name": "ctre", "version>=": "3.8"