diff --git a/.github/workflows/linux.yaml b/.github/workflows/linux.yaml index e36545b7..0098ec5d 100644 --- a/.github/workflows/linux.yaml +++ b/.github/workflows/linux.yaml @@ -53,7 +53,7 @@ jobs: pipx install conan conan profile detect - name: Make sure the library compiles with Conan - run: 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 + run: conan build . --build=missing -s compiler.cppstd=gnu20 -o *:with_capnproto=True -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 - name: Compile run: | if [[ "${{ matrix.compiler }}" == "llvm" ]]; then @@ -66,7 +66,7 @@ jobs: sudo ln -s $(which ccache) /usr/local/bin/$CC sudo ln -s $(which ccache) /usr/local/bin/$CXX $CXX --version - cmake -S . -B build -G Ninja -DREFLECTCPP_BUILD_TESTS=ON -DREFLECTCPP_BUILD_BENCHMARKS=ON -DREFLECTCPP_BSON=ON -DREFLECTCPP_CBOR=ON -DREFLECTCPP_FLEXBUFFERS=ON -DREFLECTCPP_MSGPACK=ON -DREFLECTCPP_TOML=ON -DREFLECTCPP_XML=ON -DREFLECTCPP_YAML=ON -DCMAKE_BUILD_TYPE=Release + cmake -S . -B build -G Ninja -DREFLECTCPP_BUILD_TESTS=ON -DREFLECTCPP_BUILD_BENCHMARKS=ON -DREFLECTCPP_BSON=ON -DREFLECTCPP_CAPNPROTO=ON -DREFLECTCPP_CBOR=ON -DREFLECTCPP_FLEXBUFFERS=ON -DREFLECTCPP_MSGPACK=ON -DREFLECTCPP_TOML=ON -DREFLECTCPP_XML=ON -DREFLECTCPP_YAML=ON -DCMAKE_BUILD_TYPE=Release cmake --build build - name: Run tests run: | diff --git a/.github/workflows/macos-clang.yaml b/.github/workflows/macos-clang.yaml index e12e7028..af073036 100644 --- a/.github/workflows/macos-clang.yaml +++ b/.github/workflows/macos-clang.yaml @@ -44,7 +44,7 @@ jobs: env: CC: clang CXX: clang++ - run: 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 + run: conan build . --build=missing -s compiler.cppstd=gnu20 -o *:with_capnproto=True -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 - name: Compile env: CC: clang @@ -55,7 +55,7 @@ jobs: export CMAKE_GENERATOR=Ninja fi $CXX --version - cmake -S . -B build -DREFLECTCPP_BUILD_TESTS=ON -DREFLECTCPP_BUILD_BENCHMARKS=ON -DREFLECTCPP_BSON=ON -DREFLECTCPP_CBOR=ON -DREFLECTCPP_FLEXBUFFERS=ON -DREFLECTCPP_MSGPACK=ON -DREFLECTCPP_TOML=ON -DREFLECTCPP_XML=ON -DREFLECTCPP_YAML=ON -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ + cmake -S . -B build -DREFLECTCPP_BUILD_TESTS=ON -DREFLECTCPP_BUILD_BENCHMARKS=ON -DREFLECTCPP_BSON=ON -DREFLECTCPP_CAPNPROTO=ON -DREFLECTCPP_CBOR=ON -DREFLECTCPP_FLEXBUFFERS=ON -DREFLECTCPP_MSGPACK=ON -DREFLECTCPP_TOML=ON -DREFLECTCPP_XML=ON -DREFLECTCPP_YAML=ON -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ cmake --build build -j 4 - name: Run tests run: | diff --git a/.github/workflows/windows-msvc.yaml b/.github/workflows/windows-msvc.yaml index 2bf17440..b1406f66 100644 --- a/.github/workflows/windows-msvc.yaml +++ b/.github/workflows/windows-msvc.yaml @@ -24,7 +24,7 @@ jobs: - uses: lukka/run-vcpkg@v11 - name: Compile run: | - cmake -S . -B build -DREFLECTCPP_BUILD_TESTS=ON -DREFLECTCPP_BUILD_BENCHMARKS=ON -DREFLECTCPP_BSON=ON -DREFLECTCPP_CBOR=ON -DREFLECTCPP_FLEXBUFFERS=ON -DREFLECTCPP_MSGPACK=ON -DREFLECTCPP_XML=ON -DREFLECTCPP_TOML=ON -DREFLECTCPP_YAML=ON -DCMAKE_BUILD_TYPE=Release + cmake -S . -B build -DREFLECTCPP_BUILD_TESTS=ON -DREFLECTCPP_BUILD_BENCHMARKS=ON -DREFLECTCPP_BSON=ON -DREFLECTCPP_CAPNPROTO=ON -DREFLECTCPP_CBOR=ON -DREFLECTCPP_FLEXBUFFERS=ON -DREFLECTCPP_MSGPACK=ON -DREFLECTCPP_XML=ON -DREFLECTCPP_TOML=ON -DREFLECTCPP_YAML=ON -DCMAKE_BUILD_TYPE=Release cmake --build build --config Release -j4 - name: Run tests run: | diff --git a/.gitignore b/.gitignore index eb6cda5f..b9205018 100644 --- a/.gitignore +++ b/.gitignore @@ -43,6 +43,7 @@ # Output files *.avro *.bson +*.capnproto *.cbor *.json *.fb diff --git a/CMakeLists.txt b/CMakeLists.txt index 99ce5589..6e1188fd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5,6 +5,7 @@ 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_CAPNPROTO "Enable Cap’n Proto support" OFF) option(REFLECTCPP_CBOR "Enable CBOR support" OFF) option(REFLECTCPP_FLEXBUFFERS "Enable flexbuffers support" OFF) option(REFLECTCPP_MSGPACK "Enable msgpack support" OFF) @@ -24,6 +25,7 @@ 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_CAPNPROTO ON CACHE BOOL "" FORCE) set(REFLECTCPP_CBOR ON CACHE BOOL "" FORCE) set(REFLECTCPP_FLEXBUFFERS ON CACHE BOOL "" FORCE) set(REFLECTCPP_MSGPACK ON CACHE BOOL "" FORCE) @@ -35,7 +37,8 @@ endif() if (REFLECTCPP_BUILD_TESTS OR REFLECTCPP_BUILD_BENCHMARKS 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) + REFLECTCPP_BSON OR REFLECTCPP_CAPNPROTO 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) endif() @@ -130,6 +133,16 @@ if (REFLECTCPP_BSON) target_link_libraries(reflectcpp PUBLIC $,mongo::bson_static,mongo::bson_shared>) endif () +if (REFLECTCPP_CAPNPROTO) + list(APPEND REFLECT_CPP_SOURCES + src/reflectcpp_capnproto.cpp + ) + if (NOT TARGET CapnProto) + find_package(CapnProto CONFIG REQUIRED) + endif () + target_link_libraries(reflectcpp PUBLIC CapnProto::kj CapnProto::capnp CapnProto::capnpc CapnProto::kj-gzip) +endif () + if (REFLECTCPP_CBOR) list(APPEND REFLECT_CPP_SOURCES src/reflectcpp_cbor.cpp diff --git a/README.md b/README.md index 0223d5aa..4359c06d 100644 --- a/README.md +++ b/README.md @@ -65,6 +65,7 @@ The following table lists the serialization formats currently supported by refle | 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 | +| Cap'n Proto | [capnproto](https://capnproto.org) | >= 1.0.2 | MIT | Schemaful 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 | | msgpack | [msgpack-c](https://github.com/msgpack/msgpack-c) | >= 6.0.0 | BSL 1.0 | JSON-like binary format | @@ -512,7 +513,7 @@ In addition, it supports the following custom containers: - `rfl::Binary`: Used to express numbers in binary format. - `rfl::Box`: Similar to `std::unique_ptr`, but (almost) guaranteed to never be null. -- `rfl::Bytestring`: An alias for `std::basic_string`. Supported by BSON, CBOR, flexbuffers, msgpack and UBJSON. +- `rfl::Bytestring`: An alias for `std::basic_string`. Supported by Avro, BSON, Cap'n Proto, CBOR, flexbuffers, msgpack and UBJSON. - `rfl::Generic`: A catch-all type that can represent (almost) anything. - `rfl::Hex`: Used to express numbers in hex format. - `rfl::Literal`: An explicitly enumerated string. diff --git a/benchmarks/all/canada_read.cpp b/benchmarks/all/canada_read.cpp index 21574752..fd803dbf 100644 --- a/benchmarks/all/canada_read.cpp +++ b/benchmarks/all/canada_read.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -71,6 +72,18 @@ static void BM_canada_read_reflect_cpp_bson(benchmark::State &state) { } BENCHMARK(BM_canada_read_reflect_cpp_bson); +static void BM_canada_read_reflect_cpp_capnproto(benchmark::State &state) { + const auto schema = rfl::capnproto::to_schema(); + const auto data = rfl::capnproto::write(load_data(), schema); + for (auto _ : state) { + const auto res = rfl::capnproto::read(data, schema); + if (!res) { + std::cout << res.error()->what() << std::endl; + } + } +} +BENCHMARK(BM_canada_read_reflect_cpp_capnproto); + static void BM_canada_read_reflect_cpp_cbor(benchmark::State &state) { const auto data = rfl::cbor::write(load_data()); for (auto _ : state) { diff --git a/benchmarks/all/canada_write.cpp b/benchmarks/all/canada_write.cpp index 88c37282..cdb0beae 100644 --- a/benchmarks/all/canada_write.cpp +++ b/benchmarks/all/canada_write.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -71,6 +72,18 @@ static void BM_canada_write_reflect_cpp_bson(benchmark::State &state) { } BENCHMARK(BM_canada_write_reflect_cpp_bson); +static void BM_canada_write_reflect_cpp_capnproto(benchmark::State &state) { + const auto schema = rfl::capnproto::to_schema(); + const auto data = load_data(); + for (auto _ : state) { + const auto output = rfl::capnproto::write(data, schema); + if (output.size() == 0) { + std::cout << "No output" << std::endl; + } + } +} +BENCHMARK(BM_canada_write_reflect_cpp_capnproto); + static void BM_canada_write_reflect_cpp_cbor(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 7b53cd56..a04e8af1 100644 --- a/benchmarks/all/licenses_read.cpp +++ b/benchmarks/all/licenses_read.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -87,6 +88,18 @@ static void BM_licenses_read_reflect_cpp_bson(benchmark::State &state) { } BENCHMARK(BM_licenses_read_reflect_cpp_bson); +static void BM_licenses_read_reflect_cpp_capnproto(benchmark::State &state) { + const auto schema = rfl::capnproto::to_schema(); + const auto data = rfl::capnproto::write(load_data(), schema); + for (auto _ : state) { + const auto res = rfl::capnproto::read(data, schema); + if (!res) { + std::cout << res.error()->what() << std::endl; + } + } +} +BENCHMARK(BM_licenses_read_reflect_cpp_capnproto); + static void BM_licenses_read_reflect_cpp_cbor(benchmark::State &state) { const auto data = rfl::cbor::write(load_data()); for (auto _ : state) { diff --git a/benchmarks/all/licenses_write.cpp b/benchmarks/all/licenses_write.cpp index ba68d917..ee9fe84c 100644 --- a/benchmarks/all/licenses_write.cpp +++ b/benchmarks/all/licenses_write.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -87,6 +88,18 @@ static void BM_licenses_write_reflect_cpp_bson(benchmark::State &state) { } BENCHMARK(BM_licenses_write_reflect_cpp_bson); +static void BM_licenses_write_reflect_cpp_capnproto(benchmark::State &state) { + const auto schema = rfl::capnproto::to_schema(); + const auto data = load_data(); + for (auto _ : state) { + const auto output = rfl::capnproto::write(data, schema); + if (output.size() == 0) { + std::cout << "No output" << std::endl; + } + } +} +BENCHMARK(BM_licenses_write_reflect_cpp_capnproto); + static void BM_licenses_write_reflect_cpp_cbor(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 0fae1193..64114840 100644 --- a/benchmarks/all/person_read.cpp +++ b/benchmarks/all/person_read.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -66,6 +67,18 @@ static void BM_person_read_reflect_cpp_bson(benchmark::State &state) { } BENCHMARK(BM_person_read_reflect_cpp_bson); +static void BM_person_read_reflect_cpp_capnproto(benchmark::State &state) { + const auto schema = rfl::capnproto::to_schema(); + const auto data = rfl::capnproto::write(load_data(), schema); + for (auto _ : state) { + const auto res = rfl::capnproto::read(data, schema); + if (!res) { + std::cout << res.error()->what() << std::endl; + } + } +} +BENCHMARK(BM_person_read_reflect_cpp_capnproto); + static void BM_person_read_reflect_cpp_cbor(benchmark::State &state) { const auto data = rfl::cbor::write(load_data()); for (auto _ : state) { diff --git a/benchmarks/all/person_write.cpp b/benchmarks/all/person_write.cpp index fdf6f95b..0f5e13fe 100644 --- a/benchmarks/all/person_write.cpp +++ b/benchmarks/all/person_write.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -67,6 +68,18 @@ static void BM_person_write_reflect_cpp_bson(benchmark::State &state) { } BENCHMARK(BM_person_write_reflect_cpp_bson); +static void BM_person_write_reflect_cpp_capnproto(benchmark::State &state) { + const auto schema = rfl::capnproto::to_schema(); + const auto data = load_data(); + for (auto _ : state) { + const auto output = rfl::capnproto::write(data, schema); + if (output.size() == 0) { + std::cout << "No output" << std::endl; + } + } +} +BENCHMARK(BM_person_write_reflect_cpp_capnproto); + static void BM_person_write_reflect_cpp_cbor(benchmark::State &state) { const auto data = load_data(); for (auto _ : state) { diff --git a/conanfile.py b/conanfile.py index 8b3272e8..dde33e86 100644 --- a/conanfile.py +++ b/conanfile.py @@ -23,6 +23,7 @@ class ReflectCppConan(ConanFile): "reflection", "serialization", "memory", + "Cap'n Proto", "cbor", "flatbuffers", "json", @@ -37,6 +38,7 @@ class ReflectCppConan(ConanFile): options = { "shared": [True, False], "fPIC": [True, False], + "with_capnproto": [True, False], "with_cbor": [True, False], "with_flatbuffers": [True, False], "with_msgpack": [True, False], @@ -48,6 +50,7 @@ class ReflectCppConan(ConanFile): default_options = { "shared": False, "fPIC": True, + "with_capnproto": False, "with_cbor": False, "with_flatbuffers": False, "with_msgpack": False, @@ -68,6 +71,8 @@ class ReflectCppConan(ConanFile): def requirements(self): self.requires("ctre/3.9.0", transitive_headers=True) self.requires("yyjson/0.10.0", transitive_headers=True) + if self.options.with_capnproto: + self.requires("capnproto/1.1.0", transitive_headers=True) if self.options.with_cbor: self.requires("tinycbor/0.6.0", transitive_headers=True) if self.options.with_flatbuffers: @@ -105,6 +110,7 @@ class ReflectCppConan(ConanFile): tc.cache_variables["REFLECTCPP_BUILD_SHARED"] = self.options.shared tc.cache_variables["REFLECTCPP_USE_BUNDLED_DEPENDENCIES"] = False tc.cache_variables["REFLECTCPP_USE_VCPKG"] = False + tc.cache_variables["REFLECTCPP_CAPNPROTO"] = self.options.with_capnproto tc.cache_variables["REFLECTCPP_CBOR"] = self.options.with_cbor tc.cache_variables["REFLECTCPP_FLEXBUFFERS"] = self.options.with_flatbuffers tc.cache_variables["REFLECTCPP_MSGPACK"] = self.options.with_msgpack diff --git a/docs/supported_formats/avro.md b/docs/supported_formats/avro.md index 4ceeeff0..65a92a9b 100644 --- a/docs/supported_formats/avro.md +++ b/docs/supported_formats/avro.md @@ -36,7 +36,7 @@ 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, +But if you are repeatedly serializing or deserializing the same struct, it is more efficient to generate the schema explicitly: ```cpp diff --git a/docs/supported_formats/capnproto.md b/docs/supported_formats/capnproto.md new file mode 100644 index 00000000..9e7e962e --- /dev/null +++ b/docs/supported_formats/capnproto.md @@ -0,0 +1,141 @@ +# Cap'n Proto + +For Cap'n Proto support, you must also include the header `` and link to the capnproto library (https://capnproto.org). +Furthermore, when compiling reflect-cpp, you need to pass `-DREFLECTCPP_CAPNPROTO=ON` to cmake. If you are using vcpkg or Conan, there +should be an appropriate feature (vcpkg) or options that will abstract this away for you. + +Cap'n Proto 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::capnproto::write(person); +``` + +You can parse bytes like this: + +```cpp +const rfl::Result result = rfl::capnproto::read(bytes); +``` + +## The schema + +However, Cap'n Proto 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. + +If you want to, you can pass the schema explicitly, but it will not +yield any performance gains, because the schemata are always created +upfront: + +```cpp +const auto schema = rfl::capnproto::to_schema(); + +const auto person = Person{...}; +const std::vector bytes = rfl::capnproto::write(person, schema); + +const rfl::Result result = rfl::capnproto::read(bytes, schema); +``` + +Cap'n Proto schemas are created using a schema language. You can +retrieve the schema like this: + +```cpp +schema.str(); +``` + +In this case, the resulting schema representation looks like this: + +``` +@0xdbb9ad1f14bf0b36; + +struct Person { + firstName @0 :Text; + lastName @1 :Text; + birthday @2 :Text; + children @3 :List(Person); +} +``` + +## Loading and saving + +You can also load and save to disc using a very similar syntax: + +```cpp +const rfl::Result result = rfl::capnproto::load("/path/to/file.capnproto"); + +const auto person = Person{...}; +rfl::capnproto::save("/path/to/file.capnproto", 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::capnproto::read(my_istream); + +const auto person = Person{...}; +rfl::capnproto::write(person, my_ostream); +``` + +Note that `std::cout` is also an ostream, so this works as well: + +```cpp +rfl::capnproto::write(person, std::cout) << std::endl; +``` + +(Since Cap'n Proto 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 Cap'n Proto format, these must be a static function on your struct or class called +`from_capnproto` that take a `rfl::capnproto::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::capnproto::Reader::InputVarType; + static rfl::Result from_capnproto(const InputVarType& _obj); +}; +``` + +And in your source file, you implement `from_capnproto` as follows: + +```cpp +rfl::Result Person::from_capnproto(const InputVarType& _obj) { + const auto from_nt = [](auto&& _nt) { + return rfl::from_named_tuple(std::move(_nt)); + }; + return rfl::capnproto::read>(_obj) + .transform(from_nt); +} +``` + +This will force the compiler to only compile the Cap'n Proto parsing when the source file is compiled. diff --git a/include/rfl/avro/read.hpp b/include/rfl/avro/read.hpp index c3964e75..7b343664 100644 --- a/include/rfl/avro/read.hpp +++ b/include/rfl/avro/read.hpp @@ -48,14 +48,14 @@ Result> read( /// Parses an object from AVRO using reflection. template -auto read(const char* _bytes, const size_t _size) noexcept { +auto read(const char* _bytes, const size_t _size) { 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) { +auto read(const std::vector& _bytes, const Schema& _schema) noexcept { return read(_bytes.data(), _bytes.size(), _schema); } diff --git a/include/rfl/avro/write.hpp b/include/rfl/avro/write.hpp index 7440238b..2ae7dfab 100644 --- a/include/rfl/avro/write.hpp +++ b/include/rfl/avro/write.hpp @@ -44,7 +44,7 @@ std::vector write(const auto& _obj, const auto& _schema) noexcept { /// Returns AVRO bytes. template -std::vector write(const auto& _obj) noexcept { +std::vector write(const auto& _obj) { using T = std::remove_cvref_t; const auto schema = to_schema(); return write(_obj, schema); @@ -52,7 +52,7 @@ std::vector write(const auto& _obj) noexcept { /// Writes a AVRO into an ostream. template -std::ostream& write(const auto& _obj, std::ostream& _stream) noexcept { +std::ostream& write(const auto& _obj, std::ostream& _stream) { auto buffer = write(_obj); _stream.write(buffer.data(), buffer.size()); return _stream; diff --git a/include/rfl/capnproto.hpp b/include/rfl/capnproto.hpp new file mode 100644 index 00000000..6895378e --- /dev/null +++ b/include/rfl/capnproto.hpp @@ -0,0 +1,15 @@ +#ifndef RFL_CAPNPROTO_HPP_ +#define RFL_CAPNPROTO_HPP_ + +#include "../rfl.hpp" +#include "capnproto/Parser.hpp" +#include "capnproto/Reader.hpp" +#include "capnproto/Schema.hpp" +#include "capnproto/Writer.hpp" +#include "capnproto/load.hpp" +#include "capnproto/read.hpp" +#include "capnproto/save.hpp" +#include "capnproto/to_schema.hpp" +#include "capnproto/write.hpp" + +#endif diff --git a/include/rfl/capnproto/Parser.hpp b/include/rfl/capnproto/Parser.hpp new file mode 100644 index 00000000..0112095b --- /dev/null +++ b/include/rfl/capnproto/Parser.hpp @@ -0,0 +1,122 @@ +#ifndef RFL_CAPNPROTO_PARSER_HPP_ +#define RFL_CAPNPROTO_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 { + +/// Cap'n proto 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< + capnproto::Reader, capnproto::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 capnproto::Reader&, const T&) noexcept { + static_assert(always_false_v, + "Generics are unsupported in Cap'n Proto."); + return Error("Unsupported"); + } + + template + static void write(const capnproto::Writer&, const Generic&, + const P&) noexcept { + static_assert(always_false_v

, + "Generics are unsupported in Cap'n Proto."); + } + + template + static schema::Type to_schema(T*) { + static_assert(always_false_v, + "Generics are unsupported in Cap'n Proto."); + return schema::Type{}; + } +}; + +template + requires AreReaderAndWriter< + capnproto::Reader, capnproto::Writer, + internal::Skip> +struct Parser, + ProcessorsType> { + using R = capnproto::Reader; + using W = capnproto::Writer; + + template + static Result> + read(const R&, const U&) noexcept { + static_assert(always_false_v, + "rfl::Skip is unsupported in Cap'n Proto."); + 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 Cap'n Proto."); + } + + template + static schema::Type to_schema(U* _definitions) { + static_assert(always_false_v, + "rfl::Skip is unsupported in Cap'n Proto."); + return schema::Type{}; + } +}; + +} // namespace parsing +} // namespace rfl + +namespace rfl { +namespace capnproto { + +template +using Parser = parsing::Parser; + +} +} // namespace rfl + +#endif diff --git a/include/rfl/capnproto/Reader.hpp b/include/rfl/capnproto/Reader.hpp new file mode 100644 index 00000000..d8d10971 --- /dev/null +++ b/include/rfl/capnproto/Reader.hpp @@ -0,0 +1,184 @@ +#ifndef RFL_CAPNPROTO_READER_HPP_ +#define RFL_CAPNPROTO_READER_HPP_ + +#include + +#include +#include +#include +#include +#include +#include + +#include "../Bytestring.hpp" +#include "../Result.hpp" +#include "../always_false.hpp" +#include "../internal/is_literal.hpp" +#include "../internal/ptr_cast.hpp" + +namespace rfl::capnproto { + +class Reader { + public: + struct CapNProtoInputArray { + capnp::DynamicList::Reader val_; + }; + + struct CapNProtoInputMap { + capnp::DynamicStruct::Reader val_; + }; + + struct CapNProtoInputObject { + capnp::DynamicStruct::Reader val_; + }; + + struct CapNProtoInputUnion { + capnp::DynamicStruct::Reader val_; + }; + + struct CapNProtoInputVar { + capnp::DynamicValue::Reader val_; + }; + + using InputArrayType = CapNProtoInputArray; + using InputObjectType = CapNProtoInputObject; + using InputMapType = CapNProtoInputMap; + using InputUnionType = CapNProtoInputUnion; + using InputVarType = CapNProtoInputVar; + + template + static constexpr bool has_custom_constructor = + (requires(InputVarType var) { T::from_capnproto_obj(var); }); + + bool is_empty(const InputVarType& _var) const noexcept; + + template + rfl::Result to_basic_type(const InputVarType& _var) const noexcept { + const auto type = _var.val_.getType(); + if constexpr (std::is_same, std::string>()) { + if (type != capnp::DynamicValue::TEXT) { + return Error("Could not cast to string."); + } + return std::string(_var.val_.as().cStr()); + + } else if constexpr (std::is_same, + rfl::Bytestring>()) { + if (type != capnp::DynamicValue::DATA) { + return Error("Could not cast to bytestring."); + } + const auto data = _var.val_.as(); + return rfl::Bytestring(internal::ptr_cast(data.begin()), + data.size()); + + } else if constexpr (std::is_same, bool>()) { + if (type != capnp::DynamicValue::BOOL) { + return rfl::Error("Could not cast to boolean."); + } + return _var.val_.as(); + + } else if constexpr (std::is_floating_point>() || + std::is_integral>()) { + switch (type) { + case capnp::DynamicValue::INT: + return static_cast(_var.val_.as()); + + case capnp::DynamicValue::UINT: + return static_cast(_var.val_.as()); + + case capnp::DynamicValue::FLOAT: + return static_cast(_var.val_.as()); + + default: + return rfl::Error( + "Could not cast to numeric value. The type must be integral, " + "float or double."); + } + + } else if constexpr (internal::is_literal_v) { + if (type != capnp::DynamicValue::ENUM) { + return rfl::Error("Could not cast to an enum."); + } + return T::from_value(_var.val_.as().getRaw()); + + } 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 { + for (auto element : _arr.val_) { + const auto err = _array_reader.read(InputVarType{std::move(element)}); + if (err) { + return err; + } + } + return std::nullopt; + } + + template + std::optional read_map(const MapReader& _map_reader, + const InputMapType& _map) const noexcept { + try { + const auto entries = _map.val_.get("entries").as(); + for (auto entry : entries) { + auto s = entry.template as(); + const char* key = s.get("key").as().cStr(); + _map_reader.read(std::string_view(key), InputVarType{s.get("value")}); + } + return std::nullopt; + } catch (std::exception& e) { + return Error{e.what()}; + } + } + + template + std::optional read_object(const ObjectReader& _object_reader, + const InputObjectType& _obj) const noexcept { + int i = 0; + for (auto field : _obj.val_.getSchema().getFields()) { + _object_reader.read(i++, InputVarType{_obj.val_.get(field)}); + } + return std::nullopt; + } + + template + rfl::Result read_union( + const InputUnionType& _union) const noexcept { + const auto opt_pair = identify_discriminant(_union); + if (!opt_pair) { + return Error("Could not get the discriminant."); + } + const auto& [field, disc] = *opt_pair; + return UnionReaderType::read(*this, disc, + InputVarType{_union.val_.get(field)}); + } + + template + rfl::Result use_custom_constructor( + const InputVarType& _var) const noexcept { + try { + return T::from_capnproto_obj(_var); + } catch (std::exception& e) { + return rfl::Error(e.what()); + } + } + + private: + std::optional> + identify_discriminant(const InputUnionType& _union) const noexcept; +}; + +} // namespace rfl::capnproto + +#endif diff --git a/include/rfl/capnproto/Schema.hpp b/include/rfl/capnproto/Schema.hpp new file mode 100644 index 00000000..2c4e8893 --- /dev/null +++ b/include/rfl/capnproto/Schema.hpp @@ -0,0 +1,41 @@ +#ifndef RFL_CAPNPROTO_SCHEMA_HPP_ +#define RFL_CAPNPROTO_SCHEMA_HPP_ + +#include + +#include + +#include "../Ref.hpp" +#include "SchemaImpl.hpp" + +namespace rfl::capnproto { + +template +class Schema { + public: + using Type = std::remove_cvref_t; + + Schema(const std::string& _str) : impl_(Ref::make(_str)) {} + + static Result> from_string(const std::string& _str) noexcept { + try { + return Schema(_str); + } catch (std::exception& e) { + return Error(e.what()); + } + } + + /// The string used to create this schema. + const std::string& str() const { return impl_->str(); } + + /// The struct schema used to generate new values. + const capnp::ParsedSchema& value() const { return impl_->value(); }; + + private: + /// We are using the "pimpl"-pattern + Ref impl_; +}; + +} // namespace rfl::capnproto + +#endif diff --git a/include/rfl/capnproto/SchemaImpl.hpp b/include/rfl/capnproto/SchemaImpl.hpp new file mode 100644 index 00000000..b9142a77 --- /dev/null +++ b/include/rfl/capnproto/SchemaImpl.hpp @@ -0,0 +1,43 @@ +#ifndef RFL_CAPNPROTO_SCHEMAIMPL_HPP_ +#define RFL_CAPNPROTO_SCHEMAIMPL_HPP_ + +#include + +#include +#include + +#include "../Result.hpp" + +namespace rfl::capnproto { + +class SchemaImpl { + public: + SchemaImpl(const std::string& _str); + + ~SchemaImpl() = default; + + /// The JSON string used to create this schema. + const std::string& str() const { return str_; } + + /// The interface used to create new values. + const capnp::ParsedSchema& value() const { return *schema_; }; + + private: + static capnp::ParsedSchema make_schema(const std::string& _str, + capnp::SchemaParser* _parser); + + private: + /// The string used to create the schema. + std::string str_; + + /// The schema parser - we need to hold onto this during the lifetime of the + /// schema. + Box schema_parser_; + + /// The actual schema + Box schema_; +}; + +} // namespace rfl::capnproto + +#endif diff --git a/include/rfl/capnproto/Writer.hpp b/include/rfl/capnproto/Writer.hpp new file mode 100644 index 00000000..32c2e58a --- /dev/null +++ b/include/rfl/capnproto/Writer.hpp @@ -0,0 +1,273 @@ +#ifndef RFL_CAPNPROTO_WRITER_HPP_ +#define RFL_CAPNPROTO_WRITER_HPP_ + +#include +#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" +#include "../internal/ptr_cast.hpp" + +namespace rfl::capnproto { + +class Writer { + public: + struct CapnProtoOutputArray { + capnp::DynamicList::Builder val_; + size_t ix_ = 0; + }; + + struct CapnProtoOutputMap { + capnp::DynamicStruct::Builder val_; + size_t ix_ = 0; + }; + + struct CapnProtoOutputObject { + capnp::DynamicStruct::Builder val_; + }; + + struct CapnProtoOutputUnion { + capnp::DynamicStruct::Builder val_; + }; + + struct CapnProtoOutputVar { + capnp::DynamicValue::Builder val_; + }; + + using OutputArrayType = CapnProtoOutputArray; + using OutputMapType = CapnProtoOutputMap; + using OutputObjectType = CapnProtoOutputObject; + using OutputUnionType = CapnProtoOutputUnion; + using OutputVarType = CapnProtoOutputVar; + + Writer(capnp::DynamicStruct::Builder* _root); + + ~Writer(); + + template + OutputArrayType array_as_root(const T _size) const noexcept { + static_assert(always_false_v, + "In Cap'n Proto, root values must always be structs."); + throw std::runtime_error("Unsupported."); + } + + template + OutputMapType map_as_root(const T _size) const noexcept { + static_assert(always_false_v, + "In Cap'n Proto, root values must always be structs."); + throw std::runtime_error("Unsupported."); + } + + Writer::OutputObjectType object_as_root(const size_t _size) const noexcept; + + template + OutputVarType null_as_root() const noexcept { + static_assert(always_false_v, + "In Cap'n Proto, root values must always be structs."); + throw std::runtime_error("Unsupported."); + } + + template + OutputUnionType union_as_root() const noexcept { + static_assert(always_false_v, + "In Cap'n Proto, root values must always be structs."); + throw std::runtime_error("Unsupported."); + } + + template + OutputVarType value_as_root(const T& _var) const noexcept { + static_assert(always_false_v, + "In Cap'n Proto, root values must always be structs."); + throw std::runtime_error("Unsupported."); + } + + 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 { + if constexpr (std::is_same, std::string>()) { + _parent->val_.set(_parent->ix_++, _var.c_str()); + + } else if constexpr (std::is_same, + rfl::Bytestring>()) { + const auto array_ptr = kj::ArrayPtr( + internal::ptr_cast(_var.data()), _var.size()); + _parent->val_.set(_parent->ix_++, capnp::Data::Reader(array_ptr)); + + } else if constexpr (std::is_floating_point>() || + std::is_same, bool>()) { + _parent->val_.set(_parent->ix_++, _var); + + } else if constexpr (std::is_integral>()) { + _parent->val_.set(_parent->ix_++, static_cast(_var)); + + } else if constexpr (internal::is_literal_v) { + return add_value_to_array(_var.value(), _parent); + + } else { + static_assert(rfl::always_false_v, "Unsupported type."); + } + return OutputVarType{}; + } + + template + OutputVarType add_value_to_map(const std::string_view& _name, const T& _var, + OutputMapType* _parent) const noexcept { + auto entries = + OutputArrayType{_parent->val_.get("entries").as()}; + auto new_entry = add_object_to_array(2, &entries); + add_value_to_object("key", std::string(_name), &new_entry); + return add_value_to_object("value", _var, &new_entry); + } + + template + OutputVarType add_value_to_object(const std::string_view& _name, + const T& _var, + OutputObjectType* _parent) const noexcept { + if constexpr (std::is_same, std::string>()) { + _parent->val_.set(_name.data(), _var.c_str()); + + } else if constexpr (std::is_same, + rfl::Bytestring>()) { + const auto array_ptr = kj::ArrayPtr( + internal::ptr_cast(_var.data()), _var.size()); + _parent->val_.set(_name.data(), capnp::Data::Reader(array_ptr)); + + } else if constexpr (std::is_floating_point>() || + std::is_same, bool>()) { + _parent->val_.set(_name.data(), _var); + + } else if constexpr (std::is_integral>()) { + _parent->val_.set(_name.data(), static_cast(_var)); + + } else if constexpr (internal::is_literal_v) { + return add_value_to_object(_name, _var.value(), _parent); + + } else { + static_assert(rfl::always_false_v, "Unsupported type."); + } + return OutputVarType{}; + } + + template + OutputVarType add_value_to_union(const size_t _index, const T& _var, + OutputUnionType* _parent) const noexcept { + const auto field = _parent->val_.getSchema().getFields()[_index]; + + if constexpr (std::is_same, std::string>()) { + _parent->val_.set(field, _var.c_str()); + + } else if constexpr (std::is_same, + rfl::Bytestring>()) { + const auto array_ptr = kj::ArrayPtr( + internal::ptr_cast(_var.data()), _var.size()); + _parent->val_.set(field, capnp::Data::Reader(array_ptr)); + + } else if constexpr (std::is_floating_point>() || + std::is_same, bool>()) { + _parent->val_.set(field, _var); + + } else if constexpr (std::is_integral>()) { + _parent->val_.set(field, static_cast(_var)); + + } else if constexpr (internal::is_literal_v) { + return add_value_to_union(_index, _var.value(), _parent); + + } else { + static_assert(rfl::always_false_v, "Unsupported type."); + } + return OutputVarType{}; + } + + void end_array(OutputArrayType* _arr) const noexcept {} + + void end_map(OutputMapType* _obj) const noexcept {} + + void end_object(OutputObjectType* _obj) const noexcept {} + + private: + capnp::DynamicStruct::Builder* root_; +}; + +} // namespace rfl::capnproto + +#endif diff --git a/include/rfl/capnproto/get_root_name.hpp b/include/rfl/capnproto/get_root_name.hpp new file mode 100644 index 00000000..729f4979 --- /dev/null +++ b/include/rfl/capnproto/get_root_name.hpp @@ -0,0 +1,29 @@ +#ifndef RFL_CAPNPROTO_GET_ROOT_NAME_HPP_ +#define RFL_CAPNPROTO_GET_ROOT_NAME_HPP_ + +#include + +#include "../Processors.hpp" +#include "../internal/has_custom_parser.hpp" +#include "../internal/has_reflection_type_v.hpp" +#include "../parsing/make_type_name.hpp" +#include "Parser.hpp" + +namespace rfl::capnproto { + +template +inline std::string get_root_name() { + if constexpr (internal::has_reflection_type_v) { + return get_root_name>(); + } else if constexpr (internal::has_custom_parser>) { + return get_root_name< + typename Parser>::CustomParserHelperStruct>(); + } else { + return internal::strings::to_pascal_case(parsing::make_type_name()); + } +} + +} // namespace rfl::capnproto + +#endif diff --git a/include/rfl/capnproto/is_named_type.hpp b/include/rfl/capnproto/is_named_type.hpp new file mode 100644 index 00000000..c95377c3 --- /dev/null +++ b/include/rfl/capnproto/is_named_type.hpp @@ -0,0 +1,19 @@ +#ifndef RFL_CAPNPROTO_IS_NAMED_TYPE_HPP_ +#define RFL_CAPNPROTO_IS_NAMED_TYPE_HPP_ + +namespace rfl::capnproto { + +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() || + std::is_same() || + std::is_same(); + }); +} + +} // namespace rfl::capnproto + +#endif + diff --git a/include/rfl/capnproto/load.hpp b/include/rfl/capnproto/load.hpp new file mode 100644 index 00000000..e40c0d96 --- /dev/null +++ b/include/rfl/capnproto/load.hpp @@ -0,0 +1,23 @@ +#ifndef RFL_CAPNPROTO_LOAD_HPP_ +#define RFL_CAPNPROTO_LOAD_HPP_ + +#include "../Processors.hpp" +#include "../Result.hpp" +#include "../io/load_bytes.hpp" +#include "read.hpp" + +namespace rfl { +namespace capnproto { + +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 capnproto +} // namespace rfl + +#endif diff --git a/include/rfl/capnproto/read.hpp b/include/rfl/capnproto/read.hpp new file mode 100644 index 00000000..f136505b --- /dev/null +++ b/include/rfl/capnproto/read.hpp @@ -0,0 +1,80 @@ +#ifndef RFL_CAPNPROTO_READ_HPP_ +#define RFL_CAPNPROTO_READ_HPP_ + +#include +#include +#include + +#include +#include +#include +#include + +#include "../Processors.hpp" +#include "../SnakeCaseToCamelCase.hpp" +#include "../internal/strings/strings.hpp" +#include "../internal/wrap_in_rfl_array_t.hpp" +#include "Parser.hpp" +#include "Reader.hpp" +#include "Schema.hpp" +#include "get_root_name.hpp" +#include "to_schema.hpp" + +namespace rfl::capnproto { + +using InputObjectType = typename Reader::InputObjectType; +using InputVarType = typename Reader::InputVarType; + +/// Parses an object from a CAPNPROTO var. +template +auto read(const InputVarType& _obj) { + const auto r = Reader(); + return Parser>::read(r, _obj); +} + +/// Parses an object from CAPNPROTO using reflection. +template +Result> read(const char* _bytes, + const size_t _size, + const Schema& _schema) { + const auto array_ptr = kj::ArrayPtr( + internal::ptr_cast(_bytes), _size); + auto input_stream = kj::ArrayInputStream(array_ptr); + auto message_reader = capnp::PackedMessageReader(input_stream); + const auto root_name = get_root_name, Ps...>(); + const auto root_schema = _schema.value().getNested(root_name.c_str()); + const auto input_var = InputVarType{ + message_reader.getRoot(root_schema.asStruct())}; + return read(input_var); +} + +/// Parses an object from CAPNPROTO using reflection. +template +auto read(const char* _bytes, const size_t _size) { + const auto schema = to_schema, Ps...>(); + return read(_bytes, _size, schema); +} + +/// Parses an object from CAPNPROTO using reflection. +template +auto read(const std::vector& _bytes, const Schema& _schema) noexcept { + return read(_bytes.data(), _bytes.size(), _schema); +} + +/// Parses an object from CAPNPROTO 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::capnproto + +#endif diff --git a/include/rfl/capnproto/save.hpp b/include/rfl/capnproto/save.hpp new file mode 100644 index 00000000..2f4afe0f --- /dev/null +++ b/include/rfl/capnproto/save.hpp @@ -0,0 +1,25 @@ +#ifndef RFL_CAPNPROTO_SAVE_HPP_ +#define RFL_CAPNPROTO_SAVE_HPP_ + +#include +#include +#include + +#include "../Result.hpp" +#include "../io/save_bytes.hpp" +#include "write.hpp" + +namespace rfl::capnproto { + +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::capnproto + +#endif diff --git a/include/rfl/capnproto/schema/CapnProtoTypes.hpp b/include/rfl/capnproto/schema/CapnProtoTypes.hpp new file mode 100644 index 00000000..5a5515f4 --- /dev/null +++ b/include/rfl/capnproto/schema/CapnProtoTypes.hpp @@ -0,0 +1,49 @@ +#ifndef RFL_CAPNPROTO_SCHEMA_CAPNPROTOTYPES_HPP_ +#define RFL_CAPNPROTO_SCHEMA_CAPNPROTOTYPES_HPP_ + +#include + +#include "Type.hpp" + +namespace rfl::capnproto::schema { + +struct CapnProtoTypes { + bool has_maps_ = false; + std::map structs_; + std::map enums_; + std::map tuples_; + std::map unions_; +}; + +const char* MAP_DEFINITION = R"( +struct Map(Value) { + entries @0 :List(Entry); + struct Entry { + key @0 :Text; + value @1 :Value; + } +})"; + +std::ostream& operator<<(std::ostream& _os, + const std::map& _map) { + for (const auto& [name, type] : _map) { + _os << type.with_name(internal::strings::to_pascal_case(name)) << std::endl + << std::endl; + } + return _os; +} + +std::ostream& operator<<(std::ostream& _os, const CapnProtoTypes& _cnp_types) { + // TODO: ID is hardcoded. + _os << "@0xdbb9ad1f14bf0b36;" << std::endl << std::endl; + if (_cnp_types.has_maps_) { + _os << MAP_DEFINITION << std::endl << std::endl; + } + _os << _cnp_types.structs_ << _cnp_types.enums_ << _cnp_types.tuples_ + << _cnp_types.unions_; + return _os; +} + +} // namespace rfl::capnproto::schema + +#endif diff --git a/include/rfl/capnproto/schema/Type.hpp b/include/rfl/capnproto/schema/Type.hpp new file mode 100644 index 00000000..12bf3be6 --- /dev/null +++ b/include/rfl/capnproto/schema/Type.hpp @@ -0,0 +1,88 @@ +#ifndef RFL_CAPNPROTO_SCHEMA_TYPE_HPP_ +#define RFL_CAPNPROTO_SCHEMA_TYPE_HPP_ + +#include +#include +#include +#include +#include + +#include "../../Literal.hpp" +#include "../../Object.hpp" +#include "../../Rename.hpp" +#include "../../Variant.hpp" + +namespace rfl::capnproto::schema { + +struct Type { + struct Void {}; + + struct Bool {}; + + struct Int8 {}; + + struct Int16 {}; + + struct Int32 {}; + + struct Int64 {}; + + struct UInt8 {}; + + struct UInt16 {}; + + struct UInt32 {}; + + struct UInt64 {}; + + struct Float32 {}; + + struct Float64 {}; + + struct Data {}; + + struct Text {}; + + struct Enum { + std::string name; + std::vector fields; + }; + + struct List { + rfl::Ref type; + }; + + struct Map { + rfl::Ref type; + }; + + struct Reference { + std::string type_name; + }; + + struct Struct { + std::string name; + std::vector> fields; + }; + + struct Union { + std::string name; + std::vector> fields; + }; + + using ReflectionType = + rfl::Variant; + + const auto& reflection() const { return value; } + + Type with_name(const std::string& _name) const; + + ReflectionType value; +}; + +std::ostream& operator<<(std::ostream& os, const Type& _t); + +} // namespace rfl::capnproto::schema +#endif diff --git a/include/rfl/capnproto/to_schema.hpp b/include/rfl/capnproto/to_schema.hpp new file mode 100644 index 00000000..24d66448 --- /dev/null +++ b/include/rfl/capnproto/to_schema.hpp @@ -0,0 +1,51 @@ +#ifndef RFL_CAPNPROTO_TOSCHEMA_HPP_ +#define RFL_CAPNPROTO_TOSCHEMA_HPP_ + +#include +#include +#include + +#include "../Literal.hpp" +#include "../Processors.hpp" +#include "../Result.hpp" +#include "../SnakeCaseToCamelCase.hpp" +#include "../Variant.hpp" +#include "../json.hpp" +#include "../parsing/schema/Type.hpp" +#include "../parsing/schema/ValidationType.hpp" +#include "../parsing/schema/make.hpp" +#include "Schema.hpp" +#include "Writer.hpp" +#include "schema/Type.hpp" + +namespace rfl::capnproto { + +std::string to_string_representation( + const parsing::schema::Definition& internal_schema); + +/// This ensures that the schema is only generated once. +template +struct SchemaHolder { + static SchemaHolder make() noexcept { + const auto internal_schema = + parsing::schema::make>(); + const auto str = to_string_representation(internal_schema); + return SchemaHolder{Schema::from_string(str)}; + } + + rfl::Result> schema_; +}; + +template +static const SchemaHolder schema_holder = + SchemaHolder::make(); + +/// Returns the Cap'n Proto schema for a class. +template +Schema to_schema() { + return schema_holder.schema_.value(); +} +} // namespace rfl::capnproto + +#endif diff --git a/include/rfl/capnproto/write.hpp b/include/rfl/capnproto/write.hpp new file mode 100644 index 00000000..3ce04530 --- /dev/null +++ b/include/rfl/capnproto/write.hpp @@ -0,0 +1,72 @@ +#ifndef RFL_CAPNPROTO_WRITE_HPP_ +#define RFL_CAPNPROTO_WRITE_HPP_ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "../SnakeCaseToCamelCase.hpp" +#include "../internal/ptr_cast.hpp" +#include "../internal/strings/strings.hpp" +#include "../parsing/Parent.hpp" +#include "Parser.hpp" +#include "Schema.hpp" +#include "Writer.hpp" +#include "get_root_name.hpp" +#include "to_schema.hpp" + +namespace rfl::capnproto { + +/// Returns CAPNPROTO bytes. +template +std::vector write(const auto& _obj, const auto& _schema) { + 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."); + const auto root_name = get_root_name(); + const auto root_schema = _schema.value().getNested(root_name.c_str()); + capnp::MallocMessageBuilder message_builder; + auto root = + message_builder.initRoot(root_schema.asStruct()); + const auto writer = Writer(&root); + Parser>::write( + writer, _obj, typename ParentType::Root{}); + kj::VectorOutputStream output_stream; + capnp::writePackedMessage(output_stream, message_builder); + auto arr_ptr = output_stream.getArray(); + return std::vector(internal::ptr_cast(arr_ptr.begin()), + internal::ptr_cast(arr_ptr.end())); +} + +/// Returns CAPNPROTO bytes. +template +std::vector write(const auto& _obj) { + using T = std::remove_cvref_t; + const auto schema = to_schema(); + return write(_obj, schema); +} + +/// Writes a CAPNPROTO into an ostream. +template +std::ostream& write(const auto& _obj, std::ostream& _stream) { + auto buffer = write(_obj); + _stream.write(buffer.data(), buffer.size()); + return _stream; +} + +} // namespace rfl::capnproto + +#endif diff --git a/include/rfl/internal/enums/StringConverter.hpp b/include/rfl/internal/enums/StringConverter.hpp index f5ee9a16..4e6a0e7a 100644 --- a/include/rfl/internal/enums/StringConverter.hpp +++ b/include/rfl/internal/enums/StringConverter.hpp @@ -8,8 +8,7 @@ #include #include "../../Result.hpp" -#include "../../internal/strings/join.hpp" -#include "../../internal/strings/split.hpp" +#include "../../internal/strings/strings.hpp" #include "../../type_name_t.hpp" #include "get_enum_names.hpp" #include "is_flag_enum.hpp" diff --git a/include/rfl/internal/has_custom_parser.hpp b/include/rfl/internal/has_custom_parser.hpp new file mode 100644 index 00000000..40b5720d --- /dev/null +++ b/include/rfl/internal/has_custom_parser.hpp @@ -0,0 +1,23 @@ +#ifndef RFL_INTERNAL_HASCUSTOMPARSER_HPP_ +#define RFL_INTERNAL_HASCUSTOMPARSER_HPP_ + +#include + +#include "../parsing/Parser.hpp" + +namespace rfl::internal { + +template +concept has_custom_parser = requires( + const T& _t, const typename parsing::Parser< + R, W, T, ProcessorsType>::CustomParserHelperStruct& _h) { + { + std::remove_cvref_t::from_class(_t) + } -> std::same_as>; + + { _h.to_class() } -> std::same_as; +}; + +} // namespace rfl::internal + +#endif diff --git a/include/rfl/internal/processed_t.hpp b/include/rfl/internal/processed_t.hpp index 69842a59..1e6250c5 100644 --- a/include/rfl/internal/processed_t.hpp +++ b/include/rfl/internal/processed_t.hpp @@ -4,7 +4,8 @@ #include #include "../Processors.hpp" -#include "../named_tuple_t.hpp" +#include "ptr_named_tuple_t.hpp" +#include "remove_ptrs_nt.hpp" namespace rfl::internal { @@ -13,10 +14,11 @@ struct Processed; template struct Processed> { - using NamedTupleType = named_tuple_t; - using type = typename std::invoke_result< - decltype(Processors::template process), - NamedTupleType>::type; + using PtrNamedTupleType = ptr_named_tuple_t; + using type = typename remove_ptrs_nt< + std::invoke_result_t::template process< + StructType, PtrNamedTupleType>), + PtrNamedTupleType>>::NamedTupleType; }; template diff --git a/include/rfl/internal/remove_ptrs_nt.hpp b/include/rfl/internal/remove_ptrs_nt.hpp new file mode 100644 index 00000000..dbd3eff8 --- /dev/null +++ b/include/rfl/internal/remove_ptrs_nt.hpp @@ -0,0 +1,34 @@ +#ifndef RFL_INTERNAL_REMOVE_PTRS_NT_HPP_ +#define RFL_INTERNAL_REMOVE_PTRS_NT_HPP_ + +#include +#include + +#include "../Field.hpp" +#include "StringLiteral.hpp" +#include "wrap_in_rfl_array_t.hpp" + +namespace rfl::internal { + +template +struct remove_ptr; + +template +struct remove_ptr> { + using FieldType = + Field<_name, internal::wrap_in_rfl_array_t< + std::remove_cvref_t>>>; +}; + +template +struct remove_ptrs_nt; + +template +struct remove_ptrs_nt> { + using NamedTupleType = + NamedTuple::FieldType...>; +}; + +} // namespace rfl::internal + +#endif diff --git a/include/rfl/internal/strings/join.hpp b/include/rfl/internal/strings/join.hpp deleted file mode 100644 index c562e773..00000000 --- a/include/rfl/internal/strings/join.hpp +++ /dev/null @@ -1,28 +0,0 @@ -#ifndef RFL_INTERNAL_STRINGS_JOIN_HPP_ -#define RFL_INTERNAL_STRINGS_JOIN_HPP_ - -#include -#include - -namespace rfl { -namespace internal { -namespace strings { - -/// Joins a string using the delimiter -inline std::string join(const std::string& _delimiter, - const std::vector& _strings) { - if (_strings.size() == 0) { - return ""; - } - auto res = _strings[0]; - for (size_t i = 1; i < _strings.size(); ++i) { - res += _delimiter + _strings[i]; - } - return res; -} - -} // namespace strings -} // namespace internal -} // namespace rfl - -#endif diff --git a/include/rfl/internal/strings/replace_all.hpp b/include/rfl/internal/strings/replace_all.hpp deleted file mode 100644 index bd77338c..00000000 --- a/include/rfl/internal/strings/replace_all.hpp +++ /dev/null @@ -1,28 +0,0 @@ -#ifndef RFL_INTERNAL_STRINGS_REPLACE_ALL_HPP_ -#define RFL_INTERNAL_STRINGS_REPLACE_ALL_HPP_ - -#include -#include - -namespace rfl { -namespace internal { -namespace strings { - -inline std::string replace_all(const std::string& _str, - const std::string& _from, - const std::string& _to) { - auto str = _str; - - size_t pos = 0; - while ((pos = str.find(_from, pos)) != std::string::npos) { - str.replace(pos, _from.length(), _to); - pos += _to.length(); - } - return str; -} - -} // namespace strings -} // namespace internal -} // namespace rfl - -#endif diff --git a/include/rfl/internal/strings/split.hpp b/include/rfl/internal/strings/split.hpp deleted file mode 100644 index 6bf29027..00000000 --- a/include/rfl/internal/strings/split.hpp +++ /dev/null @@ -1,29 +0,0 @@ -#ifndef RFL_INTERNAL_STRINGS_SPLIT_HPP_ -#define RFL_INTERNAL_STRINGS_SPLIT_HPP_ - -#include -#include - -namespace rfl { -namespace internal { -namespace strings { - -/// Splits a string alongside the delimiter -inline std::vector split(const std::string& _str, - const std::string& _delimiter) { - auto str = _str; - size_t pos = 0; - std::vector result; - while ((pos = str.find(_delimiter)) != std::string::npos) { - result.emplace_back(str.substr(0, pos)); - str.erase(0, pos + _delimiter.length()); - } - result.emplace_back(std::move(str)); - return result; -} - -} // namespace strings -} // namespace internal -} // namespace rfl - -#endif diff --git a/include/rfl/internal/strings/strings.hpp b/include/rfl/internal/strings/strings.hpp new file mode 100644 index 00000000..6db4118e --- /dev/null +++ b/include/rfl/internal/strings/strings.hpp @@ -0,0 +1,29 @@ +#ifndef RFL_INTERNAL_STRINGS_STRINGS_HPP_ +#define RFL_INTERNAL_STRINGS_STRINGS_HPP_ + +#include +#include + +namespace rfl::internal::strings { + +/// Joins a series of strings. +std::string join(const std::string& _delimiter, + const std::vector& _strings); + +/// Replace all occurences of _from with _to. +std::string replace_all(const std::string& _str, const std::string& _from, + const std::string& _to); + +/// Splits _str along _delimiter. +std::vector split(const std::string& _str, + const std::string& _delimiter); + +/// Transforms the string to camel case. +std::string to_camel_case(const std::string& _str); + +/// Transforms the string to pascal case. +std::string to_pascal_case(const std::string& _str); + +} // namespace rfl::internal::strings + +#endif diff --git a/include/rfl/internal/transform_snake_case.hpp b/include/rfl/internal/transform_snake_case.hpp index a6a246b0..cf7360d5 100644 --- a/include/rfl/internal/transform_snake_case.hpp +++ b/include/rfl/internal/transform_snake_case.hpp @@ -15,19 +15,36 @@ consteval char to_upper() { } } +template +consteval char to_lower() { + if constexpr (c >= 'A' && c <= 'Z') { + return c - ('A' - 'a'); + } else { + return c; + } +} + /// Transforms the field name from snake case to camel case. template consteval auto transform_snake_case() { if constexpr (_i == _name.arr_.size()) { return StringLiteral(chars...); + } else if constexpr (_name.arr_[_i] == '_') { return transform_snake_case<_name, true, _i + 1, chars...>(); + } else if constexpr (_name.arr_[_i] == '\0') { return transform_snake_case<_name, false, _name.arr_.size(), chars...>(); + } else if constexpr (_capitalize) { return transform_snake_case<_name, false, _i + 1, chars..., to_upper<_name.arr_[_i]>()>(); + + } else if constexpr (sizeof...(chars) == 0) { + return transform_snake_case<_name, false, _i + 1, + to_lower<_name.arr_[_i]>()>(); + } else { return transform_snake_case<_name, false, _i + 1, chars..., _name.arr_[_i]>(); diff --git a/include/rfl/named_tuple_t.hpp b/include/rfl/named_tuple_t.hpp index d1bfd385..4cb7786a 100644 --- a/include/rfl/named_tuple_t.hpp +++ b/include/rfl/named_tuple_t.hpp @@ -6,38 +6,18 @@ #include #include "NamedTuple.hpp" -#include "internal/is_named_tuple.hpp" #include "internal/ptr_named_tuple_t.hpp" -#include "internal/wrap_in_rfl_array_t.hpp" +#include "internal/remove_ptrs_nt.hpp" #include "to_named_tuple.hpp" namespace rfl { -template -struct remove_ptr; - -template -struct remove_ptr> { - using FieldType = - Field<_name, internal::wrap_in_rfl_array_t< - std::remove_cvref_t>>>; -}; - -template -struct remove_ptrs_nt; - -template -struct remove_ptrs_nt> { - using NamedTupleType = - NamedTuple::FieldType...>; -}; - /// Generates the named tuple that is equivalent to the struct T. /// This is the result you would expect from calling to_named_tuple(my_struct). /// All fields of the struct must be an rfl::Field. template -using named_tuple_t = - typename remove_ptrs_nt>::NamedTupleType; +using named_tuple_t = typename internal::remove_ptrs_nt< + internal::ptr_named_tuple_t>::NamedTupleType; } // namespace rfl diff --git a/include/rfl/parsing/CustomParser.hpp b/include/rfl/parsing/CustomParser.hpp index 200c0ff9..88f8be09 100644 --- a/include/rfl/parsing/CustomParser.hpp +++ b/include/rfl/parsing/CustomParser.hpp @@ -1,6 +1,7 @@ #ifndef RFL_PARSING_CUSTOMPARSER_HPP_ #define RFL_PARSING_CUSTOMPARSER_HPP_ +#include #include #include @@ -16,6 +17,8 @@ namespace parsing { template struct CustomParser { + using CustomParserHelperStruct = std::remove_cvref_t; + static Result read(const R& _r, const auto& _var) noexcept { const auto to_class = [](auto&& _h) -> Result { try { @@ -32,21 +35,22 @@ struct CustomParser { return Error(e.what()); } }; - return Parser::read(_r, _var).and_then( - to_class); + return Parser::read(_r, + _var) + .and_then(to_class); } template static auto write(const W& _w, const OriginalClass& _p, const P& _parent) noexcept { - Parser::write( + Parser::write( _w, HelperStruct::from_class(_p), _parent); } static schema::Type to_schema( std::map* _definitions) { - return Parser, - ProcessorsType>::to_schema(_definitions); + return Parser::to_schema( + _definitions); } }; diff --git a/include/rfl/parsing/NamedTupleParser.hpp b/include/rfl/parsing/NamedTupleParser.hpp index 4cf8d203..eb530271 100644 --- a/include/rfl/parsing/NamedTupleParser.hpp +++ b/include/rfl/parsing/NamedTupleParser.hpp @@ -20,7 +20,6 @@ #include "../internal/no_duplicate_field_names.hpp" #include "../internal/nth_element_t.hpp" #include "../internal/ptr_cast.hpp" -#include "../internal/strings/replace_all.hpp" #include "../to_view.hpp" #include "AreReaderAndWriter.hpp" #include "Parent.hpp" diff --git a/include/rfl/parsing/Parser_default.hpp b/include/rfl/parsing/Parser_default.hpp index 38f4945c..8ff5b1a5 100644 --- a/include/rfl/parsing/Parser_default.hpp +++ b/include/rfl/parsing/Parser_default.hpp @@ -22,17 +22,17 @@ #include "../internal/ptr_cast.hpp" #include "../internal/to_ptr_named_tuple.hpp" #include "../to_view.hpp" -#include "../type_name_t.hpp" #include "AreReaderAndWriter.hpp" #include "Parent.hpp" #include "Parser_base.hpp" #include "call_destructors_where_necessary.hpp" #include "is_tagged_union_wrapper.hpp" +#include "make_type_name.hpp" #include "schema/Type.hpp" #include "schemaful/IsSchemafulReader.hpp" #include "schemaful/IsSchemafulWriter.hpp" -namespace rfl ::parsing { +namespace rfl::parsing { /// Default case - anything that cannot be explicitly matched. template @@ -265,16 +265,6 @@ struct Parser { .validation_ = ValidationType::template to_schema()}}; } - template - static std::string make_type_name() { - if constexpr (is_tagged_union_wrapper_v) { - return replace_non_alphanumeric(type_name_t().str() + - "__tagged"); - } else { - return replace_non_alphanumeric(type_name_t().str()); - } - } - /// The way this works is that we allocate space on the stack in this size of /// the struct in which we then write the individual fields using /// views and placement new. This is how we deal with the fact that some @@ -312,13 +302,6 @@ struct Parser { } return t; } - - static std::string replace_non_alphanumeric(std::string _str) { - for (auto& ch : _str) { - ch = std::isalnum(ch) ? ch : '_'; - } - return _str; - } }; } // namespace rfl::parsing diff --git a/include/rfl/parsing/Parser_tagged_union.hpp b/include/rfl/parsing/Parser_tagged_union.hpp index 49c10695..2f9b493b 100644 --- a/include/rfl/parsing/Parser_tagged_union.hpp +++ b/include/rfl/parsing/Parser_tagged_union.hpp @@ -8,7 +8,7 @@ #include "../Result.hpp" #include "../TaggedUnion.hpp" #include "../always_false.hpp" -#include "../internal/strings/join.hpp" +#include "../internal/strings/strings.hpp" #include "../named_tuple_t.hpp" #include "Parser_base.hpp" #include "TaggedUnionWrapper.hpp" diff --git a/include/rfl/parsing/TupleParser.hpp b/include/rfl/parsing/TupleParser.hpp index 5e916b86..e09b24ab 100644 --- a/include/rfl/parsing/TupleParser.hpp +++ b/include/rfl/parsing/TupleParser.hpp @@ -46,7 +46,7 @@ struct TupleParser { } else { const auto parse = [&](const InputArrayType& _arr) -> Result { - alignas(TupleType) unsigned char buf[sizeof(TupleType)]; + alignas(TupleType) unsigned char buf[sizeof(TupleType)]{}; auto ptr = internal::ptr_cast(&buf); const auto tuple_reader = TupleReader +static std::string make_type_name() { + if constexpr (is_tagged_union_wrapper_v) { + return replace_non_alphanumeric(type_name_t().str() + + "__tagged"); + } else { + return replace_non_alphanumeric(type_name_t().str()); + } +} + +} // namespace parsing +} // namespace rfl + +#endif diff --git a/include/rfl/parsing/schemaful/tuple_to_named_tuple.hpp b/include/rfl/parsing/schemaful/tuple_to_named_tuple.hpp index 70ea442e..65f654e1 100644 --- a/include/rfl/parsing/schemaful/tuple_to_named_tuple.hpp +++ b/include/rfl/parsing/schemaful/tuple_to_named_tuple.hpp @@ -13,7 +13,7 @@ namespace rfl::parsing::schemaful { template -consteval auto to_field_name() { +inline consteval auto to_field_name() { return internal::StringLiteral<5>('f', static_cast('0' + ((_i / 100) % 10)), static_cast('0' + ((_i / 10) % 10)), @@ -21,7 +21,7 @@ consteval auto to_field_name() { } template -auto to_field(const auto& _t) { +inline auto to_field(const auto& _t) { using T = std::remove_cvref_t; return rfl::Field(), const T*>(&_t); } diff --git a/include/rfl/parsing/schemaful/tuple_to_object.hpp b/include/rfl/parsing/schemaful/tuple_to_object.hpp index a4cad6ad..b01da602 100644 --- a/include/rfl/parsing/schemaful/tuple_to_object.hpp +++ b/include/rfl/parsing/schemaful/tuple_to_object.hpp @@ -7,21 +7,9 @@ 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; -} +schema::Type::Object tuple_to_object(const schema::Type::Tuple& _tup); } // namespace rfl::parsing::schemaful diff --git a/include/rfl/parsing/to_single_error_message.hpp b/include/rfl/parsing/to_single_error_message.hpp index b5e633b9..3d42b7c6 100644 --- a/include/rfl/parsing/to_single_error_message.hpp +++ b/include/rfl/parsing/to_single_error_message.hpp @@ -6,7 +6,7 @@ #include #include -#include "../internal/strings/replace_all.hpp" +#include "../internal/strings/strings.hpp" namespace rfl::parsing { diff --git a/mkdocs.yaml b/mkdocs.yaml index 46beabe5..cd3ee8be 100644 --- a/mkdocs.yaml +++ b/mkdocs.yaml @@ -94,6 +94,7 @@ nav: - Supported Formats: - Avro: supported_formats/avro.md - BSON: supported_formats/bson.md + - Cap'n Proto: supported_formats/capnproto.md - CBOR: supported_formats/cbor.md - FlexBuffers: supported_formats/flexbuffers.md - JSON: supported_formats/json.md diff --git a/src/reflectcpp.cpp b/src/reflectcpp.cpp index 52cf1c11..5fa52a99 100644 --- a/src/reflectcpp.cpp +++ b/src/reflectcpp.cpp @@ -32,4 +32,6 @@ SOFTWARE. #include "rfl/Generic.cpp" #include "rfl/generic/Reader.cpp" #include "rfl/generic/Writer.cpp" +#include "rfl/internal/strings/strings.cpp" #include "rfl/parsing/schema/Type.cpp" +#include "rfl/parsing/schemaful/tuple_to_object.cpp" diff --git a/src/reflectcpp_capnproto.cpp b/src/reflectcpp_capnproto.cpp new file mode 100644 index 00000000..217e3f23 --- /dev/null +++ b/src/reflectcpp_capnproto.cpp @@ -0,0 +1,42 @@ +/* + +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"*/ +#include "rfl/capnproto/Reader.cpp" +#include "rfl/capnproto/SchemaImpl.cpp" +#include "rfl/capnproto/Type.cpp" +#include "rfl/capnproto/Writer.cpp" +#include "rfl/capnproto/to_schema.cpp" diff --git a/src/rfl/capnproto/Reader.cpp b/src/rfl/capnproto/Reader.cpp new file mode 100644 index 00000000..f6fa03bf --- /dev/null +++ b/src/rfl/capnproto/Reader.cpp @@ -0,0 +1,58 @@ +#include "rfl/capnproto/Reader.hpp" + +#include "rfl/parsing/schemaful/IsSchemafulReader.hpp" + +namespace rfl::capnproto { + +static_assert(parsing::schemaful::IsSchemafulReader, + "This must be a schemaful reader."); + +std::optional> +Reader::identify_discriminant(const InputUnionType& _union) const noexcept { + size_t ix = 0; + for (auto field : _union.val_.getSchema().getFields()) { + if (_union.val_.has(field)) { + return std::make_pair(field, ix); + } + ++ix; + } + return std::nullopt; +} + +bool Reader::is_empty(const InputVarType& _var) const noexcept { + return _var.val_.getType() == capnp::DynamicValue::VOID; +} + +rfl::Result Reader::to_array( + const InputVarType& _var) const noexcept { + if (_var.val_.getType() != capnp::DynamicValue::LIST) { + return Error("Could not cast to a list."); + } + return InputArrayType{_var.val_.as()}; +} + +rfl::Result Reader::to_object( + const InputVarType& _var) const noexcept { + if (_var.val_.getType() != capnp::DynamicValue::STRUCT) { + return Error("Could not cast to a struct."); + } + return InputObjectType{_var.val_.as()}; +} + +rfl::Result Reader::to_map( + const InputVarType& _var) const noexcept { + if (_var.val_.getType() != capnp::DynamicValue::STRUCT) { + return Error("Could not cast to a map."); + } + return InputMapType{_var.val_.as()}; +} + +rfl::Result Reader::to_union( + const InputVarType& _var) const noexcept { + if (_var.val_.getType() != capnp::DynamicValue::STRUCT) { + return Error("Could not cast to a struct."); + } + return InputUnionType{_var.val_.as()}; +} + +} // namespace rfl::capnproto diff --git a/src/rfl/capnproto/SchemaImpl.cpp b/src/rfl/capnproto/SchemaImpl.cpp new file mode 100644 index 00000000..15078e5c --- /dev/null +++ b/src/rfl/capnproto/SchemaImpl.cpp @@ -0,0 +1,23 @@ +#include "rfl/capnproto/SchemaImpl.hpp" + +#include +#include + +namespace rfl::capnproto { + +SchemaImpl::SchemaImpl(const std::string& _str) + : str_(_str), + schema_parser_(Box::make()), + schema_(Box::make( + make_schema(str_, schema_parser_.get()))) {} + +capnp::ParsedSchema SchemaImpl::make_schema( + const std::string& _str, capnp::SchemaParser* _schema_parser) { + auto dir = kj::newInMemoryDirectory(kj::nullClock()); + auto path = kj::Path::parse("foo/bar.capnp"); + dir->openFile(path, kj::WriteMode::CREATE | kj::WriteMode::CREATE_PARENT) + ->writeAll(_str); + return _schema_parser->parseFromDirectory(*dir, std::move(path), nullptr); +} + +} // namespace rfl::capnproto diff --git a/src/rfl/capnproto/Type.cpp b/src/rfl/capnproto/Type.cpp new file mode 100644 index 00000000..de6592fe --- /dev/null +++ b/src/rfl/capnproto/Type.cpp @@ -0,0 +1,198 @@ +/* + +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/capnproto/schema/Type.hpp" + +#include +#include + +#include "rfl/internal/strings/strings.hpp" + +namespace rfl::capnproto::schema { + +/// Cap'n proto has a somewhat weird way of handling union fields, please refer +/// to the schema for further explanation. This is a workaround that ensures +/// that we can also support complex, nested unions. +void handle_fields_in_structs_or_unions(const auto& _struct_or_union, + const size_t _indent, + const std::string& _namespace, + std::ostream* _os, size_t* _ix) { + for (const auto& pair : _struct_or_union.fields) { + const auto name = pair.first; + // Because of the way Cap'n proto handles unions, we need a special case for + // them. + pair.second.reflection().visit([&](const auto& _r) { + using R = std::remove_cvref_t; + if constexpr (std::is_same()) { + // Special case: Union field. + *_os << std::string(_indent * 2, ' ') << name << " :union {" + << std::endl; + for (size_t i = 0; i < _r.fields.size(); ++i) { + _r.fields[i].second.reflection().visit([&](const auto& _union_field) { + using U = std::remove_cvref_t; + if constexpr (std::is_same()) { + *_os << std::string(_indent * 2 + 2, ' ') + << internal::strings::to_camel_case(_namespace + name + "_" + + _r.fields[i].first) + << " :union {" << std::endl; + handle_fields_in_structs_or_unions( + _union_field, _indent + 2, + _namespace + name + "_" + _r.fields[i].first + "_", _os, _ix); + *_os << std::string(_indent * 2 + 2, ' ') << "}" << std::endl; + + } else { + *_os << std::string(_indent * 2 + 2, ' ') + << internal::strings::to_camel_case(_namespace + name + "_" + + _r.fields[i].first) + << " @" << (*_ix)++ << " :" << _union_field << ";" + << std::endl; + } + }); + } + *_os << std::string(_indent * 2, ' ') << "}" << std::endl; + + } else { + // Standard case: Non-union field. + *_os << std::string(_indent * 2, ' ') + << internal::strings::to_camel_case(_namespace + name) << " @" + << (*_ix)++ << " :" << _r << ";" << std::endl; + } + }); + } +} + +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() || + 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)}; +} + +std::ostream& operator<<(std::ostream& _os, const Type::Void&) { + return _os << "Void"; +} + +std::ostream& operator<<(std::ostream& _os, const Type::Bool&) { + return _os << "Bool"; +} + +std::ostream& operator<<(std::ostream& _os, const Type::Int8&) { + return _os << "Int8"; +} + +std::ostream& operator<<(std::ostream& _os, const Type::Int16&) { + return _os << "Int16"; +} + +std::ostream& operator<<(std::ostream& _os, const Type::Int32&) { + return _os << "Int32"; +} + +std::ostream& operator<<(std::ostream& _os, const Type::Int64&) { + return _os << "Int64"; +} + +std::ostream& operator<<(std::ostream& _os, const Type::UInt8&) { + return _os << "UInt8"; +} + +std::ostream& operator<<(std::ostream& _os, const Type::UInt16&) { + return _os << "UInt16"; +} + +std::ostream& operator<<(std::ostream& _os, const Type::UInt32&) { + return _os << "UInt32"; +} + +std::ostream& operator<<(std::ostream& _os, const Type::UInt64&) { + return _os << "UInt64"; +} + +std::ostream& operator<<(std::ostream& _os, const Type::Float32&) { + return _os << "Float32"; +} + +std::ostream& operator<<(std::ostream& _os, const Type::Float64&) { + return _os << "Float64"; +} + +std::ostream& operator<<(std::ostream& _os, const Type::Data&) { + return _os << "Data"; +} + +std::ostream& operator<<(std::ostream& _os, const Type::Enum& _e) { + _os << "enum " << _e.name << " {" << std::endl; + for (size_t i = 0; i < _e.fields.size(); ++i) { + _os << " " << internal::strings::to_camel_case(_e.fields[i]) << " @" << i + << ";" << std::endl; + } + return _os << "}" << std::endl; +} + +std::ostream& operator<<(std::ostream& _os, const Type::List& _l) { + return _os << "List(" << *_l.type << ")"; +} + +std::ostream& operator<<(std::ostream& _os, const Type::Map& _m) { + return _os << "Map(" << *_m.type << ")"; +} + +std::ostream& operator<<(std::ostream& _os, const Type::Text&) { + return _os << "Text"; +} + +std::ostream& operator<<(std::ostream& _os, const Type::Struct& _s) { + _os << "struct " << _s.name << " {" << std::endl; + size_t ix = 0; + handle_fields_in_structs_or_unions(_s, 1, "", &_os, &ix); + return _os << "}" << std::endl; +} + +std::ostream& operator<<(std::ostream& _os, const Type::Union& _u) { + _os << "struct " << _u.name << " {" << std::endl << " union {" << std::endl; + size_t ix = 0; + handle_fields_in_structs_or_unions(_u, 2, "", &_os, &ix); + return _os << " }" << std::endl << "}" << std::endl; +} + +std::ostream& operator<<(std::ostream& _os, const Type::Reference& _r) { + return _os << internal::strings::to_pascal_case(_r.type_name); +} + +std::ostream& operator<<(std::ostream& _os, const Type& _t) { + return _t.reflection().visit( + [&](const auto& _r) -> std::ostream& { return _os << _r; }); +} + +} // namespace rfl::capnproto::schema diff --git a/src/rfl/capnproto/Writer.cpp b/src/rfl/capnproto/Writer.cpp new file mode 100644 index 00000000..cf575a1d --- /dev/null +++ b/src/rfl/capnproto/Writer.cpp @@ -0,0 +1,174 @@ +#include "rfl/capnproto/Writer.hpp" + +#include + +#include "rfl/parsing/schemaful/IsSchemafulWriter.hpp" + +namespace rfl::capnproto { + +static_assert(parsing::schemaful::IsSchemafulWriter, + "This must be a schemaful writer."); + +Writer::Writer(capnp::DynamicStruct::Builder* _root) : root_(_root){}; + +Writer::~Writer() = default; + +Writer::OutputObjectType Writer::object_as_root( + const size_t _size) const noexcept { + return OutputObjectType{root_->as()}; +} + +Writer::OutputArrayType Writer::add_array_to_array( + const size_t _size, OutputArrayType* _parent) const noexcept { + return OutputArrayType{ + _parent->val_.init(_parent->ix_++, _size).as()}; +} + +Writer::OutputArrayType Writer::add_array_to_map( + const std::string_view& _name, const size_t _size, + OutputMapType* _parent) const noexcept { + auto entries = OutputArrayType{ + .val_ = _parent->val_.get("entries").as(), + .ix_ = _parent->ix_++}; + auto new_entry = add_object_to_array(2, &entries); + add_value_to_object("key", std::string(_name), &new_entry); + return add_array_to_object("value", _size, &new_entry); +} + +Writer::OutputArrayType Writer::add_array_to_object( + const std::string_view& _name, const size_t _size, + OutputObjectType* _parent) const noexcept { + return OutputArrayType{ + _parent->val_.init(_name.data(), _size).as()}; +} + +Writer::OutputArrayType Writer::add_array_to_union( + const size_t _index, const size_t _size, + OutputUnionType* _parent) const noexcept { + const auto field = _parent->val_.getSchema().getFields()[_index]; + return OutputArrayType{ + _parent->val_.init(field, _size).template as()}; +} + +Writer::OutputMapType Writer::add_map_to_array( + const size_t _size, OutputArrayType* _parent) const noexcept { + auto new_map = add_object_to_array(1, _parent); + add_array_to_object("entries", _size, &new_map); + return OutputMapType{new_map.val_}; +} + +Writer::OutputMapType Writer::add_map_to_map( + const std::string_view& _name, const size_t _size, + OutputMapType* _parent) const noexcept { + auto new_map = add_object_to_map(_name, 1, _parent); + add_array_to_object("entries", _size, &new_map); + return OutputMapType{new_map.val_}; +} + +Writer::OutputMapType Writer::add_map_to_object( + const std::string_view& _name, const size_t _size, + OutputObjectType* _parent) const noexcept { + auto new_map = add_object_to_object(_name, 1, _parent); + add_array_to_object("entries", _size, &new_map); + return OutputMapType{new_map.val_}; +} + +Writer::OutputMapType Writer::add_map_to_union( + const size_t _index, const size_t _size, + OutputUnionType* _parent) const noexcept { + auto new_map = add_object_to_union(_index, 1, _parent); + add_array_to_object("entries", _size, &new_map); + return OutputMapType{new_map.val_}; +} + +Writer::OutputObjectType Writer::add_object_to_array( + const size_t _size, OutputArrayType* _parent) const noexcept { + return OutputObjectType{ + _parent->val_[_parent->ix_++].as()}; +} + +Writer::OutputObjectType Writer::add_object_to_map( + const std::string_view& _name, const size_t _size, + OutputMapType* _parent) const noexcept { + auto entries = OutputArrayType{ + .val_ = _parent->val_.get("entries").as(), + .ix_ = _parent->ix_++}; + auto new_entry = add_object_to_array(2, &entries); + add_value_to_object("key", std::string(_name), &new_entry); + return add_object_to_object("value", _size, &new_entry); +} + +Writer::OutputObjectType Writer::add_object_to_object( + const std::string_view& _name, const size_t _size, + OutputObjectType* _parent) const noexcept { + return OutputObjectType{ + _parent->val_.get(_name.data()).as()}; +} + +Writer::OutputObjectType Writer::add_object_to_union( + const size_t _index, const size_t _size, + OutputUnionType* _parent) const noexcept { + const auto field = _parent->val_.getSchema().getFields()[_index]; + return OutputObjectType{ + _parent->val_.init(field).template as()}; +} + +Writer::OutputUnionType Writer::add_union_to_array( + OutputArrayType* _parent) const noexcept { + return OutputUnionType{ + _parent->val_[_parent->ix_++].as()}; +} + +Writer::OutputUnionType Writer::add_union_to_map( + const std::string_view& _name, OutputMapType* _parent) const noexcept { + auto entries = OutputArrayType{ + .val_ = _parent->val_.get("entries").as(), + .ix_ = _parent->ix_++}; + auto new_entry = add_object_to_array(2, &entries); + add_value_to_object("key", std::string(_name), &new_entry); + return add_union_to_object("value", &new_entry); +} + +Writer::OutputUnionType Writer::add_union_to_object( + const std::string_view& _name, OutputObjectType* _parent) const noexcept { + return OutputUnionType{ + _parent->val_.get(_name.data()).as()}; +} + +Writer::OutputUnionType Writer::add_union_to_union( + const size_t _index, OutputUnionType* _parent) const noexcept { + const auto field = _parent->val_.getSchema().getFields()[_index]; + return OutputUnionType{ + _parent->val_.init(field).template as()}; +} + +Writer::OutputVarType Writer::add_null_to_array( + OutputArrayType* _parent) const noexcept { + _parent->val_.set(_parent->ix_++, capnp::VOID); + return OutputVarType{}; +} + +Writer::OutputVarType Writer::add_null_to_map( + const std::string_view& _name, OutputMapType* _parent) const noexcept { + auto entries = OutputArrayType{ + .val_ = _parent->val_.get("entries").as(), + .ix_ = _parent->ix_++}; + auto new_entry = add_object_to_array(2, &entries); + add_value_to_object("key", std::string(_name), &new_entry); + return add_null_to_object("value", &new_entry); +} + +Writer::OutputVarType Writer::add_null_to_object( + const std::string_view& _name, OutputObjectType* _parent) const noexcept { + _parent->val_.set(_name.data(), capnp::VOID); + return OutputVarType{}; +} + +Writer::OutputVarType Writer::add_null_to_union( + const size_t _index, OutputUnionType* _parent) const noexcept { + const auto field = _parent->val_.getSchema().getFields()[_index]; + _parent->val_.set(field, capnp::VOID); + return OutputVarType{}; +} + +} // namespace rfl::capnproto diff --git a/src/rfl/capnproto/to_schema.cpp b/src/rfl/capnproto/to_schema.cpp new file mode 100644 index 00000000..3057a60e --- /dev/null +++ b/src/rfl/capnproto/to_schema.cpp @@ -0,0 +1,257 @@ +/* + +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/capnproto/to_schema.hpp" + +#include +#include +#include +#include + +#include "rfl/capnproto/is_named_type.hpp" +#include "rfl/capnproto/schema/CapnProtoTypes.hpp" +#include "rfl/capnproto/schema/Type.hpp" +#include "rfl/internal/strings/strings.hpp" +#include "rfl/json.hpp" +#include "rfl/parsing/schemaful/tuple_to_object.hpp" + +namespace rfl::capnproto { + +enum struct Parent { is_top_level, is_a_struct, is_not_a_struct }; + +schema::Type type_to_capnproto_schema_type( + const parsing::schema::Type& _type, + const std::map& _definitions, + const Parent _parent, schema::CapnProtoTypes* _cnp_types); + +schema::Type any_of_to_capnproto_schema_type( + const parsing::schema::Type::AnyOf& _any_of, + const std::map& _definitions, + const Parent _parent, schema::CapnProtoTypes* _cnp_types) { + auto value = schema::Type::Union{}; + size_t i = 1; + for (const auto& type : _any_of.types_) { + value.fields.push_back( + std::make_pair(std::string("Opt" + std::to_string(i++)), + type_to_capnproto_schema_type(type, _definitions, + _parent, _cnp_types))); + } + if (_parent == Parent::is_a_struct) { + return schema::Type{.value = value}; + } else { + const auto name = + std::string("Union") + std::to_string(_cnp_types->unions_.size() + 1); + _cnp_types->unions_[name] = schema::Type{.value = value}; + return schema::Type{.value = schema::Type::Reference{name}}; + } +} + +schema::Type literal_to_capnproto_schema_type( + const parsing::schema::Type::Literal& _literal, + const std::map& _definitions, + const Parent _parent, schema::CapnProtoTypes* _cnp_types) { + const auto enum_schema = schema::Type::Enum{.fields = _literal.values_}; + if (_parent == Parent::is_top_level) { + return schema::Type{.value = enum_schema}; + } else { + const auto name = + std::string("Enum") + std::to_string(_cnp_types->enums_.size() + 1); + _cnp_types->enums_[name] = schema::Type{.value = enum_schema}; + return schema::Type{.value = schema::Type::Reference{name}}; + } +} + +schema::Type object_to_capnproto_schema_type( + const parsing::schema::Type::Object& _obj, + const std::map& _definitions, + const Parent _parent, schema::CapnProtoTypes* _cnp_types) { + schema::Type::Struct struct_schema; + for (const auto& [k, v] : _obj.types_) { + struct_schema.fields.push_back(std::make_pair( + k, type_to_capnproto_schema_type(v, _definitions, Parent::is_a_struct, + _cnp_types))); + } + if (_parent == Parent::is_top_level) { + return schema::Type{.value = struct_schema}; + } else { + const auto name = + std::string("Tuple") + std::to_string(_cnp_types->tuples_.size() + 1); + _cnp_types->tuples_[name] = schema::Type{.value = struct_schema}; + return schema::Type{.value = schema::Type::Reference{name}}; + } +} + +schema::Type optional_to_capnproto_schema_type( + const parsing::schema::Type::Optional& _optional, + const std::map& _definitions, + const Parent _parent, schema::CapnProtoTypes* _cnp_types) { + const auto value = schema::Type::Union{ + .fields = + std::vector({std::make_pair(std::string("Some"), + type_to_capnproto_schema_type( + *_optional.type_, _definitions, + _parent, _cnp_types)), + std::make_pair(std::string("None"), + schema::Type{schema::Type::Void{}})})}; + if (_parent == Parent::is_a_struct) { + return schema::Type{.value = value}; + } else { + const auto name = + std::string("Union") + std::to_string(_cnp_types->unions_.size() + 1); + _cnp_types->unions_[name] = schema::Type{.value = value}; + return schema::Type{.value = schema::Type::Reference{name}}; + } +} + +schema::Type reference_to_capnproto_schema_type( + const parsing::schema::Type::Reference& _reference, + const std::map& _definitions, + const Parent _parent, schema::CapnProtoTypes* _cnp_types) { + const auto it = _definitions.find(_reference.name_); + if (it == _definitions.end() || is_named_type(it->second)) { + return schema::Type{ + .value = schema::Type::Reference{.type_name = _reference.name_}}; + } else { + return type_to_capnproto_schema_type(it->second, _definitions, _parent, + _cnp_types); + } +} + +schema::Type type_to_capnproto_schema_type( + const parsing::schema::Type& _type, + const std::map& _definitions, + const Parent _parent, schema::CapnProtoTypes* _cnp_types) { + 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::Bool{}}; + + } else if constexpr (std::is_same()) { + return schema::Type{.value = schema::Type::Data{}}; + + } else if constexpr (std::is_same() || + std::is_same()) { + return schema::Type{.value = schema::Type::Int32{}}; + + } else if constexpr (std::is_same()) { + return schema::Type{.value = schema::Type::Int64{}}; + + } else if constexpr (std::is_same()) { + return schema::Type{.value = schema::Type::UInt32{}}; + + } else if constexpr (std::is_same()) { + return schema::Type{.value = schema::Type::UInt64{}}; + + } else if constexpr (std::is_same()) { + return schema::Type{.value = schema::Type::Float32{}}; + + } else if constexpr (std::is_same()) { + return schema::Type{.value = schema::Type::Float64{}}; + + } else if constexpr (std::is_same()) { + return schema::Type{.value = schema::Type::Text{}}; + + } else if constexpr (std::is_same()) { + return any_of_to_capnproto_schema_type(_t, _definitions, _parent, + _cnp_types); + + } else if constexpr (std::is_same()) { + return type_to_capnproto_schema_type(*_t.type_, _definitions, _parent, + _cnp_types); + + } else if constexpr (std::is_same()) { + return schema::Type{ + .value = schema::Type::List{ + .type = Ref::make(type_to_capnproto_schema_type( + *_t.type_, _definitions, Parent::is_not_a_struct, + _cnp_types))}}; + + } else if constexpr (std::is_same()) { + return literal_to_capnproto_schema_type(_t, _definitions, _parent, + _cnp_types); + + } else if constexpr (std::is_same()) { + return object_to_capnproto_schema_type(_t, _definitions, _parent, + _cnp_types); + + } else if constexpr (std::is_same()) { + return optional_to_capnproto_schema_type(_t, _definitions, _parent, + _cnp_types); + + } else if constexpr (std::is_same()) { + return reference_to_capnproto_schema_type(_t, _definitions, _parent, + _cnp_types); + + } else if constexpr (std::is_same()) { + _cnp_types->has_maps_ = true; + return schema::Type{ + .value = schema::Type::Map{ + .type = Ref::make(type_to_capnproto_schema_type( + *_t.value_type_, _definitions, Parent::is_not_a_struct, + _cnp_types))}}; + + } else if constexpr (std::is_same()) { + return type_to_capnproto_schema_type( + Type{parsing::schemaful::tuple_to_object(_t)}, _definitions, _parent, + _cnp_types); + + } else if constexpr (std::is_same()) { + return schema::Type{ + .value = schema::Type::List{ + .type = Ref::make(type_to_capnproto_schema_type( + *_t.type_, _definitions, Parent::is_not_a_struct, + _cnp_types))}}; + + } else if constexpr (std::is_same()) { + // Cap'n Proto knows no validation. + return type_to_capnproto_schema_type(*_t.type_, _definitions, _parent, + _cnp_types); + } else { + static_assert(rfl::always_false_v, "Not all cases were covered."); + } + }; + + return rfl::visit(handle_variant, _type.variant_); +} + +std::string to_string_representation( + const parsing::schema::Definition& _internal_schema) { + schema::CapnProtoTypes cnp_types; + for (const auto& [name, def] : _internal_schema.definitions_) { + if (!is_named_type(def)) { + continue; + } + cnp_types.structs_[name] = type_to_capnproto_schema_type( + def, _internal_schema.definitions_, Parent::is_top_level, &cnp_types); + } + + std::stringstream sstream; + sstream << cnp_types; + return sstream.str(); +} + +} // namespace rfl::capnproto diff --git a/src/rfl/internal/strings/strings.cpp b/src/rfl/internal/strings/strings.cpp new file mode 100644 index 00000000..9692ceb1 --- /dev/null +++ b/src/rfl/internal/strings/strings.cpp @@ -0,0 +1,84 @@ + +namespace rfl ::internal ::strings { + +char to_lower(const char ch) { + if (ch >= 'A' && ch <= 'Z') { + return ch + ('a' - 'A'); + } else { + return ch; + } +} + +char to_upper(const char ch) { + if (ch >= 'a' && ch <= 'z') { + return ch + ('A' - 'a'); + } else { + return ch; + } +} + +std::string join(const std::string& _delimiter, + const std::vector& _strings) { + if (_strings.size() == 0) { + return ""; + } + auto res = _strings[0]; + for (size_t i = 1; i < _strings.size(); ++i) { + res += _delimiter + _strings[i]; + } + return res; +} + +std::string replace_all(const std::string& _str, const std::string& _from, + const std::string& _to) { + auto str = _str; + + size_t pos = 0; + while ((pos = str.find(_from, pos)) != std::string::npos) { + str.replace(pos, _from.length(), _to); + pos += _to.length(); + } + return str; +} + +std::vector split(const std::string& _str, + const std::string& _delimiter) { + auto str = _str; + size_t pos = 0; + std::vector result; + while ((pos = str.find(_delimiter)) != std::string::npos) { + result.emplace_back(str.substr(0, pos)); + str.erase(0, pos + _delimiter.length()); + } + result.emplace_back(std::move(str)); + return result; +} + +std::string to_camel_case(const std::string& _str) { + std::string result; + bool capitalize = false; + for (const char ch : _str) { + if (ch == '_') { + capitalize = true; + } else if (capitalize) { + result.push_back(to_upper(ch)); + capitalize = false; + } else { + result.push_back(ch); + } + } + if (result.size() > 0) { + result[0] = to_lower(result[0]); + } + return result; +} + +std::string to_pascal_case(const std::string& _str) { + auto result = to_camel_case("_" + _str); + if (result.size() > 0) { + result[0] = to_upper(result[0]); + } + return result; +} + +} // namespace rfl::internal::strings diff --git a/src/rfl/parsing/schemaful/tuple_to_object.cpp b/src/rfl/parsing/schemaful/tuple_to_object.cpp new file mode 100644 index 00000000..e75f9a33 --- /dev/null +++ b/src/rfl/parsing/schemaful/tuple_to_object.cpp @@ -0,0 +1,18 @@ +#include "rfl/parsing/schemaful/tuple_to_object.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))}); +} + +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 diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index d99a20a2..cdd1a6d5 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -20,6 +20,10 @@ if (REFLECTCPP_BSON) add_subdirectory(bson) endif() +if (REFLECTCPP_CAPNPROTO) + add_subdirectory(capnproto) +endif() + if (REFLECTCPP_CBOR) add_subdirectory(cbor) endif() diff --git a/tests/README.md b/tests/README.md index 3da3b66b..67ccb3b8 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_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 -S . -B build -DREFLECTCPP_BUILD_TESTS=ON -DREFLECTCPP_AVRO=ON -DREFLECTCPP_BSON=ON -DREFLECTCPP_CAPNPROTO=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 ``` @@ -42,6 +42,7 @@ To run the tests, do the following: ``` ./build/tests/avro/reflect-cpp-avro-tests ./build/tests/bson/reflect-cpp-bson-tests +./build/tests/capnproto/reflect-cpp-capnproto-tests ./build/tests/cbor/reflect-cpp-cbor-tests ./build/tests/flexbuffers/reflect-cpp-flexbuffers-tests ./build/tests/msgpack/reflect-cpp-msgpack-tests diff --git a/tests/capnproto/CMakeLists.txt b/tests/capnproto/CMakeLists.txt new file mode 100644 index 00000000..4a6fb365 --- /dev/null +++ b/tests/capnproto/CMakeLists.txt @@ -0,0 +1,19 @@ +project(reflect-cpp-capnproto-tests) + +file(GLOB_RECURSE SOURCES CONFIGURE_DEPENDS "*.cpp") + +add_executable( + reflect-cpp-capnproto-tests + ${SOURCES} +) +target_precompile_headers(reflect-cpp-capnproto-tests PRIVATE [["rfl.hpp"]] ) + + +target_link_libraries( + reflect-cpp-capnproto-tests + PRIVATE + "${REFLECT_CPP_GTEST_LIB}" +) + +find_package(GTest) +gtest_discover_tests(reflect-cpp-capnproto-tests) diff --git a/tests/capnproto/test_add_struct_name.cpp b/tests/capnproto/test_add_struct_name.cpp new file mode 100644 index 00000000..3fc04e97 --- /dev/null +++ b/tests/capnproto/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(capnproto, 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/capnproto/test_array.cpp b/tests/capnproto/test_array.cpp new file mode 100644 index 00000000..bbaa618c --- /dev/null +++ b/tests/capnproto/test_array.cpp @@ -0,0 +1,35 @@ +#include +#include +#include +#include +#include + +// Make sure things still compile when +// rfl.hpp is included after rfl/capnproto.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(capnproto, 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/capnproto/test_box.cpp b/tests/capnproto/test_box.cpp new file mode 100644 index 00000000..def342eb --- /dev/null +++ b/tests/capnproto/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(capnproto, 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/capnproto/test_bytestring.cpp b/tests/capnproto/test_bytestring.cpp new file mode 100644 index 00000000..43fa5c9b --- /dev/null +++ b/tests/capnproto/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(capnproto, 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/capnproto/test_custom_class1.cpp b/tests/capnproto/test_custom_class1.cpp new file mode 100644 index 00000000..e57e9d85 --- /dev/null +++ b/tests/capnproto/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(capnproto, test_custom_class1) { + const auto bart = Person("Bart"); + + write_and_read(bart); +} +} // namespace test_custom_class1 diff --git a/tests/capnproto/test_custom_class3.cpp b/tests/capnproto/test_custom_class3.cpp new file mode 100644 index 00000000..0e90b9ba --- /dev/null +++ b/tests/capnproto/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(capnproto, test_custom_class3) { + const auto bart = Person("Bart", "Simpson", 10); + + write_and_read(bart); +} + +} // namespace test_custom_class3 diff --git a/tests/capnproto/test_custom_class4.cpp b/tests/capnproto/test_custom_class4.cpp new file mode 100644 index 00000000..688d877c --- /dev/null +++ b/tests/capnproto/test_custom_class4.cpp @@ -0,0 +1,70 @@ +#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()}; + } + + Person to_class() const { + return Person(first_name.value(), std::move(last_name.value()), + age.value()); + } +}; + +} // namespace test_custom_class4 + +namespace rfl { +namespace parsing { + +template +struct Parser + : public CustomParser {}; + +} // namespace parsing +} // namespace rfl + +namespace test_custom_class4 { + +TEST(capnproto, 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/capnproto/test_default_values.cpp b/tests/capnproto/test_default_values.cpp new file mode 100644 index 00000000..6d456271 --- /dev/null +++ b/tests/capnproto/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(capnproto, 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/capnproto/test_deque.cpp b/tests/capnproto/test_deque.cpp new file mode 100644 index 00000000..250005fa --- /dev/null +++ b/tests/capnproto/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(capnproto, 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/capnproto/test_enum.cpp b/tests/capnproto/test_enum.cpp new file mode 100644 index 00000000..fd92b6bc --- /dev/null +++ b/tests/capnproto/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(capnproto, test_enum) { + const auto circle = Circle{.radius = 2.0, .color = Color::green}; + + write_and_read(circle); +} + +} // namespace test_enum diff --git a/tests/capnproto/test_field_variant.cpp b/tests/capnproto/test_field_variant.cpp new file mode 100644 index 00000000..1418e9af --- /dev/null +++ b/tests/capnproto/test_field_variant.cpp @@ -0,0 +1,36 @@ +#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; +}; + +struct Shapes { + rfl::Variant, rfl::Field<"rectangle", Rectangle>, + rfl::Field<"square", rfl::Box>> + root; +}; + +TEST(capnproto, test_field_variant_std) { + const auto r = + Shapes{rfl::make_field<"rectangle">(Rectangle{.height = 10, .width = 5})}; + + write_and_read(r); +} +} // namespace test_field_variant diff --git a/tests/capnproto/test_field_variant_std.cpp b/tests/capnproto/test_field_variant_std.cpp new file mode 100644 index 00000000..2262fe2d --- /dev/null +++ b/tests/capnproto/test_field_variant_std.cpp @@ -0,0 +1,36 @@ +#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; +}; + +struct Shapes { + std::variant, rfl::Field<"rectangle", Rectangle>, + rfl::Field<"square", rfl::Box>> + root; +}; + +TEST(capnproto, test_field_variant_std) { + const auto r = + Shapes{rfl::make_field<"rectangle">(Rectangle{.height = 10, .width = 5})}; + + write_and_read(r); +} +} // namespace test_field_variant_std diff --git a/tests/capnproto/test_flag_enum.cpp b/tests/capnproto/test_flag_enum.cpp new file mode 100644 index 00000000..17687653 --- /dev/null +++ b/tests/capnproto/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(capnproto, 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/capnproto/test_flag_enum_with_int.cpp b/tests/capnproto/test_flag_enum_with_int.cpp new file mode 100644 index 00000000..08de18e2 --- /dev/null +++ b/tests/capnproto/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(capnproto, 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/capnproto/test_flatten.cpp b/tests/capnproto/test_flatten.cpp new file mode 100644 index 00000000..e461ac35 --- /dev/null +++ b/tests/capnproto/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(capnproto, 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/capnproto/test_flatten_anonymous.cpp b/tests/capnproto/test_flatten_anonymous.cpp new file mode 100644 index 00000000..03749f15 --- /dev/null +++ b/tests/capnproto/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(capnproto, 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/capnproto/test_forward_list.cpp b/tests/capnproto/test_forward_list.cpp new file mode 100644 index 00000000..256c7437 --- /dev/null +++ b/tests/capnproto/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(capnproto, 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/capnproto/test_literal.cpp b/tests/capnproto/test_literal.cpp new file mode 100644 index 00000000..441feec7 --- /dev/null +++ b/tests/capnproto/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(capnproto, test_literal) { + const auto bart = Person{.first_name = FirstName::make<"Bart">()}; + + write_and_read(bart); +} +} // namespace test_literal diff --git a/tests/capnproto/test_literal_map.cpp b/tests/capnproto/test_literal_map.cpp new file mode 100644 index 00000000..e3149d5d --- /dev/null +++ b/tests/capnproto/test_literal_map.cpp @@ -0,0 +1,26 @@ +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_literal_map { + +using FieldName = rfl::Literal<"firstName", "lastName">; + +struct RootStruct { + std::map> root; +}; + +TEST(capnproto, test_literal_map) { + RootStruct homer; + homer.root.insert(std::make_pair(FieldName::make<"firstName">(), + std::make_unique("Homer"))); + homer.root.insert(std::make_pair(FieldName::make<"lastName">(), + std::make_unique("Simpson"))); + write_and_read(homer); +} +} // namespace test_literal_map diff --git a/tests/capnproto/test_map.cpp b/tests/capnproto/test_map.cpp new file mode 100644 index 00000000..a0e17f51 --- /dev/null +++ b/tests/capnproto/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(capnproto, 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/capnproto/test_map2.cpp b/tests/capnproto/test_map2.cpp new file mode 100644 index 00000000..ac2a5acc --- /dev/null +++ b/tests/capnproto/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(capnproto, 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/capnproto/test_monster_example.cpp b/tests/capnproto/test_monster_example.cpp new file mode 100644 index 00000000..d5a52e62 --- /dev/null +++ b/tests/capnproto/test_monster_example.cpp @@ -0,0 +1,60 @@ +#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, rfl::Field<"None", int>>; + +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(capnproto, 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/capnproto/test_optional_fields.cpp b/tests/capnproto/test_optional_fields.cpp new file mode 100644 index 00000000..6456fec4 --- /dev/null +++ b/tests/capnproto/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(capnproto, 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/capnproto/test_optionals_in_vectors.cpp b/tests/capnproto/test_optionals_in_vectors.cpp new file mode 100644 index 00000000..10e49302 --- /dev/null +++ b/tests/capnproto/test_optionals_in_vectors.cpp @@ -0,0 +1,30 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_optionals_in_vectors { + +struct Person { + std::string first_name; + std::string last_name = "Simpson"; + std::vector> children; +}; + +TEST(capnproto, test_optionals_in_vectors) { + const std::optional bart = Person{.first_name = "Bart"}; + + const std::optional lisa = Person{.first_name = "Lisa"}; + + const std::optional maggie = Person{.first_name = "Maggie"}; + + const auto homer = Person{.first_name = "Homer", + .children = std::vector>( + {bart, lisa, maggie, std::nullopt})}; + + write_and_read(homer); +} +} // namespace test_optionals_in_vectors diff --git a/tests/capnproto/test_person.cpp b/tests/capnproto/test_person.cpp new file mode 100644 index 00000000..1e469935 --- /dev/null +++ b/tests/capnproto/test_person.cpp @@ -0,0 +1,32 @@ +#include + +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_tutorial_example { + +struct Person { + std::string first_name; + std::string last_name = "Simpson"; + std::vector children; +}; + +TEST(capnproto, test_person) { + 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_tutorial_example diff --git a/tests/capnproto/test_readme_example.cpp b/tests/capnproto/test_readme_example.cpp new file mode 100644 index 00000000..3e911aa6 --- /dev/null +++ b/tests/capnproto/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(capnproto, 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/capnproto/test_readme_example2.cpp b/tests/capnproto/test_readme_example2.cpp new file mode 100644 index 00000000..2f6f9b44 --- /dev/null +++ b/tests/capnproto/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(capnproto, 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/capnproto/test_readme_example3.cpp b/tests/capnproto/test_readme_example3.cpp new file mode 100644 index 00000000..1e898c40 --- /dev/null +++ b/tests/capnproto/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(capnproto, 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/capnproto/test_ref.cpp b/tests/capnproto/test_ref.cpp new file mode 100644 index 00000000..c9408b53 --- /dev/null +++ b/tests/capnproto/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(capnproto, 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/capnproto/test_rfl_tuple.cpp b/tests/capnproto/test_rfl_tuple.cpp new file mode 100644 index 00000000..bcb7a162 --- /dev/null +++ b/tests/capnproto/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(capnproto, 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/capnproto/test_rfl_variant.cpp b/tests/capnproto/test_rfl_variant.cpp new file mode 100644 index 00000000..45da5b74 --- /dev/null +++ b/tests/capnproto/test_rfl_variant.cpp @@ -0,0 +1,33 @@ +#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; +}; + +struct Shapes { + rfl::Variant> root; +}; + +TEST(capnproto, test_rfl_variant) { + const auto r = Shapes{Rectangle{.height = 10, .width = 5}}; + + write_and_read(r); +} +} // namespace test_variant diff --git a/tests/capnproto/test_save_load.cpp b/tests/capnproto/test_save_load.cpp new file mode 100644 index 00000000..a64a1527 --- /dev/null +++ b/tests/capnproto/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(capnproto, 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::capnproto::save("homer.capnproto", homer1); + + const auto homer2 = rfl::capnproto::load("homer.capnproto").value(); + + const auto string1 = rfl::capnproto::write(homer1); + const auto string2 = rfl::capnproto::write(homer2); + + EXPECT_EQ(string1, string2); +} +} // namespace test_save_load diff --git a/tests/capnproto/test_set.cpp b/tests/capnproto/test_set.cpp new file mode 100644 index 00000000..d2f2732d --- /dev/null +++ b/tests/capnproto/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(capnproto, 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/capnproto/test_shared_ptr.cpp b/tests/capnproto/test_shared_ptr.cpp new file mode 100644 index 00000000..62857583 --- /dev/null +++ b/tests/capnproto/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(capnproto, 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/capnproto/test_size.cpp b/tests/capnproto/test_size.cpp new file mode 100644 index 00000000..e85870e4 --- /dev/null +++ b/tests/capnproto/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(capnproto, 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/capnproto/test_string_map.cpp b/tests/capnproto/test_string_map.cpp new file mode 100644 index 00000000..e1580d59 --- /dev/null +++ b/tests/capnproto/test_string_map.cpp @@ -0,0 +1,25 @@ +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_string_map { + +struct RootStruct { + std::map> root; +}; + +TEST(capnproto, test_string_map) { + RootStruct homer; + homer.root.insert( + std::make_pair("firstName", std::make_unique("Homer"))); + homer.root.insert( + std::make_pair("lastName", std::make_unique("Simpson"))); + + write_and_read(homer); +} +} // namespace test_string_map diff --git a/tests/capnproto/test_tagged_union.cpp b/tests/capnproto/test_tagged_union.cpp new file mode 100644 index 00000000..112cb448 --- /dev/null +++ b/tests/capnproto/test_tagged_union.cpp @@ -0,0 +1,32 @@ +#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; +}; + +struct Shapes { + rfl::TaggedUnion<"shape", Rectangle, Circle, Square> root; +}; + +TEST(capnproto, test_tagged_union) { + const auto r = Shapes{Rectangle{.height = 10, .width = 5}}; + write_and_read(r); +} +} // namespace test_tagged_union diff --git a/tests/capnproto/test_timestamp.cpp b/tests/capnproto/test_timestamp.cpp new file mode 100644 index 00000000..1ea5b48a --- /dev/null +++ b/tests/capnproto/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(capnproto, 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/capnproto/test_tuple.cpp b/tests/capnproto/test_tuple.cpp new file mode 100644 index 00000000..0aa9af4d --- /dev/null +++ b/tests/capnproto/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(capnproto, 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/capnproto/test_tutorial_example.cpp b/tests/capnproto/test_tutorial_example.cpp new file mode 100644 index 00000000..5271148f --- /dev/null +++ b/tests/capnproto/test_tutorial_example.cpp @@ -0,0 +1,70 @@ +#include + +#include +#include +#include +#include +#include + +// #include "write_and_read.hpp" + +/// The basic example from the capnproto C tutorial. +namespace test_tutorial_example { + +const std::string ADDRESS_BOOK_SCHEMA = R"( +@0xb07899ba441fd7ec; + +struct Person { + id @0 :UInt32; + name @1 :Text; + email @2 :Text; + phones @3 :List(PhoneNumber); + + struct PhoneNumber { + number @0 :Text; + type @1 :Type; + + enum Type { + mobile @0; + home @1; + work @2; + } + } + + employment :union { + unemployed @4 :Void; + employer @5 :Text; + school @6 :Text; + selfEmployed @7 :Void; + # We assume that a person is only one of these. + } +} + +struct AddressBook { + people @0 :List(Person); +} +)"; + +enum class Type { mobile, home, work }; + +struct PhoneNumber { + std::string number; + std::string email; + Type type; +}; + +struct Person { + uint32_t id; + std::string name; + std::string email; + // TODO: Employment. +}; + +struct AddressBook { + std::vector people; +}; + +TEST(capnproto, test_tutorial_example) { + rfl::capnproto::Schema::from_string(ADDRESS_BOOK_SCHEMA).value(); +} +} // namespace test_tutorial_example diff --git a/tests/capnproto/test_unique_ptr.cpp b/tests/capnproto/test_unique_ptr.cpp new file mode 100644 index 00000000..ca5964b8 --- /dev/null +++ b/tests/capnproto/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(capnproto, 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/capnproto/test_unique_ptr2.cpp b/tests/capnproto/test_unique_ptr2.cpp new file mode 100644 index 00000000..b3459221 --- /dev/null +++ b/tests/capnproto/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(capnproto, 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/capnproto/test_variant.cpp b/tests/capnproto/test_variant.cpp new file mode 100644 index 00000000..1f68ee2c --- /dev/null +++ b/tests/capnproto/test_variant.cpp @@ -0,0 +1,33 @@ +#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; +}; + +struct Shapes { + std::variant> root; +}; + +TEST(capnproto, test_variant) { + const auto r = Shapes{Rectangle{.height = 10, .width = 5}}; + + write_and_read(r); +} +} // namespace test_variant diff --git a/tests/capnproto/test_variants_in_vectors.cpp b/tests/capnproto/test_variants_in_vectors.cpp new file mode 100644 index 00000000..8e9633fe --- /dev/null +++ b/tests/capnproto/test_variants_in_vectors.cpp @@ -0,0 +1,32 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_variants_in_vectors { + +struct Person { + std::string first_name; + std::string last_name = "Simpson"; + std::vector> children; +}; + +TEST(capnproto, test_variants_in_vectors) { + const std::variant bart = Person{.first_name = "Bart"}; + + const std::variant lisa = Person{.first_name = "Lisa"}; + + const std::variant maggie = + Person{.first_name = "Maggie"}; + + const auto homer = + Person{.first_name = "Homer", + .children = std::vector>( + {bart, lisa, maggie, "Unknown"})}; + + write_and_read(homer); +} +} // namespace test_variants_in_vectors diff --git a/tests/capnproto/test_wstring.cpp b/tests/capnproto/test_wstring.cpp new file mode 100644 index 00000000..a71e1571 --- /dev/null +++ b/tests/capnproto/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(capnproto, 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/capnproto/write_and_read.hpp b/tests/capnproto/write_and_read.hpp new file mode 100644 index 00000000..81692be4 --- /dev/null +++ b/tests/capnproto/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::capnproto::write(_struct); + const auto res = rfl::capnproto::read(serialized1); + EXPECT_TRUE(res && true) << "Test failed on read. Error: " + << res.error().value().what(); + const auto serialized2 = rfl::capnproto::write(res.value()); + EXPECT_EQ(serialized1, serialized2); +} +#endif diff --git a/vcpkg.json b/vcpkg.json index ceaa1802..705b2865 100644 --- a/vcpkg.json +++ b/vcpkg.json @@ -7,6 +7,10 @@ "name": "avro-c", "version>=": "1.11.3" }, + { + "name": "capnproto", + "version>=": "1.0.2#1" + }, { "name": "ctre", "version>=": "3.8"