mirror of
https://codeberg.org/DawnMagnet/reflect-cpp
synced 2026-11-29 22:36:19 +08:00
Added support for Cap'n Proto (#323)
This commit is contained in:
@@ -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: |
|
||||
|
||||
@@ -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: |
|
||||
|
||||
@@ -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: |
|
||||
|
||||
@@ -43,6 +43,7 @@
|
||||
# Output files
|
||||
*.avro
|
||||
*.bson
|
||||
*.capnproto
|
||||
*.cbor
|
||||
*.json
|
||||
*.fb
|
||||
|
||||
+14
-1
@@ -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 $<IF:$<TARGET_EXISTS:mongo::bson_static>,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
|
||||
|
||||
@@ -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<std::byte>`. Supported by BSON, CBOR, flexbuffers, msgpack and UBJSON.
|
||||
- `rfl::Bytestring`: An alias for `std::basic_string<std::byte>`. 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.
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
#include <optional>
|
||||
#include <rfl/avro.hpp>
|
||||
#include <rfl/bson.hpp>
|
||||
#include <rfl/capnproto.hpp>
|
||||
#include <rfl/cbor.hpp>
|
||||
#include <rfl/flexbuf.hpp>
|
||||
#include <rfl/json.hpp>
|
||||
@@ -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<FeatureCollection>();
|
||||
const auto data = rfl::capnproto::write(load_data(), schema);
|
||||
for (auto _ : state) {
|
||||
const auto res = rfl::capnproto::read<FeatureCollection>(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) {
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
#include <optional>
|
||||
#include <rfl/avro.hpp>
|
||||
#include <rfl/bson.hpp>
|
||||
#include <rfl/capnproto.hpp>
|
||||
#include <rfl/cbor.hpp>
|
||||
#include <rfl/flexbuf.hpp>
|
||||
#include <rfl/json.hpp>
|
||||
@@ -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<FeatureCollection>();
|
||||
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) {
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
#include <optional>
|
||||
#include <rfl/avro.hpp>
|
||||
#include <rfl/bson.hpp>
|
||||
#include <rfl/capnproto.hpp>
|
||||
#include <rfl/cbor.hpp>
|
||||
#include <rfl/flexbuf.hpp>
|
||||
#include <rfl/json.hpp>
|
||||
@@ -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<Licenses>();
|
||||
const auto data = rfl::capnproto::write(load_data(), schema);
|
||||
for (auto _ : state) {
|
||||
const auto res = rfl::capnproto::read<Licenses>(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) {
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
#include <optional>
|
||||
#include <rfl/avro.hpp>
|
||||
#include <rfl/bson.hpp>
|
||||
#include <rfl/capnproto.hpp>
|
||||
#include <rfl/cbor.hpp>
|
||||
#include <rfl/flexbuf.hpp>
|
||||
#include <rfl/json.hpp>
|
||||
@@ -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<Licenses>();
|
||||
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) {
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
#include <optional>
|
||||
#include <rfl/avro.hpp>
|
||||
#include <rfl/bson.hpp>
|
||||
#include <rfl/capnproto.hpp>
|
||||
#include <rfl/cbor.hpp>
|
||||
#include <rfl/flexbuf.hpp>
|
||||
#include <rfl/json.hpp>
|
||||
@@ -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<Person>();
|
||||
const auto data = rfl::capnproto::write(load_data(), schema);
|
||||
for (auto _ : state) {
|
||||
const auto res = rfl::capnproto::read<Person>(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) {
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
#include <optional>
|
||||
#include <rfl/avro.hpp>
|
||||
#include <rfl/bson.hpp>
|
||||
#include <rfl/capnproto.hpp>
|
||||
#include <rfl/cbor.hpp>
|
||||
#include <rfl/flexbuf.hpp>
|
||||
#include <rfl/json.hpp>
|
||||
@@ -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<Person>();
|
||||
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) {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
# Cap'n Proto
|
||||
|
||||
For Cap'n Proto support, you must also include the header `<rfl/capnproto.hpp>` 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<Person> children;
|
||||
};
|
||||
```
|
||||
|
||||
A `Person` struct can be serialized to a bytes vector like this:
|
||||
|
||||
```cpp
|
||||
const auto person = Person{...};
|
||||
const std::vector<char> bytes = rfl::capnproto::write(person);
|
||||
```
|
||||
|
||||
You can parse bytes like this:
|
||||
|
||||
```cpp
|
||||
const rfl::Result<Person> result = rfl::capnproto::read<Person>(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<Person>();
|
||||
|
||||
const auto person = Person{...};
|
||||
const std::vector<char> bytes = rfl::capnproto::write(person, schema);
|
||||
|
||||
const rfl::Result<Person> result = rfl::capnproto::read<Person>(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<Person> result = rfl::capnproto::load<Person>("/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<Person> result = rfl::capnproto::read<Person>(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<Person> from_capnproto(const InputVarType& _obj);
|
||||
};
|
||||
```
|
||||
|
||||
And in your source file, you implement `from_capnproto` as follows:
|
||||
|
||||
```cpp
|
||||
rfl::Result<Person> Person::from_capnproto(const InputVarType& _obj) {
|
||||
const auto from_nt = [](auto&& _nt) {
|
||||
return rfl::from_named_tuple<Person>(std::move(_nt));
|
||||
};
|
||||
return rfl::capnproto::read<rfl::named_tuple_t<Person>>(_obj)
|
||||
.transform(from_nt);
|
||||
}
|
||||
```
|
||||
|
||||
This will force the compiler to only compile the Cap'n Proto parsing when the source file is compiled.
|
||||
@@ -48,14 +48,14 @@ Result<internal::wrap_in_rfl_array_t<T>> read(
|
||||
|
||||
/// Parses an object from AVRO using reflection.
|
||||
template <class T, class... Ps>
|
||||
auto read(const char* _bytes, const size_t _size) noexcept {
|
||||
auto read(const char* _bytes, const size_t _size) {
|
||||
const auto schema = to_schema<std::remove_cvref_t<T>, Ps...>();
|
||||
return read<T, Ps...>(_bytes, _size, schema);
|
||||
}
|
||||
|
||||
/// Parses an object from AVRO using reflection.
|
||||
template <class T, class... Ps>
|
||||
auto read(const std::vector<char>& _bytes, const Schema<T>& _schema) {
|
||||
auto read(const std::vector<char>& _bytes, const Schema<T>& _schema) noexcept {
|
||||
return read<T, Ps...>(_bytes.data(), _bytes.size(), _schema);
|
||||
}
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ std::vector<char> write(const auto& _obj, const auto& _schema) noexcept {
|
||||
|
||||
/// Returns AVRO bytes.
|
||||
template <class... Ps>
|
||||
std::vector<char> write(const auto& _obj) noexcept {
|
||||
std::vector<char> write(const auto& _obj) {
|
||||
using T = std::remove_cvref_t<decltype(_obj)>;
|
||||
const auto schema = to_schema<T, Ps...>();
|
||||
return write<Ps...>(_obj, schema);
|
||||
@@ -52,7 +52,7 @@ std::vector<char> write(const auto& _obj) noexcept {
|
||||
|
||||
/// Writes a AVRO into an ostream.
|
||||
template <class... Ps>
|
||||
std::ostream& write(const auto& _obj, std::ostream& _stream) noexcept {
|
||||
std::ostream& write(const auto& _obj, std::ostream& _stream) {
|
||||
auto buffer = write<Ps...>(_obj);
|
||||
_stream.write(buffer.data(), buffer.size());
|
||||
return _stream;
|
||||
|
||||
@@ -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
|
||||
@@ -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 <class ProcessorsType, class... FieldTypes>
|
||||
requires AreReaderAndWriter<capnproto::Reader, capnproto::Writer,
|
||||
NamedTuple<FieldTypes...>>
|
||||
struct Parser<capnproto::Reader, capnproto::Writer, NamedTuple<FieldTypes...>,
|
||||
ProcessorsType>
|
||||
: public NamedTupleParser<
|
||||
capnproto::Reader, capnproto::Writer,
|
||||
/*_ignore_empty_containers=*/false,
|
||||
/*_all_required=*/true,
|
||||
/*_no_field_names=*/ProcessorsType::no_field_names_, ProcessorsType,
|
||||
FieldTypes...> {};
|
||||
|
||||
template <class ProcessorsType, class... Ts>
|
||||
requires AreReaderAndWriter<capnproto::Reader, capnproto::Writer,
|
||||
rfl::Tuple<Ts...>>
|
||||
struct Parser<capnproto::Reader, capnproto::Writer, rfl::Tuple<Ts...>,
|
||||
ProcessorsType>
|
||||
: public TupleParser<capnproto::Reader, capnproto::Writer,
|
||||
/*_ignore_empty_containers=*/false,
|
||||
/*_all_required=*/true, ProcessorsType,
|
||||
rfl::Tuple<Ts...>> {};
|
||||
|
||||
template <class ProcessorsType, class... Ts>
|
||||
requires AreReaderAndWriter<capnproto::Reader, capnproto::Writer,
|
||||
std::tuple<Ts...>>
|
||||
struct Parser<capnproto::Reader, capnproto::Writer, std::tuple<Ts...>,
|
||||
ProcessorsType>
|
||||
: public TupleParser<capnproto::Reader, capnproto::Writer,
|
||||
/*_ignore_empty_containers=*/false,
|
||||
/*_all_required=*/true, ProcessorsType,
|
||||
std::tuple<Ts...>> {};
|
||||
|
||||
template <class ProcessorsType>
|
||||
requires AreReaderAndWriter<capnproto::Reader, capnproto::Writer, Generic>
|
||||
struct Parser<capnproto::Reader, capnproto::Writer, Generic, ProcessorsType> {
|
||||
template <class T>
|
||||
static Result<Generic> read(const capnproto::Reader&, const T&) noexcept {
|
||||
static_assert(always_false_v<T>,
|
||||
"Generics are unsupported in Cap'n Proto.");
|
||||
return Error("Unsupported");
|
||||
}
|
||||
|
||||
template <class P>
|
||||
static void write(const capnproto::Writer&, const Generic&,
|
||||
const P&) noexcept {
|
||||
static_assert(always_false_v<P>,
|
||||
"Generics are unsupported in Cap'n Proto.");
|
||||
}
|
||||
|
||||
template <class T>
|
||||
static schema::Type to_schema(T*) {
|
||||
static_assert(always_false_v<T>,
|
||||
"Generics are unsupported in Cap'n Proto.");
|
||||
return schema::Type{};
|
||||
}
|
||||
};
|
||||
|
||||
template <class T, bool _skip_serialization, bool _skip_deserialization,
|
||||
class ProcessorsType>
|
||||
requires AreReaderAndWriter<
|
||||
capnproto::Reader, capnproto::Writer,
|
||||
internal::Skip<T, _skip_serialization, _skip_deserialization>>
|
||||
struct Parser<capnproto::Reader, capnproto::Writer,
|
||||
internal::Skip<T, _skip_serialization, _skip_deserialization>,
|
||||
ProcessorsType> {
|
||||
using R = capnproto::Reader;
|
||||
using W = capnproto::Writer;
|
||||
|
||||
template <class U>
|
||||
static Result<internal::Skip<T, _skip_serialization, _skip_deserialization>>
|
||||
read(const R&, const U&) noexcept {
|
||||
static_assert(always_false_v<T>,
|
||||
"rfl::Skip is unsupported in Cap'n Proto.");
|
||||
return Error("Unsupported");
|
||||
}
|
||||
|
||||
template <class P>
|
||||
static void write(const W& _w,
|
||||
const internal::Skip<T, _skip_serialization,
|
||||
_skip_deserialization>& _skip,
|
||||
const P& _parent) noexcept {
|
||||
static_assert(always_false_v<P>,
|
||||
"rfl::Skip is unsupported in Cap'n Proto.");
|
||||
}
|
||||
|
||||
template <class U>
|
||||
static schema::Type to_schema(U* _definitions) {
|
||||
static_assert(always_false_v<U>,
|
||||
"rfl::Skip is unsupported in Cap'n Proto.");
|
||||
return schema::Type{};
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace parsing
|
||||
} // namespace rfl
|
||||
|
||||
namespace rfl {
|
||||
namespace capnproto {
|
||||
|
||||
template <class T, class ProcessorsType>
|
||||
using Parser = parsing::Parser<Reader, Writer, T, ProcessorsType>;
|
||||
|
||||
}
|
||||
} // namespace rfl
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,184 @@
|
||||
#ifndef RFL_CAPNPROTO_READER_HPP_
|
||||
#define RFL_CAPNPROTO_READER_HPP_
|
||||
|
||||
#include <capnp/dynamic.h>
|
||||
|
||||
#include <cstddef>
|
||||
#include <exception>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <type_traits>
|
||||
#include <vector>
|
||||
|
||||
#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 <class T>
|
||||
static constexpr bool has_custom_constructor =
|
||||
(requires(InputVarType var) { T::from_capnproto_obj(var); });
|
||||
|
||||
bool is_empty(const InputVarType& _var) const noexcept;
|
||||
|
||||
template <class T>
|
||||
rfl::Result<T> to_basic_type(const InputVarType& _var) const noexcept {
|
||||
const auto type = _var.val_.getType();
|
||||
if constexpr (std::is_same<std::remove_cvref_t<T>, std::string>()) {
|
||||
if (type != capnp::DynamicValue::TEXT) {
|
||||
return Error("Could not cast to string.");
|
||||
}
|
||||
return std::string(_var.val_.as<capnp::Text>().cStr());
|
||||
|
||||
} else if constexpr (std::is_same<std::remove_cvref_t<T>,
|
||||
rfl::Bytestring>()) {
|
||||
if (type != capnp::DynamicValue::DATA) {
|
||||
return Error("Could not cast to bytestring.");
|
||||
}
|
||||
const auto data = _var.val_.as<capnp::Data>();
|
||||
return rfl::Bytestring(internal::ptr_cast<const std::byte*>(data.begin()),
|
||||
data.size());
|
||||
|
||||
} else if constexpr (std::is_same<std::remove_cvref_t<T>, bool>()) {
|
||||
if (type != capnp::DynamicValue::BOOL) {
|
||||
return rfl::Error("Could not cast to boolean.");
|
||||
}
|
||||
return _var.val_.as<bool>();
|
||||
|
||||
} else if constexpr (std::is_floating_point<std::remove_cvref_t<T>>() ||
|
||||
std::is_integral<std::remove_cvref_t<T>>()) {
|
||||
switch (type) {
|
||||
case capnp::DynamicValue::INT:
|
||||
return static_cast<T>(_var.val_.as<int64_t>());
|
||||
|
||||
case capnp::DynamicValue::UINT:
|
||||
return static_cast<T>(_var.val_.as<uint64_t>());
|
||||
|
||||
case capnp::DynamicValue::FLOAT:
|
||||
return static_cast<T>(_var.val_.as<double>());
|
||||
|
||||
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<T>) {
|
||||
if (type != capnp::DynamicValue::ENUM) {
|
||||
return rfl::Error("Could not cast to an enum.");
|
||||
}
|
||||
return T::from_value(_var.val_.as<capnp::DynamicEnum>().getRaw());
|
||||
|
||||
} else {
|
||||
static_assert(rfl::always_false_v<T>, "Unsupported type.");
|
||||
}
|
||||
}
|
||||
|
||||
rfl::Result<InputArrayType> to_array(const InputVarType& _var) const noexcept;
|
||||
|
||||
rfl::Result<InputObjectType> to_object(
|
||||
const InputVarType& _var) const noexcept;
|
||||
|
||||
rfl::Result<InputMapType> to_map(const InputVarType& _var) const noexcept;
|
||||
|
||||
rfl::Result<InputUnionType> to_union(const InputVarType& _var) const noexcept;
|
||||
|
||||
template <class ArrayReader>
|
||||
std::optional<Error> 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 <class MapReader>
|
||||
std::optional<Error> read_map(const MapReader& _map_reader,
|
||||
const InputMapType& _map) const noexcept {
|
||||
try {
|
||||
const auto entries = _map.val_.get("entries").as<capnp::DynamicList>();
|
||||
for (auto entry : entries) {
|
||||
auto s = entry.template as<capnp::DynamicStruct>();
|
||||
const char* key = s.get("key").as<capnp::Text>().cStr();
|
||||
_map_reader.read(std::string_view(key), InputVarType{s.get("value")});
|
||||
}
|
||||
return std::nullopt;
|
||||
} catch (std::exception& e) {
|
||||
return Error{e.what()};
|
||||
}
|
||||
}
|
||||
|
||||
template <class ObjectReader>
|
||||
std::optional<Error> 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 <class VariantType, class UnionReaderType>
|
||||
rfl::Result<VariantType> 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 <class T>
|
||||
rfl::Result<T> 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<std::pair<capnp::StructSchema::Field, size_t>>
|
||||
identify_discriminant(const InputUnionType& _union) const noexcept;
|
||||
};
|
||||
|
||||
} // namespace rfl::capnproto
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,41 @@
|
||||
#ifndef RFL_CAPNPROTO_SCHEMA_HPP_
|
||||
#define RFL_CAPNPROTO_SCHEMA_HPP_
|
||||
|
||||
#include <capnp/schema-parser.h>
|
||||
|
||||
#include <type_traits>
|
||||
|
||||
#include "../Ref.hpp"
|
||||
#include "SchemaImpl.hpp"
|
||||
|
||||
namespace rfl::capnproto {
|
||||
|
||||
template <class T>
|
||||
class Schema {
|
||||
public:
|
||||
using Type = std::remove_cvref_t<T>;
|
||||
|
||||
Schema(const std::string& _str) : impl_(Ref<SchemaImpl>::make(_str)) {}
|
||||
|
||||
static Result<Schema<T>> from_string(const std::string& _str) noexcept {
|
||||
try {
|
||||
return Schema<T>(_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<SchemaImpl> impl_;
|
||||
};
|
||||
|
||||
} // namespace rfl::capnproto
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,43 @@
|
||||
#ifndef RFL_CAPNPROTO_SCHEMAIMPL_HPP_
|
||||
#define RFL_CAPNPROTO_SCHEMAIMPL_HPP_
|
||||
|
||||
#include <capnp/schema-parser.h>
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#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<capnp::SchemaParser> schema_parser_;
|
||||
|
||||
/// The actual schema
|
||||
Box<capnp::ParsedSchema> schema_;
|
||||
};
|
||||
|
||||
} // namespace rfl::capnproto
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,273 @@
|
||||
#ifndef RFL_CAPNPROTO_WRITER_HPP_
|
||||
#define RFL_CAPNPROTO_WRITER_HPP_
|
||||
|
||||
#include <capnp/dynamic.h>
|
||||
#include <kj/array.h>
|
||||
|
||||
#include <bit>
|
||||
#include <cstdint>
|
||||
#include <exception>
|
||||
#include <map>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <type_traits>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
#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 <class T>
|
||||
OutputArrayType array_as_root(const T _size) const noexcept {
|
||||
static_assert(always_false_v<T>,
|
||||
"In Cap'n Proto, root values must always be structs.");
|
||||
throw std::runtime_error("Unsupported.");
|
||||
}
|
||||
|
||||
template <class T>
|
||||
OutputMapType map_as_root(const T _size) const noexcept {
|
||||
static_assert(always_false_v<T>,
|
||||
"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 <class T = int>
|
||||
OutputVarType null_as_root() const noexcept {
|
||||
static_assert(always_false_v<T>,
|
||||
"In Cap'n Proto, root values must always be structs.");
|
||||
throw std::runtime_error("Unsupported.");
|
||||
}
|
||||
|
||||
template <class T = int>
|
||||
OutputUnionType union_as_root() const noexcept {
|
||||
static_assert(always_false_v<T>,
|
||||
"In Cap'n Proto, root values must always be structs.");
|
||||
throw std::runtime_error("Unsupported.");
|
||||
}
|
||||
|
||||
template <class T>
|
||||
OutputVarType value_as_root(const T& _var) const noexcept {
|
||||
static_assert(always_false_v<T>,
|
||||
"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 <class T>
|
||||
OutputVarType add_value_to_array(const T& _var,
|
||||
OutputArrayType* _parent) const noexcept {
|
||||
if constexpr (std::is_same<std::remove_cvref_t<T>, std::string>()) {
|
||||
_parent->val_.set(_parent->ix_++, _var.c_str());
|
||||
|
||||
} else if constexpr (std::is_same<std::remove_cvref_t<T>,
|
||||
rfl::Bytestring>()) {
|
||||
const auto array_ptr = kj::ArrayPtr<const kj::byte>(
|
||||
internal::ptr_cast<const unsigned char*>(_var.data()), _var.size());
|
||||
_parent->val_.set(_parent->ix_++, capnp::Data::Reader(array_ptr));
|
||||
|
||||
} else if constexpr (std::is_floating_point<std::remove_cvref_t<T>>() ||
|
||||
std::is_same<std::remove_cvref_t<T>, bool>()) {
|
||||
_parent->val_.set(_parent->ix_++, _var);
|
||||
|
||||
} else if constexpr (std::is_integral<std::remove_cvref_t<T>>()) {
|
||||
_parent->val_.set(_parent->ix_++, static_cast<std::int64_t>(_var));
|
||||
|
||||
} else if constexpr (internal::is_literal_v<T>) {
|
||||
return add_value_to_array(_var.value(), _parent);
|
||||
|
||||
} else {
|
||||
static_assert(rfl::always_false_v<T>, "Unsupported type.");
|
||||
}
|
||||
return OutputVarType{};
|
||||
}
|
||||
|
||||
template <class T>
|
||||
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<capnp::DynamicList>()};
|
||||
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 <class T>
|
||||
OutputVarType add_value_to_object(const std::string_view& _name,
|
||||
const T& _var,
|
||||
OutputObjectType* _parent) const noexcept {
|
||||
if constexpr (std::is_same<std::remove_cvref_t<T>, std::string>()) {
|
||||
_parent->val_.set(_name.data(), _var.c_str());
|
||||
|
||||
} else if constexpr (std::is_same<std::remove_cvref_t<T>,
|
||||
rfl::Bytestring>()) {
|
||||
const auto array_ptr = kj::ArrayPtr<const kj::byte>(
|
||||
internal::ptr_cast<const unsigned char*>(_var.data()), _var.size());
|
||||
_parent->val_.set(_name.data(), capnp::Data::Reader(array_ptr));
|
||||
|
||||
} else if constexpr (std::is_floating_point<std::remove_cvref_t<T>>() ||
|
||||
std::is_same<std::remove_cvref_t<T>, bool>()) {
|
||||
_parent->val_.set(_name.data(), _var);
|
||||
|
||||
} else if constexpr (std::is_integral<std::remove_cvref_t<T>>()) {
|
||||
_parent->val_.set(_name.data(), static_cast<std::int64_t>(_var));
|
||||
|
||||
} else if constexpr (internal::is_literal_v<T>) {
|
||||
return add_value_to_object(_name, _var.value(), _parent);
|
||||
|
||||
} else {
|
||||
static_assert(rfl::always_false_v<T>, "Unsupported type.");
|
||||
}
|
||||
return OutputVarType{};
|
||||
}
|
||||
|
||||
template <class T>
|
||||
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::remove_cvref_t<T>, std::string>()) {
|
||||
_parent->val_.set(field, _var.c_str());
|
||||
|
||||
} else if constexpr (std::is_same<std::remove_cvref_t<T>,
|
||||
rfl::Bytestring>()) {
|
||||
const auto array_ptr = kj::ArrayPtr<const kj::byte>(
|
||||
internal::ptr_cast<const unsigned char*>(_var.data()), _var.size());
|
||||
_parent->val_.set(field, capnp::Data::Reader(array_ptr));
|
||||
|
||||
} else if constexpr (std::is_floating_point<std::remove_cvref_t<T>>() ||
|
||||
std::is_same<std::remove_cvref_t<T>, bool>()) {
|
||||
_parent->val_.set(field, _var);
|
||||
|
||||
} else if constexpr (std::is_integral<std::remove_cvref_t<T>>()) {
|
||||
_parent->val_.set(field, static_cast<std::int64_t>(_var));
|
||||
|
||||
} else if constexpr (internal::is_literal_v<T>) {
|
||||
return add_value_to_union(_index, _var.value(), _parent);
|
||||
|
||||
} else {
|
||||
static_assert(rfl::always_false_v<T>, "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
|
||||
@@ -0,0 +1,29 @@
|
||||
#ifndef RFL_CAPNPROTO_GET_ROOT_NAME_HPP_
|
||||
#define RFL_CAPNPROTO_GET_ROOT_NAME_HPP_
|
||||
|
||||
#include <string>
|
||||
|
||||
#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 <class T, class... Ps>
|
||||
inline std::string get_root_name() {
|
||||
if constexpr (internal::has_reflection_type_v<T>) {
|
||||
return get_root_name<std::remove_cvref_t<typename T::ReflectionType>>();
|
||||
} else if constexpr (internal::has_custom_parser<Reader, Writer, T,
|
||||
Processors<Ps...>>) {
|
||||
return get_root_name<
|
||||
typename Parser<T, Processors<Ps...>>::CustomParserHelperStruct>();
|
||||
} else {
|
||||
return internal::strings::to_pascal_case(parsing::make_type_name<T>());
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace rfl::capnproto
|
||||
|
||||
#endif
|
||||
@@ -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<decltype(_v)>;
|
||||
return std::is_same<T, parsing::schema::Type::Object>() ||
|
||||
std::is_same<T, parsing::schema::Type::AnyOf>() ||
|
||||
std::is_same<T, parsing::schema::Type::StringMap>() ||
|
||||
std::is_same<T, parsing::schema::Type::Literal>();
|
||||
});
|
||||
}
|
||||
|
||||
} // namespace rfl::capnproto
|
||||
|
||||
#endif
|
||||
|
||||
@@ -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 <class T, class... Ps>
|
||||
Result<T> load(const std::string& _fname) {
|
||||
const auto read_bytes = [](const auto& _bytes) {
|
||||
return read<T, Ps...>(_bytes);
|
||||
};
|
||||
return rfl::io::load_bytes(_fname).and_then(read_bytes);
|
||||
}
|
||||
|
||||
} // namespace capnproto
|
||||
} // namespace rfl
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,80 @@
|
||||
#ifndef RFL_CAPNPROTO_READ_HPP_
|
||||
#define RFL_CAPNPROTO_READ_HPP_
|
||||
|
||||
#include <capnp/dynamic.h>
|
||||
#include <capnp/serialize-packed.h>
|
||||
#include <kj/io.h>
|
||||
|
||||
#include <bit>
|
||||
#include <istream>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
|
||||
#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 <class T, class... Ps>
|
||||
auto read(const InputVarType& _obj) {
|
||||
const auto r = Reader();
|
||||
return Parser<T, Processors<SnakeCaseToCamelCase, Ps...>>::read(r, _obj);
|
||||
}
|
||||
|
||||
/// Parses an object from CAPNPROTO using reflection.
|
||||
template <class T, class... Ps>
|
||||
Result<internal::wrap_in_rfl_array_t<T>> read(const char* _bytes,
|
||||
const size_t _size,
|
||||
const Schema<T>& _schema) {
|
||||
const auto array_ptr = kj::ArrayPtr<const kj::byte>(
|
||||
internal::ptr_cast<const kj::byte*>(_bytes), _size);
|
||||
auto input_stream = kj::ArrayInputStream(array_ptr);
|
||||
auto message_reader = capnp::PackedMessageReader(input_stream);
|
||||
const auto root_name = get_root_name<std::remove_cv_t<T>, Ps...>();
|
||||
const auto root_schema = _schema.value().getNested(root_name.c_str());
|
||||
const auto input_var = InputVarType{
|
||||
message_reader.getRoot<capnp::DynamicStruct>(root_schema.asStruct())};
|
||||
return read<T, Ps...>(input_var);
|
||||
}
|
||||
|
||||
/// Parses an object from CAPNPROTO using reflection.
|
||||
template <class T, class... Ps>
|
||||
auto read(const char* _bytes, const size_t _size) {
|
||||
const auto schema = to_schema<std::remove_cvref_t<T>, Ps...>();
|
||||
return read<T, Ps...>(_bytes, _size, schema);
|
||||
}
|
||||
|
||||
/// Parses an object from CAPNPROTO using reflection.
|
||||
template <class T, class... Ps>
|
||||
auto read(const std::vector<char>& _bytes, const Schema<T>& _schema) noexcept {
|
||||
return read<T, Ps...>(_bytes.data(), _bytes.size(), _schema);
|
||||
}
|
||||
|
||||
/// Parses an object from CAPNPROTO using reflection.
|
||||
template <class T, class... Ps>
|
||||
auto read(const std::vector<char>& _bytes) {
|
||||
return read<T, Ps...>(_bytes.data(), _bytes.size());
|
||||
}
|
||||
|
||||
/// Parses an object from a stream.
|
||||
template <class T, class... Ps>
|
||||
auto read(std::istream& _stream) {
|
||||
std::istreambuf_iterator<char> begin(_stream), end;
|
||||
auto bytes = std::vector<char>(begin, end);
|
||||
return read<T, Ps...>(bytes.data(), bytes.size());
|
||||
}
|
||||
|
||||
} // namespace rfl::capnproto
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,25 @@
|
||||
#ifndef RFL_CAPNPROTO_SAVE_HPP_
|
||||
#define RFL_CAPNPROTO_SAVE_HPP_
|
||||
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
#include "../Result.hpp"
|
||||
#include "../io/save_bytes.hpp"
|
||||
#include "write.hpp"
|
||||
|
||||
namespace rfl::capnproto {
|
||||
|
||||
template <class... Ps>
|
||||
Result<Nothing> save(const std::string& _fname, const auto& _obj) {
|
||||
const auto write_func = [](const auto& _obj,
|
||||
std::ostream& _stream) -> std::ostream& {
|
||||
return write<Ps...>(_obj, _stream);
|
||||
};
|
||||
return rfl::io::save_bytes(_fname, _obj, write_func);
|
||||
}
|
||||
|
||||
} // namespace rfl::capnproto
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,49 @@
|
||||
#ifndef RFL_CAPNPROTO_SCHEMA_CAPNPROTOTYPES_HPP_
|
||||
#define RFL_CAPNPROTO_SCHEMA_CAPNPROTOTYPES_HPP_
|
||||
|
||||
#include <map>
|
||||
|
||||
#include "Type.hpp"
|
||||
|
||||
namespace rfl::capnproto::schema {
|
||||
|
||||
struct CapnProtoTypes {
|
||||
bool has_maps_ = false;
|
||||
std::map<std::string, schema::Type> structs_;
|
||||
std::map<std::string, schema::Type> enums_;
|
||||
std::map<std::string, schema::Type> tuples_;
|
||||
std::map<std::string, schema::Type> 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<std::string, schema::Type>& _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
|
||||
@@ -0,0 +1,88 @@
|
||||
#ifndef RFL_CAPNPROTO_SCHEMA_TYPE_HPP_
|
||||
#define RFL_CAPNPROTO_SCHEMA_TYPE_HPP_
|
||||
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
|
||||
#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<std::string> fields;
|
||||
};
|
||||
|
||||
struct List {
|
||||
rfl::Ref<Type> type;
|
||||
};
|
||||
|
||||
struct Map {
|
||||
rfl::Ref<Type> type;
|
||||
};
|
||||
|
||||
struct Reference {
|
||||
std::string type_name;
|
||||
};
|
||||
|
||||
struct Struct {
|
||||
std::string name;
|
||||
std::vector<std::pair<std::string, Type>> fields;
|
||||
};
|
||||
|
||||
struct Union {
|
||||
std::string name;
|
||||
std::vector<std::pair<std::string, Type>> fields;
|
||||
};
|
||||
|
||||
using ReflectionType =
|
||||
rfl::Variant<Void, Bool, Int8, Int16, Int32, Int64, UInt8, UInt16, UInt32,
|
||||
UInt64, Float32, Float64, Data, Enum, List, Map, Reference,
|
||||
Struct, Text, Union>;
|
||||
|
||||
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
|
||||
@@ -0,0 +1,51 @@
|
||||
#ifndef RFL_CAPNPROTO_TOSCHEMA_HPP_
|
||||
#define RFL_CAPNPROTO_TOSCHEMA_HPP_
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
|
||||
#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 <class T, class... Ps>
|
||||
struct SchemaHolder {
|
||||
static SchemaHolder<T, Ps...> make() noexcept {
|
||||
const auto internal_schema =
|
||||
parsing::schema::make<Reader, Writer, T,
|
||||
Processors<SnakeCaseToCamelCase, Ps...>>();
|
||||
const auto str = to_string_representation(internal_schema);
|
||||
return SchemaHolder<T, Ps...>{Schema<T>::from_string(str)};
|
||||
}
|
||||
|
||||
rfl::Result<Schema<T>> schema_;
|
||||
};
|
||||
|
||||
template <class T, class... Ps>
|
||||
static const SchemaHolder<T, Ps...> schema_holder =
|
||||
SchemaHolder<T, Ps...>::make();
|
||||
|
||||
/// Returns the Cap'n Proto schema for a class.
|
||||
template <class T, class... Ps>
|
||||
Schema<T> to_schema() {
|
||||
return schema_holder<T, Ps...>.schema_.value();
|
||||
}
|
||||
} // namespace rfl::capnproto
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,72 @@
|
||||
#ifndef RFL_CAPNPROTO_WRITE_HPP_
|
||||
#define RFL_CAPNPROTO_WRITE_HPP_
|
||||
|
||||
#include <capnp/dynamic.h>
|
||||
#include <capnp/message.h>
|
||||
#include <capnp/schema-parser.h>
|
||||
#include <capnp/schema.h>
|
||||
#include <capnp/serialize-packed.h>
|
||||
#include <kj/io.h>
|
||||
|
||||
#include <bit>
|
||||
#include <cstdint>
|
||||
#include <ostream>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
|
||||
#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 <class... Ps>
|
||||
std::vector<char> write(const auto& _obj, const auto& _schema) {
|
||||
using T = std::remove_cvref_t<decltype(_obj)>;
|
||||
using U = typename std::remove_cvref_t<decltype(_schema)>::Type;
|
||||
using ParentType = parsing::Parent<Writer>;
|
||||
static_assert(std::is_same<T, U>(),
|
||||
"The schema must be compatible with the type to write.");
|
||||
const auto root_name = get_root_name<T, Ps...>();
|
||||
const auto root_schema = _schema.value().getNested(root_name.c_str());
|
||||
capnp::MallocMessageBuilder message_builder;
|
||||
auto root =
|
||||
message_builder.initRoot<capnp::DynamicStruct>(root_schema.asStruct());
|
||||
const auto writer = Writer(&root);
|
||||
Parser<T, Processors<SnakeCaseToCamelCase, Ps...>>::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<char>(internal::ptr_cast<char*>(arr_ptr.begin()),
|
||||
internal::ptr_cast<char*>(arr_ptr.end()));
|
||||
}
|
||||
|
||||
/// Returns CAPNPROTO bytes.
|
||||
template <class... Ps>
|
||||
std::vector<char> write(const auto& _obj) {
|
||||
using T = std::remove_cvref_t<decltype(_obj)>;
|
||||
const auto schema = to_schema<T, Ps...>();
|
||||
return write<Ps...>(_obj, schema);
|
||||
}
|
||||
|
||||
/// Writes a CAPNPROTO into an ostream.
|
||||
template <class... Ps>
|
||||
std::ostream& write(const auto& _obj, std::ostream& _stream) {
|
||||
auto buffer = write<Ps...>(_obj);
|
||||
_stream.write(buffer.data(), buffer.size());
|
||||
return _stream;
|
||||
}
|
||||
|
||||
} // namespace rfl::capnproto
|
||||
|
||||
#endif
|
||||
@@ -8,8 +8,7 @@
|
||||
#include <type_traits>
|
||||
|
||||
#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"
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
#ifndef RFL_INTERNAL_HASCUSTOMPARSER_HPP_
|
||||
#define RFL_INTERNAL_HASCUSTOMPARSER_HPP_
|
||||
|
||||
#include <type_traits>
|
||||
|
||||
#include "../parsing/Parser.hpp"
|
||||
|
||||
namespace rfl::internal {
|
||||
|
||||
template <class R, class W, class T, class ProcessorsType>
|
||||
concept has_custom_parser = requires(
|
||||
const T& _t, const typename parsing::Parser<
|
||||
R, W, T, ProcessorsType>::CustomParserHelperStruct& _h) {
|
||||
{
|
||||
std::remove_cvref_t<decltype(_h)>::from_class(_t)
|
||||
} -> std::same_as<std::remove_cvref_t<decltype(_h)>>;
|
||||
|
||||
{ _h.to_class() } -> std::same_as<T>;
|
||||
};
|
||||
|
||||
} // namespace rfl::internal
|
||||
|
||||
#endif
|
||||
@@ -4,7 +4,8 @@
|
||||
#include <type_traits>
|
||||
|
||||
#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 <class StructType, class... Ps>
|
||||
struct Processed<StructType, Processors<Ps...>> {
|
||||
using NamedTupleType = named_tuple_t<StructType>;
|
||||
using type = typename std::invoke_result<
|
||||
decltype(Processors<Ps...>::template process<StructType, NamedTupleType>),
|
||||
NamedTupleType>::type;
|
||||
using PtrNamedTupleType = ptr_named_tuple_t<StructType>;
|
||||
using type = typename remove_ptrs_nt<
|
||||
std::invoke_result_t<decltype(Processors<Ps...>::template process<
|
||||
StructType, PtrNamedTupleType>),
|
||||
PtrNamedTupleType>>::NamedTupleType;
|
||||
};
|
||||
|
||||
template <class StructType, class ProcessorsType>
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
#ifndef RFL_INTERNAL_REMOVE_PTRS_NT_HPP_
|
||||
#define RFL_INTERNAL_REMOVE_PTRS_NT_HPP_
|
||||
|
||||
#include <functional>
|
||||
#include <type_traits>
|
||||
|
||||
#include "../Field.hpp"
|
||||
#include "StringLiteral.hpp"
|
||||
#include "wrap_in_rfl_array_t.hpp"
|
||||
|
||||
namespace rfl::internal {
|
||||
|
||||
template <class T>
|
||||
struct remove_ptr;
|
||||
|
||||
template <internal::StringLiteral _name, class T>
|
||||
struct remove_ptr<Field<_name, T>> {
|
||||
using FieldType =
|
||||
Field<_name, internal::wrap_in_rfl_array_t<
|
||||
std::remove_cvref_t<std::remove_pointer_t<T>>>>;
|
||||
};
|
||||
|
||||
template <class T>
|
||||
struct remove_ptrs_nt;
|
||||
|
||||
template <class... FieldTypes>
|
||||
struct remove_ptrs_nt<NamedTuple<FieldTypes...>> {
|
||||
using NamedTupleType =
|
||||
NamedTuple<typename remove_ptr<FieldTypes>::FieldType...>;
|
||||
};
|
||||
|
||||
} // namespace rfl::internal
|
||||
|
||||
#endif
|
||||
@@ -1,28 +0,0 @@
|
||||
#ifndef RFL_INTERNAL_STRINGS_JOIN_HPP_
|
||||
#define RFL_INTERNAL_STRINGS_JOIN_HPP_
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace rfl {
|
||||
namespace internal {
|
||||
namespace strings {
|
||||
|
||||
/// Joins a string using the delimiter
|
||||
inline std::string join(const std::string& _delimiter,
|
||||
const std::vector<std::string>& _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
|
||||
@@ -1,28 +0,0 @@
|
||||
#ifndef RFL_INTERNAL_STRINGS_REPLACE_ALL_HPP_
|
||||
#define RFL_INTERNAL_STRINGS_REPLACE_ALL_HPP_
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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
|
||||
@@ -1,29 +0,0 @@
|
||||
#ifndef RFL_INTERNAL_STRINGS_SPLIT_HPP_
|
||||
#define RFL_INTERNAL_STRINGS_SPLIT_HPP_
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace rfl {
|
||||
namespace internal {
|
||||
namespace strings {
|
||||
|
||||
/// Splits a string alongside the delimiter
|
||||
inline std::vector<std::string> split(const std::string& _str,
|
||||
const std::string& _delimiter) {
|
||||
auto str = _str;
|
||||
size_t pos = 0;
|
||||
std::vector<std::string> 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
|
||||
@@ -0,0 +1,29 @@
|
||||
#ifndef RFL_INTERNAL_STRINGS_STRINGS_HPP_
|
||||
#define RFL_INTERNAL_STRINGS_STRINGS_HPP_
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace rfl::internal::strings {
|
||||
|
||||
/// Joins a series of strings.
|
||||
std::string join(const std::string& _delimiter,
|
||||
const std::vector<std::string>& _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<std::string> 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
|
||||
@@ -15,19 +15,36 @@ consteval char to_upper() {
|
||||
}
|
||||
}
|
||||
|
||||
template <char c>
|
||||
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 <internal::StringLiteral _name, bool _capitalize, size_t _i = 0,
|
||||
char... chars>
|
||||
consteval auto transform_snake_case() {
|
||||
if constexpr (_i == _name.arr_.size()) {
|
||||
return StringLiteral<sizeof...(chars) + 1>(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]>();
|
||||
|
||||
@@ -6,38 +6,18 @@
|
||||
#include <type_traits>
|
||||
|
||||
#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 <class T>
|
||||
struct remove_ptr;
|
||||
|
||||
template <internal::StringLiteral _name, class T>
|
||||
struct remove_ptr<Field<_name, T>> {
|
||||
using FieldType =
|
||||
Field<_name, internal::wrap_in_rfl_array_t<
|
||||
std::remove_cvref_t<std::remove_pointer_t<T>>>>;
|
||||
};
|
||||
|
||||
template <class T>
|
||||
struct remove_ptrs_nt;
|
||||
|
||||
template <class... FieldTypes>
|
||||
struct remove_ptrs_nt<NamedTuple<FieldTypes...>> {
|
||||
using NamedTupleType =
|
||||
NamedTuple<typename remove_ptr<FieldTypes>::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 <class T>
|
||||
using named_tuple_t =
|
||||
typename remove_ptrs_nt<internal::ptr_named_tuple_t<T>>::NamedTupleType;
|
||||
using named_tuple_t = typename internal::remove_ptrs_nt<
|
||||
internal::ptr_named_tuple_t<T>>::NamedTupleType;
|
||||
|
||||
} // namespace rfl
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#ifndef RFL_PARSING_CUSTOMPARSER_HPP_
|
||||
#define RFL_PARSING_CUSTOMPARSER_HPP_
|
||||
|
||||
#include <concepts>
|
||||
#include <exception>
|
||||
#include <tuple>
|
||||
|
||||
@@ -16,6 +17,8 @@ namespace parsing {
|
||||
template <class R, class W, class ProcessorsType, class OriginalClass,
|
||||
class HelperStruct>
|
||||
struct CustomParser {
|
||||
using CustomParserHelperStruct = std::remove_cvref_t<HelperStruct>;
|
||||
|
||||
static Result<OriginalClass> read(const R& _r, const auto& _var) noexcept {
|
||||
const auto to_class = [](auto&& _h) -> Result<OriginalClass> {
|
||||
try {
|
||||
@@ -32,21 +35,22 @@ struct CustomParser {
|
||||
return Error(e.what());
|
||||
}
|
||||
};
|
||||
return Parser<R, W, HelperStruct, ProcessorsType>::read(_r, _var).and_then(
|
||||
to_class);
|
||||
return Parser<R, W, CustomParserHelperStruct, ProcessorsType>::read(_r,
|
||||
_var)
|
||||
.and_then(to_class);
|
||||
}
|
||||
|
||||
template <class P>
|
||||
static auto write(const W& _w, const OriginalClass& _p,
|
||||
const P& _parent) noexcept {
|
||||
Parser<R, W, HelperStruct, ProcessorsType>::write(
|
||||
Parser<R, W, CustomParserHelperStruct, ProcessorsType>::write(
|
||||
_w, HelperStruct::from_class(_p), _parent);
|
||||
}
|
||||
|
||||
static schema::Type to_schema(
|
||||
std::map<std::string, schema::Type>* _definitions) {
|
||||
return Parser<R, W, std::remove_cvref_t<HelperStruct>,
|
||||
ProcessorsType>::to_schema(_definitions);
|
||||
return Parser<R, W, CustomParserHelperStruct, ProcessorsType>::to_schema(
|
||||
_definitions);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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 <class R, class W, class T, class ProcessorsType>
|
||||
@@ -265,16 +265,6 @@ struct Parser {
|
||||
.validation_ = ValidationType::template to_schema<ReflectionType>()}};
|
||||
}
|
||||
|
||||
template <class U>
|
||||
static std::string make_type_name() {
|
||||
if constexpr (is_tagged_union_wrapper_v<U>) {
|
||||
return replace_non_alphanumeric(type_name_t<typename U::Type>().str() +
|
||||
"__tagged");
|
||||
} else {
|
||||
return replace_non_alphanumeric(type_name_t<U>().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
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -46,7 +46,7 @@ struct TupleParser {
|
||||
|
||||
} else {
|
||||
const auto parse = [&](const InputArrayType& _arr) -> Result<TupleType> {
|
||||
alignas(TupleType) unsigned char buf[sizeof(TupleType)];
|
||||
alignas(TupleType) unsigned char buf[sizeof(TupleType)]{};
|
||||
auto ptr = internal::ptr_cast<TupleType*>(&buf);
|
||||
const auto tuple_reader =
|
||||
TupleReader<R, W, TupleType, _ignore_empty_containers,
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
#ifndef RFL_PARSING_MAKETYPENAME_HPP_
|
||||
#define RFL_PARSING_MAKETYPENAME_HPP_
|
||||
|
||||
#include "../type_name_t.hpp"
|
||||
#include "is_tagged_union_wrapper.hpp"
|
||||
|
||||
namespace rfl {
|
||||
namespace parsing {
|
||||
|
||||
inline std::string replace_non_alphanumeric(std::string _str) {
|
||||
for (auto& ch : _str) {
|
||||
ch = std::isalnum(ch) ? ch : '_';
|
||||
}
|
||||
return _str;
|
||||
}
|
||||
|
||||
template <class U>
|
||||
static std::string make_type_name() {
|
||||
if constexpr (is_tagged_union_wrapper_v<U>) {
|
||||
return replace_non_alphanumeric(type_name_t<typename U::Type>().str() +
|
||||
"__tagged");
|
||||
} else {
|
||||
return replace_non_alphanumeric(type_name_t<U>().str());
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace parsing
|
||||
} // namespace rfl
|
||||
|
||||
#endif
|
||||
@@ -13,7 +13,7 @@
|
||||
namespace rfl::parsing::schemaful {
|
||||
|
||||
template <int _i>
|
||||
consteval auto to_field_name() {
|
||||
inline consteval auto to_field_name() {
|
||||
return internal::StringLiteral<5>('f',
|
||||
static_cast<char>('0' + ((_i / 100) % 10)),
|
||||
static_cast<char>('0' + ((_i / 10) % 10)),
|
||||
@@ -21,7 +21,7 @@ consteval auto to_field_name() {
|
||||
}
|
||||
|
||||
template <int _i>
|
||||
auto to_field(const auto& _t) {
|
||||
inline auto to_field(const auto& _t) {
|
||||
using T = std::remove_cvref_t<decltype(_t)>;
|
||||
return rfl::Field<to_field_name<_i>(), const T*>(&_t);
|
||||
}
|
||||
|
||||
@@ -7,21 +7,9 @@
|
||||
|
||||
namespace rfl::parsing::schemaful {
|
||||
|
||||
std::string to_field_name(const size_t _i) {
|
||||
return std::string({'f', static_cast<char>('0' + ((_i / 100) % 10)),
|
||||
static_cast<char>('0' + ((_i / 10) % 10)),
|
||||
static_cast<char>('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
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "../internal/strings/replace_all.hpp"
|
||||
#include "../internal/strings/strings.hpp"
|
||||
|
||||
namespace rfl::parsing {
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
@@ -0,0 +1,58 @@
|
||||
#include "rfl/capnproto/Reader.hpp"
|
||||
|
||||
#include "rfl/parsing/schemaful/IsSchemafulReader.hpp"
|
||||
|
||||
namespace rfl::capnproto {
|
||||
|
||||
static_assert(parsing::schemaful::IsSchemafulReader<Reader>,
|
||||
"This must be a schemaful reader.");
|
||||
|
||||
std::optional<std::pair<capnp::StructSchema::Field, size_t>>
|
||||
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::InputArrayType> 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<capnp::DynamicList>()};
|
||||
}
|
||||
|
||||
rfl::Result<Reader::InputObjectType> 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<capnp::DynamicStruct>()};
|
||||
}
|
||||
|
||||
rfl::Result<Reader::InputMapType> 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<capnp::DynamicStruct>()};
|
||||
}
|
||||
|
||||
rfl::Result<Reader::InputUnionType> 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<capnp::DynamicStruct>()};
|
||||
}
|
||||
|
||||
} // namespace rfl::capnproto
|
||||
@@ -0,0 +1,23 @@
|
||||
#include "rfl/capnproto/SchemaImpl.hpp"
|
||||
|
||||
#include <capnp/schema-parser.h>
|
||||
#include <capnp/schema.h>
|
||||
|
||||
namespace rfl::capnproto {
|
||||
|
||||
SchemaImpl::SchemaImpl(const std::string& _str)
|
||||
: str_(_str),
|
||||
schema_parser_(Box<capnp::SchemaParser>::make()),
|
||||
schema_(Box<capnp::ParsedSchema>::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
|
||||
@@ -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 <functional>
|
||||
#include <type_traits>
|
||||
|
||||
#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<decltype(_r)>;
|
||||
if constexpr (std::is_same<R, Type::Union>()) {
|
||||
// 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<decltype(_union_field)>;
|
||||
if constexpr (std::is_same<U, Type::Union>()) {
|
||||
*_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<decltype(_v)>;
|
||||
if constexpr (std::is_same<T, Struct>() || std::is_same<T, Union>() ||
|
||||
std::is_same<T, Enum>()) {
|
||||
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
|
||||
@@ -0,0 +1,174 @@
|
||||
#include "rfl/capnproto/Writer.hpp"
|
||||
|
||||
#include <stdexcept>
|
||||
|
||||
#include "rfl/parsing/schemaful/IsSchemafulWriter.hpp"
|
||||
|
||||
namespace rfl::capnproto {
|
||||
|
||||
static_assert(parsing::schemaful::IsSchemafulWriter<Writer>,
|
||||
"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<capnp::DynamicStruct>()};
|
||||
}
|
||||
|
||||
Writer::OutputArrayType Writer::add_array_to_array(
|
||||
const size_t _size, OutputArrayType* _parent) const noexcept {
|
||||
return OutputArrayType{
|
||||
_parent->val_.init(_parent->ix_++, _size).as<capnp::DynamicList>()};
|
||||
}
|
||||
|
||||
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<capnp::DynamicList>(),
|
||||
.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<capnp::DynamicList>()};
|
||||
}
|
||||
|
||||
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<capnp::DynamicList>()};
|
||||
}
|
||||
|
||||
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<capnp::DynamicStruct>()};
|
||||
}
|
||||
|
||||
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<capnp::DynamicList>(),
|
||||
.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<capnp::DynamicStruct>()};
|
||||
}
|
||||
|
||||
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<capnp::DynamicStruct>()};
|
||||
}
|
||||
|
||||
Writer::OutputUnionType Writer::add_union_to_array(
|
||||
OutputArrayType* _parent) const noexcept {
|
||||
return OutputUnionType{
|
||||
_parent->val_[_parent->ix_++].as<capnp::DynamicStruct>()};
|
||||
}
|
||||
|
||||
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<capnp::DynamicList>(),
|
||||
.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<capnp::DynamicStruct>()};
|
||||
}
|
||||
|
||||
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<capnp::DynamicStruct>()};
|
||||
}
|
||||
|
||||
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<capnp::DynamicList>(),
|
||||
.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
|
||||
@@ -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 <iostream>
|
||||
#include <map>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
|
||||
#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<std::string, parsing::schema::Type>& _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<std::string, parsing::schema::Type>& _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<std::string, parsing::schema::Type>& _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<std::string, parsing::schema::Type>& _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<std::string, parsing::schema::Type>& _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<std::string, parsing::schema::Type>& _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<std::string, parsing::schema::Type>& _definitions,
|
||||
const Parent _parent, schema::CapnProtoTypes* _cnp_types) {
|
||||
auto handle_variant = [&](const auto& _t) -> schema::Type {
|
||||
using T = std::remove_cvref_t<decltype(_t)>;
|
||||
using Type = parsing::schema::Type;
|
||||
if constexpr (std::is_same<T, Type::Boolean>()) {
|
||||
return schema::Type{.value = schema::Type::Bool{}};
|
||||
|
||||
} else if constexpr (std::is_same<T, Type::Bytestring>()) {
|
||||
return schema::Type{.value = schema::Type::Data{}};
|
||||
|
||||
} else if constexpr (std::is_same<T, Type::Int32>() ||
|
||||
std::is_same<T, Type::Integer>()) {
|
||||
return schema::Type{.value = schema::Type::Int32{}};
|
||||
|
||||
} else if constexpr (std::is_same<T, Type::Int64>()) {
|
||||
return schema::Type{.value = schema::Type::Int64{}};
|
||||
|
||||
} else if constexpr (std::is_same<T, Type::UInt32>()) {
|
||||
return schema::Type{.value = schema::Type::UInt32{}};
|
||||
|
||||
} else if constexpr (std::is_same<T, Type::UInt64>()) {
|
||||
return schema::Type{.value = schema::Type::UInt64{}};
|
||||
|
||||
} else if constexpr (std::is_same<T, Type::Float>()) {
|
||||
return schema::Type{.value = schema::Type::Float32{}};
|
||||
|
||||
} else if constexpr (std::is_same<T, Type::Double>()) {
|
||||
return schema::Type{.value = schema::Type::Float64{}};
|
||||
|
||||
} else if constexpr (std::is_same<T, Type::String>()) {
|
||||
return schema::Type{.value = schema::Type::Text{}};
|
||||
|
||||
} else if constexpr (std::is_same<T, Type::AnyOf>()) {
|
||||
return any_of_to_capnproto_schema_type(_t, _definitions, _parent,
|
||||
_cnp_types);
|
||||
|
||||
} else if constexpr (std::is_same<T, Type::Description>()) {
|
||||
return type_to_capnproto_schema_type(*_t.type_, _definitions, _parent,
|
||||
_cnp_types);
|
||||
|
||||
} else if constexpr (std::is_same<T, Type::FixedSizeTypedArray>()) {
|
||||
return schema::Type{
|
||||
.value = schema::Type::List{
|
||||
.type = Ref<schema::Type>::make(type_to_capnproto_schema_type(
|
||||
*_t.type_, _definitions, Parent::is_not_a_struct,
|
||||
_cnp_types))}};
|
||||
|
||||
} else if constexpr (std::is_same<T, Type::Literal>()) {
|
||||
return literal_to_capnproto_schema_type(_t, _definitions, _parent,
|
||||
_cnp_types);
|
||||
|
||||
} else if constexpr (std::is_same<T, Type::Object>()) {
|
||||
return object_to_capnproto_schema_type(_t, _definitions, _parent,
|
||||
_cnp_types);
|
||||
|
||||
} else if constexpr (std::is_same<T, Type::Optional>()) {
|
||||
return optional_to_capnproto_schema_type(_t, _definitions, _parent,
|
||||
_cnp_types);
|
||||
|
||||
} else if constexpr (std::is_same<T, Type::Reference>()) {
|
||||
return reference_to_capnproto_schema_type(_t, _definitions, _parent,
|
||||
_cnp_types);
|
||||
|
||||
} else if constexpr (std::is_same<T, Type::StringMap>()) {
|
||||
_cnp_types->has_maps_ = true;
|
||||
return schema::Type{
|
||||
.value = schema::Type::Map{
|
||||
.type = Ref<schema::Type>::make(type_to_capnproto_schema_type(
|
||||
*_t.value_type_, _definitions, Parent::is_not_a_struct,
|
||||
_cnp_types))}};
|
||||
|
||||
} else if constexpr (std::is_same<T, Type::Tuple>()) {
|
||||
return type_to_capnproto_schema_type(
|
||||
Type{parsing::schemaful::tuple_to_object(_t)}, _definitions, _parent,
|
||||
_cnp_types);
|
||||
|
||||
} else if constexpr (std::is_same<T, Type::TypedArray>()) {
|
||||
return schema::Type{
|
||||
.value = schema::Type::List{
|
||||
.type = Ref<schema::Type>::make(type_to_capnproto_schema_type(
|
||||
*_t.type_, _definitions, Parent::is_not_a_struct,
|
||||
_cnp_types))}};
|
||||
|
||||
} else if constexpr (std::is_same<T, Type::Validated>()) {
|
||||
// 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<T>, "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
|
||||
@@ -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<std::string>& _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<std::string> split(const std::string& _str,
|
||||
const std::string& _delimiter) {
|
||||
auto str = _str;
|
||||
size_t pos = 0;
|
||||
std::vector<std::string> 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
|
||||
@@ -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<char>('0' + ((_i / 100) % 10)),
|
||||
static_cast<char>('0' + ((_i / 10) % 10)),
|
||||
static_cast<char>('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
|
||||
@@ -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()
|
||||
|
||||
+2
-1
@@ -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
|
||||
|
||||
@@ -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"]] <iostream> <string> <functional> <gtest/gtest.h>)
|
||||
|
||||
|
||||
target_link_libraries(
|
||||
reflect-cpp-capnproto-tests
|
||||
PRIVATE
|
||||
"${REFLECT_CPP_GTEST_LIB}"
|
||||
)
|
||||
|
||||
find_package(GTest)
|
||||
gtest_discover_tests(reflect-cpp-capnproto-tests)
|
||||
@@ -0,0 +1,46 @@
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "write_and_read.hpp"
|
||||
|
||||
namespace test_add_struct_name {
|
||||
|
||||
using Age = rfl::Validator<unsigned int, rfl::Minimum<0>, 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<Person> 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<Person>({bart, lisa, maggie})};
|
||||
|
||||
write_and_read<rfl::AddStructName<"type">>(homer);
|
||||
}
|
||||
} // namespace test_add_struct_name
|
||||
@@ -0,0 +1,35 @@
|
||||
#include <array>
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <rfl/capnproto.hpp>
|
||||
#include <string>
|
||||
|
||||
// Make sure things still compile when
|
||||
// rfl.hpp is included after rfl/capnproto.hpp.
|
||||
#include <rfl.hpp>
|
||||
|
||||
#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<std::array<Person, 3>> 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<Person, 3>>(std::array<Person, 3>{
|
||||
std::move(bart), std::move(lisa), std::move(maggie)})};
|
||||
|
||||
write_and_read(homer);
|
||||
}
|
||||
} // namespace test_array
|
||||
@@ -0,0 +1,44 @@
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
#include <rfl.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#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<DecisionTree> lesser;
|
||||
rfl::Box<DecisionTree> 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>(DecisionTree{leaf1}),
|
||||
.greater = rfl::make_box<DecisionTree>(DecisionTree{leaf2})};
|
||||
|
||||
const DecisionTree tree{.leaf_or_node = std::move(node)};
|
||||
|
||||
write_and_read(tree);
|
||||
|
||||
}
|
||||
} // namespace test_box
|
||||
@@ -0,0 +1,21 @@
|
||||
#include <iostream>
|
||||
#include <rfl.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#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
|
||||
@@ -0,0 +1,36 @@
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
#include <rfl.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#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<Person> 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
|
||||
@@ -0,0 +1,64 @@
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
#include <rfl.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#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 <class ReaderType, class WriterType, class ProcessorsType>
|
||||
struct Parser<ReaderType, WriterType, test_custom_class3::Person,
|
||||
ProcessorsType>
|
||||
: public CustomParser<ReaderType, WriterType, ProcessorsType,
|
||||
test_custom_class3::Person,
|
||||
test_custom_class3::PersonImpl> {};
|
||||
|
||||
} // 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
|
||||
@@ -0,0 +1,70 @@
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
#include <rfl.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "write_and_read.hpp"
|
||||
|
||||
namespace test_custom_class4 {
|
||||
|
||||
struct Person {
|
||||
Person(const std::string& _first_name,
|
||||
const rfl::Box<std::string>& _last_name, int _age)
|
||||
: first_name_(_first_name),
|
||||
last_name_(rfl::make_box<std::string>(*_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<std::string> last_name_;
|
||||
int age_;
|
||||
};
|
||||
|
||||
struct PersonImpl {
|
||||
rfl::Field<"firstName", std::string> first_name;
|
||||
rfl::Field<"lastName", rfl::Box<std::string>> 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<std::string>(*_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 <class ReaderType, class WriterType, class ProcessorsType>
|
||||
struct Parser<ReaderType, WriterType, test_custom_class4::Person,
|
||||
ProcessorsType>
|
||||
: public CustomParser<ReaderType, WriterType, ProcessorsType,
|
||||
test_custom_class4::Person,
|
||||
test_custom_class4::PersonImpl> {};
|
||||
|
||||
} // namespace parsing
|
||||
} // namespace rfl
|
||||
|
||||
namespace test_custom_class4 {
|
||||
|
||||
TEST(capnproto, test_custom_class4) {
|
||||
const auto bart = test_custom_class4::Person(
|
||||
"Bart", rfl::make_box<std::string>("Simpson"), 10);
|
||||
|
||||
write_and_read(bart);
|
||||
}
|
||||
} // namespace test_custom_class4
|
||||
@@ -0,0 +1,27 @@
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
#include <rfl.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#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<Person> 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<Person>({bart, lisa, maggie})};
|
||||
|
||||
write_and_read(homer);
|
||||
}
|
||||
} // namespace test_default_values
|
||||
@@ -0,0 +1,28 @@
|
||||
#include <iostream>
|
||||
#include <rfl.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#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<std::deque<Person>> children;
|
||||
};
|
||||
|
||||
TEST(capnproto, test_default_values) {
|
||||
auto children = std::make_unique<std::deque<Person>>();
|
||||
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
|
||||
@@ -0,0 +1,25 @@
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
#include <rfl.hpp>
|
||||
#include <rfl/json.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#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
|
||||
@@ -0,0 +1,36 @@
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
#include <rfl.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#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<"circle", Circle>, rfl::Field<"rectangle", Rectangle>,
|
||||
rfl::Field<"square", rfl::Box<Square>>>
|
||||
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
|
||||
@@ -0,0 +1,36 @@
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
#include <rfl.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#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<"circle", Circle>, rfl::Field<"rectangle", Rectangle>,
|
||||
rfl::Field<"square", rfl::Box<Square>>>
|
||||
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
|
||||
@@ -0,0 +1,35 @@
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
#include <rfl.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#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<Color>(static_cast<int>(c1) | static_cast<int>(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
|
||||
@@ -0,0 +1,34 @@
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
#include <rfl.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#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<Color>(static_cast<int>(c1) | static_cast<int>(c2));
|
||||
}
|
||||
|
||||
struct Circle {
|
||||
float radius;
|
||||
Color color;
|
||||
};
|
||||
|
||||
TEST(capnproto, test_flag_enum_with_int) {
|
||||
const auto circle = Circle{.radius = 2.0, .color = static_cast<Color>(10000)};
|
||||
|
||||
write_and_read(circle);
|
||||
}
|
||||
|
||||
} // namespace test_flag_enum_with_int
|
||||
@@ -0,0 +1,33 @@
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
#include <rfl.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "write_and_read.hpp"
|
||||
|
||||
namespace test_flatten {
|
||||
|
||||
struct Person {
|
||||
rfl::Field<"firstName", std::string> first_name;
|
||||
rfl::Field<"lastName", rfl::Box<std::string>> last_name;
|
||||
rfl::Field<"age", int> age;
|
||||
};
|
||||
|
||||
struct Employee {
|
||||
rfl::Flatten<Person> person;
|
||||
rfl::Field<"employer", rfl::Box<std::string>> employer;
|
||||
rfl::Field<"salary", float> salary;
|
||||
};
|
||||
|
||||
TEST(capnproto, test_flatten) {
|
||||
const auto employee = Employee{
|
||||
.person = Person{.first_name = "Homer",
|
||||
.last_name = rfl::make_box<std::string>("Simpson"),
|
||||
.age = 45},
|
||||
.employer = rfl::make_box<std::string>("Mr. Burns"),
|
||||
.salary = 60000.0};
|
||||
|
||||
write_and_read(employee);
|
||||
}
|
||||
} // namespace test_flatten
|
||||
@@ -0,0 +1,34 @@
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
#include <rfl.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "write_and_read.hpp"
|
||||
|
||||
namespace test_flatten_anonymous {
|
||||
|
||||
struct Person {
|
||||
std::string first_name;
|
||||
rfl::Box<std::string> last_name;
|
||||
int age;
|
||||
};
|
||||
|
||||
struct Employee {
|
||||
rfl::Flatten<Person> person;
|
||||
rfl::Box<std::string> employer;
|
||||
float salary;
|
||||
};
|
||||
|
||||
TEST(capnproto, test_flatten_anonymous) {
|
||||
const auto employee = Employee{
|
||||
.person = Person{.first_name = "Homer",
|
||||
.last_name = rfl::make_box<std::string>("Simpson"),
|
||||
.age = 45},
|
||||
.employer = rfl::make_box<std::string>("Mr. Burns"),
|
||||
.salary = 60000.0};
|
||||
|
||||
write_and_read(employee);
|
||||
}
|
||||
|
||||
} // namespace test_flatten_anonymous
|
||||
@@ -0,0 +1,28 @@
|
||||
#include <iostream>
|
||||
#include <rfl.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#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<std::forward_list<Person>> children;
|
||||
};
|
||||
|
||||
TEST(capnproto, test_forward_list) {
|
||||
auto children = std::make_unique<std::forward_list<Person>>();
|
||||
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
|
||||
@@ -0,0 +1,26 @@
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
#include <rfl.hpp>
|
||||
#include <rfl/json.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#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<Person> children;
|
||||
};
|
||||
|
||||
TEST(capnproto, test_literal) {
|
||||
const auto bart = Person{.first_name = FirstName::make<"Bart">()};
|
||||
|
||||
write_and_read(bart);
|
||||
}
|
||||
} // namespace test_literal
|
||||
@@ -0,0 +1,26 @@
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <rfl.hpp>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
#include "write_and_read.hpp"
|
||||
|
||||
namespace test_literal_map {
|
||||
|
||||
using FieldName = rfl::Literal<"firstName", "lastName">;
|
||||
|
||||
struct RootStruct {
|
||||
std::map<FieldName, std::unique_ptr<std::string>> root;
|
||||
};
|
||||
|
||||
TEST(capnproto, test_literal_map) {
|
||||
RootStruct homer;
|
||||
homer.root.insert(std::make_pair(FieldName::make<"firstName">(),
|
||||
std::make_unique<std::string>("Homer")));
|
||||
homer.root.insert(std::make_pair(FieldName::make<"lastName">(),
|
||||
std::make_unique<std::string>("Simpson")));
|
||||
write_and_read(homer);
|
||||
}
|
||||
} // namespace test_literal_map
|
||||
@@ -0,0 +1,28 @@
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
#include <rfl.hpp>
|
||||
#include <rfl/json.hpp>
|
||||
#include <string>
|
||||
|
||||
#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<std::map<std::string, Person>> children;
|
||||
};
|
||||
|
||||
TEST(capnproto, test_map) {
|
||||
auto children = std::make_unique<std::map<std::string, Person>>();
|
||||
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
|
||||
@@ -0,0 +1,28 @@
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
#include <rfl.hpp>
|
||||
#include <rfl/json.hpp>
|
||||
#include <string>
|
||||
|
||||
#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<std::string, Person> children;
|
||||
};
|
||||
|
||||
TEST(capnproto, test_map2) {
|
||||
auto children = std::map<std::string, Person>();
|
||||
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
|
||||
@@ -0,0 +1,60 @@
|
||||
#include <iostream>
|
||||
#include <rfl.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#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<"weapon", Weapon>, 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<int> inventory;
|
||||
Color color = Color::make<"Blue">();
|
||||
std::vector<Weapon> weapons;
|
||||
Equipment equipped;
|
||||
std::vector<Vec3> 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<Weapon>({sword, axe});
|
||||
|
||||
const auto position = Vec3{1.0f, 2.0f, 3.0f};
|
||||
|
||||
const auto inventory = std::vector<int>({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
|
||||
@@ -0,0 +1,30 @@
|
||||
#include <iostream>
|
||||
#include <rfl.hpp>
|
||||
#include <rfl/json.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "write_and_read.hpp"
|
||||
|
||||
namespace test_optional_fields {
|
||||
|
||||
struct Person {
|
||||
std::string first_name;
|
||||
std::string last_name = "Simpson";
|
||||
std::optional<std::vector<Person>> 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<Person>({bart, lisa, maggie})};
|
||||
|
||||
write_and_read(homer);
|
||||
}
|
||||
} // namespace test_optional_fields
|
||||
@@ -0,0 +1,30 @@
|
||||
#include <iostream>
|
||||
#include <rfl.hpp>
|
||||
#include <rfl/json.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "write_and_read.hpp"
|
||||
|
||||
namespace test_optionals_in_vectors {
|
||||
|
||||
struct Person {
|
||||
std::string first_name;
|
||||
std::string last_name = "Simpson";
|
||||
std::vector<std::optional<Person>> children;
|
||||
};
|
||||
|
||||
TEST(capnproto, test_optionals_in_vectors) {
|
||||
const std::optional<Person> bart = Person{.first_name = "Bart"};
|
||||
|
||||
const std::optional<Person> lisa = Person{.first_name = "Lisa"};
|
||||
|
||||
const std::optional<Person> maggie = Person{.first_name = "Maggie"};
|
||||
|
||||
const auto homer = Person{.first_name = "Homer",
|
||||
.children = std::vector<std::optional<Person>>(
|
||||
{bart, lisa, maggie, std::nullopt})};
|
||||
|
||||
write_and_read(homer);
|
||||
}
|
||||
} // namespace test_optionals_in_vectors
|
||||
@@ -0,0 +1,32 @@
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <iostream>
|
||||
#include <rfl.hpp>
|
||||
#include <rfl/capnproto.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "write_and_read.hpp"
|
||||
|
||||
namespace test_tutorial_example {
|
||||
|
||||
struct Person {
|
||||
std::string first_name;
|
||||
std::string last_name = "Simpson";
|
||||
std::vector<Person> 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<Person>({bart, lisa, maggie})};
|
||||
|
||||
write_and_read(homer);
|
||||
}
|
||||
} // namespace test_tutorial_example
|
||||
@@ -0,0 +1,46 @@
|
||||
#include <iostream>
|
||||
#include <rfl.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "write_and_read.hpp"
|
||||
|
||||
namespace test_readme_example {
|
||||
|
||||
using Age = rfl::Validator<unsigned int, rfl::Minimum<0>, 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<Person> 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<Person>({bart, lisa, maggie})};
|
||||
|
||||
write_and_read(homer);
|
||||
}
|
||||
} // namespace test_readme_example
|
||||
@@ -0,0 +1,22 @@
|
||||
#include <iostream>
|
||||
#include <rfl.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#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
|
||||
@@ -0,0 +1,31 @@
|
||||
#include <iostream>
|
||||
#include <rfl.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#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<Person> 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<Person>({bart, lisa, maggie})};
|
||||
|
||||
write_and_read(homer);
|
||||
}
|
||||
} // namespace test_readme_example3
|
||||
@@ -0,0 +1,44 @@
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
#include <rfl.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#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<DecisionTree> lesser;
|
||||
rfl::Ref<DecisionTree> 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>(DecisionTree{leaf1}),
|
||||
.greater = rfl::make_ref<DecisionTree>(DecisionTree{leaf2})};
|
||||
|
||||
const DecisionTree tree{.leaf_or_node = std::move(node)};
|
||||
|
||||
write_and_read(tree);
|
||||
|
||||
}
|
||||
} // namespace test_ref
|
||||
@@ -0,0 +1,33 @@
|
||||
|
||||
#include <memory>
|
||||
#include <rfl.hpp>
|
||||
#include <rfl/json.hpp>
|
||||
#include <string>
|
||||
#include <tuple>
|
||||
|
||||
#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<rfl::Tuple<Person, Person, Person>> 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<Person, Person, Person>>(
|
||||
rfl::Tuple<Person, Person, Person>{
|
||||
std::move(bart), std::move(lisa), std::move(maggie)})};
|
||||
|
||||
write_and_read(homer);
|
||||
}
|
||||
} // namespace test_rfl_tuple
|
||||
@@ -0,0 +1,33 @@
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
#include <rfl.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#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<Circle, Rectangle, std::unique_ptr<Square>> root;
|
||||
};
|
||||
|
||||
TEST(capnproto, test_rfl_variant) {
|
||||
const auto r = Shapes{Rectangle{.height = 10, .width = 5}};
|
||||
|
||||
write_and_read(r);
|
||||
}
|
||||
} // namespace test_variant
|
||||
@@ -0,0 +1,61 @@
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
#include <rfl.hpp>
|
||||
#include <rfl/capnproto.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace test_save_load {
|
||||
|
||||
using Age = rfl::Validator<unsigned int,
|
||||
rfl::AllOf<rfl::Minimum<0>, 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<Person> 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<Person>()};
|
||||
|
||||
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<Person>({bart, lisa, maggie})};
|
||||
|
||||
rfl::capnproto::save("homer.capnproto", homer1);
|
||||
|
||||
const auto homer2 = rfl::capnproto::load<Person>("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
|
||||
@@ -0,0 +1,25 @@
|
||||
#include <iostream>
|
||||
#include <rfl.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#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<std::set<std::string>> children;
|
||||
};
|
||||
|
||||
TEST(capnproto, test_set) {
|
||||
auto children = std::make_unique<std::set<std::string>>(
|
||||
std::set<std::string>({"Bart", "Lisa", "Maggie"}));
|
||||
|
||||
const auto homer =
|
||||
Person{.first_name = "Homer", .children = std::move(children)};
|
||||
|
||||
write_and_read(homer);
|
||||
}
|
||||
} // namespace test_set
|
||||
@@ -0,0 +1,29 @@
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <rfl.hpp>
|
||||
#include <rfl/json.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "write_and_read.hpp"
|
||||
|
||||
namespace test_shared_ptr {
|
||||
|
||||
struct Person {
|
||||
std::string first_name;
|
||||
std::string last_name = "Simpson";
|
||||
std::shared_ptr<std::vector<Person>> children;
|
||||
};
|
||||
|
||||
TEST(capnproto, test_shared_ptr) {
|
||||
auto children = std::make_shared<std::vector<Person>>();
|
||||
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
|
||||
@@ -0,0 +1,37 @@
|
||||
#include <iostream>
|
||||
#include <rfl.hpp>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#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<std::vector<Person>,
|
||||
rfl::Size<rfl::AnyOf<rfl::EqualTo<0>, 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<Person>({bart, lisa, maggie})};
|
||||
|
||||
write_and_read(homer);
|
||||
}
|
||||
} // namespace test_size
|
||||
@@ -0,0 +1,25 @@
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <rfl.hpp>
|
||||
#include <rfl/json.hpp>
|
||||
#include <string>
|
||||
|
||||
#include "write_and_read.hpp"
|
||||
|
||||
namespace test_string_map {
|
||||
|
||||
struct RootStruct {
|
||||
std::map<std::string, std::unique_ptr<std::string>> root;
|
||||
};
|
||||
|
||||
TEST(capnproto, test_string_map) {
|
||||
RootStruct homer;
|
||||
homer.root.insert(
|
||||
std::make_pair("firstName", std::make_unique<std::string>("Homer")));
|
||||
homer.root.insert(
|
||||
std::make_pair("lastName", std::make_unique<std::string>("Simpson")));
|
||||
|
||||
write_and_read(homer);
|
||||
}
|
||||
} // namespace test_string_map
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user