diff --git a/.github/workflows/linux.yaml b/.github/workflows/linux-cxx20.yaml similarity index 92% rename from .github/workflows/linux.yaml rename to .github/workflows/linux-cxx20.yaml index 0098ec5d..78c17611 100644 --- a/.github/workflows/linux.yaml +++ b/.github/workflows/linux-cxx20.yaml @@ -1,4 +1,4 @@ -name: linux +name: linux-cxx20 on: [ pull_request, workflow_dispatch ] @@ -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_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 -S . -B build -G Ninja -DCMAKE_CXX_STANDARD=20 -DREFLECTCPP_BUILD_TESTS=ON -DREFLECTCPP_BUILD_BENCHMARKS=ON -DREFLECTCPP_BSON=ON -DREFLECTCPP_CAPNPROTO=ON -DREFLECTCPP_CBOR=ON -DREFLECTCPP_FLEXBUFFERS=ON -DREFLECTCPP_MSGPACK=ON -DREFLECTCPP_TOML=ON -DREFLECTCPP_XML=ON -DREFLECTCPP_YAML=ON -DCMAKE_BUILD_TYPE=Release cmake --build build - name: Run tests run: | diff --git a/.github/workflows/linux-cxx23.yaml b/.github/workflows/linux-cxx23.yaml new file mode 100644 index 00000000..0f8f80d5 --- /dev/null +++ b/.github/workflows/linux-cxx23.yaml @@ -0,0 +1,84 @@ +name: linux-cxx23 + +on: [ pull_request, workflow_dispatch ] + +env: + VCPKG_BINARY_SOURCES: "clear;x-gha,readwrite" + +jobs: + linux: + strategy: + fail-fast: false + matrix: + include: + - compiler: gcc + compiler-version: 13 + - compiler: gcc + compiler-version: 14 + name: "${{ github.job }} (${{ matrix.compiler }}-${{ matrix.compiler-version }})" + runs-on: ubuntu-24.04 + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + submodules: recursive + fetch-depth: 0 + - name: Export GitHub Actions cache environment variables + uses: actions/github-script@v7 + with: + script: | + core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || ''); + core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || ''); + - name: Setup ccache + uses: hendrikmuhs/ccache-action@v1 + with: + key: "${{ github.job }}-${{ matrix.compiler }}-${{ matrix.compiler-version }}" + max-size: "2G" + - name: Run vcpkg + uses: lukka/run-vcpkg@v11 + - name: Install dependencies + run: | + sudo apt update + sudo apt install -y ninja-build ${{ matrix.additional-dep }} + - name: Install Conan + run: | + sudo apt install -y pipx + pipx install conan + conan profile detect + - name: Make sure the library compiles with Conan + run: conan build . --build=missing -s compiler.cppstd=gnu23 -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 + export CC=clang-${{ matrix.compiler-version }} + export CXX=clang++-${{ matrix.compiler-version }} + elif [[ "${{ matrix.compiler }}" == "gcc" ]]; then + export CC=gcc-${{ matrix.compiler-version }} + export CXX=g++-${{ matrix.compiler-version }} + fi + 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 -DCMAKE_CXX_STANDARD=23 -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 -DREFLECTCPP_USE_STD_EXPECTED=ON + cmake --build build + - name: Run tests + run: | + ctest --test-dir build --output-on-failure + - name: Run benchmarks + run: | + echo '# Benchmarks' >> $GITHUB_STEP_SUMMARY + echo '## Benchmarks across different formats' >> $GITHUB_STEP_SUMMARY + echo '```' >> $GITHUB_STEP_SUMMARY + ./build/benchmarks/all/reflect-cpp-all-format-benchmarks --benchmark_filter=canada_read >> $GITHUB_STEP_SUMMARY + ./build/benchmarks/all/reflect-cpp-all-format-benchmarks --benchmark_filter=canada_write >> $GITHUB_STEP_SUMMARY + ./build/benchmarks/all/reflect-cpp-all-format-benchmarks --benchmark_filter=licenses_read >> $GITHUB_STEP_SUMMARY + ./build/benchmarks/all/reflect-cpp-all-format-benchmarks --benchmark_filter=licenses_write >> $GITHUB_STEP_SUMMARY + ./build/benchmarks/all/reflect-cpp-all-format-benchmarks --benchmark_filter=person_read >> $GITHUB_STEP_SUMMARY + ./build/benchmarks/all/reflect-cpp-all-format-benchmarks --benchmark_filter=person_write >> $GITHUB_STEP_SUMMARY + echo '```' >> $GITHUB_STEP_SUMMARY + echo '## Benchmarks for JSON' >> $GITHUB_STEP_SUMMARY + echo '```' >> $GITHUB_STEP_SUMMARY + ./build/benchmarks/json/reflect-cpp-json-benchmarks --benchmark_filter=person_read >> $GITHUB_STEP_SUMMARY + ./build/benchmarks/json/reflect-cpp-json-benchmarks --benchmark_filter=canada >> $GITHUB_STEP_SUMMARY + ./build/benchmarks/json/reflect-cpp-json-benchmarks --benchmark_filter=licenses >> $GITHUB_STEP_SUMMARY + echo '```' >> $GITHUB_STEP_SUMMARY diff --git a/.github/workflows/macos-clang.yaml b/.github/workflows/macos-cxx20.yaml similarity index 89% rename from .github/workflows/macos-clang.yaml rename to .github/workflows/macos-cxx20.yaml index af073036..d4c3a384 100644 --- a/.github/workflows/macos-clang.yaml +++ b/.github/workflows/macos-cxx20.yaml @@ -1,4 +1,4 @@ -name: macos-clang +name: macos-cxx20 on: [ pull_request, workflow_dispatch ] @@ -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_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 -S . -B build -DCMAKE_CXX_STANDARD=20 -DREFLECTCPP_BUILD_TESTS=ON -DREFLECTCPP_BUILD_BENCHMARKS=ON -DREFLECTCPP_BSON=ON -DREFLECTCPP_CAPNPROTO=ON -DREFLECTCPP_CBOR=ON -DREFLECTCPP_FLEXBUFFERS=ON -DREFLECTCPP_MSGPACK=ON -DREFLECTCPP_TOML=ON -DREFLECTCPP_XML=ON -DREFLECTCPP_YAML=ON -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ cmake --build build -j 4 - name: Run tests run: | diff --git a/.github/workflows/windows-msvc.yaml b/.github/workflows/windows-cxx20.yaml similarity index 88% rename from .github/workflows/windows-msvc.yaml rename to .github/workflows/windows-cxx20.yaml index b1406f66..483e31a4 100644 --- a/.github/workflows/windows-msvc.yaml +++ b/.github/workflows/windows-cxx20.yaml @@ -1,4 +1,4 @@ -name: windows-msvc +name: windows-cxx20 on: [ pull_request, workflow_dispatch ] @@ -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_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 -S . -B build -DCMAKE_CXX_STANDARD=20 -DREFLECTCPP_BUILD_TESTS=ON -DREFLECTCPP_BUILD_BENCHMARKS=ON -DREFLECTCPP_BSON=ON -DREFLECTCPP_CAPNPROTO=ON -DREFLECTCPP_CBOR=ON -DREFLECTCPP_FLEXBUFFERS=ON -DREFLECTCPP_MSGPACK=ON -DREFLECTCPP_XML=ON -DREFLECTCPP_TOML=ON -DREFLECTCPP_YAML=ON -DCMAKE_BUILD_TYPE=Release cmake --build build --config Release -j4 - name: Run tests run: | diff --git a/.gitignore b/.gitignore index b9205018..13abfb6a 100644 --- a/.gitignore +++ b/.gitignore @@ -10,7 +10,7 @@ # Precompiled Headers *.gch *.pch - +.cache # Compiled Dynamic libraries *.so *.dylib diff --git a/CMakeLists.txt b/CMakeLists.txt index 4d0904fb..5afb6066 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -19,6 +19,21 @@ option(REFLECTCPP_BUILD_TESTS "Build tests" OFF) option(REFLECTCPP_USE_BUNDLED_DEPENDENCIES "Use the bundled dependencies" ON) +option(REFLECTCPP_USE_STD_EXPECTED "Use std::expected instead of the built-in Result type (requires C++-23)" OFF) + +if(REFLECTCPP_USE_STD_EXPECTED) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DREFLECTCPP_USE_STD_EXPECTED") + if(NOT DEFINED CMAKE_CXX_STANDARD) + set(CMAKE_CXX_STANDARD 23) + endif() +else() + if(NOT DEFINED CMAKE_CXX_STANDARD) + set(CMAKE_CXX_STANDARD 20) + endif() +endif() + +set(CMAKE_CXX_STANDARD_REQUIRED ON) + set(REFLECTCPP_USE_VCPKG_DEFAULT OFF) if(REFLECTCPP_BUILD_BENCHMARKS) @@ -51,8 +66,6 @@ endif () project(reflectcpp VERSION 0.17.0 LANGUAGES CXX) -set(CMAKE_CXX_STANDARD 20) - if (REFLECTCPP_BUILD_SHARED) add_library(reflectcpp SHARED) set_target_properties(reflectcpp PROPERTIES SOVERSION ${PROJECT_VERSION}) diff --git a/README.md b/README.md index b5fe8e70..d41b854b 100644 --- a/README.md +++ b/README.md @@ -554,7 +554,7 @@ https://conan.io/center/recipes/reflect-cpp This will compile reflect-cpp with JSON support only. You can then include reflect-cpp in your project and link to the binary. ```bash -cmake -S . -B build -DCMAKE_BUILD_TYPE=Release +cmake -S . -B build -DCMAKE_CXX_STANDARD=20 -DCMAKE_BUILD_TYPE=Release cmake --build build -j 4 # gcc, clang cmake --build build --config Release -j 4 # MSVC ``` diff --git a/benchmarks/README.md b/benchmarks/README.md index 85a6562e..ce0a04bf 100644 --- a/benchmarks/README.md +++ b/benchmarks/README.md @@ -19,7 +19,7 @@ this repository to learn how to install vcpkg. To compile the benchmarks, do the following: ```bash -cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DREFLECTCPP_BUILD_BENCHMARKS=ON +cmake -S . -B build -DCMAKE_CXX_STANDARD=20 -DCMAKE_BUILD_TYPE=Release -DREFLECTCPP_BUILD_BENCHMARKS=ON cmake --build build -j 4 # gcc, clang cmake --build build --config Release -j 4 # MSVC ``` diff --git a/benchmarks/all/canada_read.cpp b/benchmarks/all/canada_read.cpp index fd803dbf..3053ce7d 100644 --- a/benchmarks/all/canada_read.cpp +++ b/benchmarks/all/canada_read.cpp @@ -55,7 +55,7 @@ static void BM_canada_read_reflect_cpp_avro(benchmark::State &state) { for (auto _ : state) { const auto res = rfl::avro::read(data, schema); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -66,7 +66,7 @@ static void BM_canada_read_reflect_cpp_bson(benchmark::State &state) { for (auto _ : state) { const auto res = rfl::bson::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -78,7 +78,7 @@ static void BM_canada_read_reflect_cpp_capnproto(benchmark::State &state) { for (auto _ : state) { const auto res = rfl::capnproto::read(data, schema); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -89,7 +89,7 @@ static void BM_canada_read_reflect_cpp_cbor(benchmark::State &state) { for (auto _ : state) { const auto res = rfl::cbor::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -102,7 +102,7 @@ static void BM_canada_read_reflect_cpp_cbor_without_field_names( const auto res = rfl::cbor::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -113,7 +113,7 @@ static void BM_canada_read_reflect_cpp_flexbuf(benchmark::State &state) { for (auto _ : state) { const auto res = rfl::flexbuf::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -126,7 +126,7 @@ static void BM_canada_read_reflect_cpp_flexbuf_without_field_names( const auto res = rfl::flexbuf::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -137,7 +137,7 @@ static void BM_canada_read_reflect_cpp_json(benchmark::State &state) { for (auto _ : state) { const auto res = rfl::json::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -150,7 +150,7 @@ static void BM_canada_read_reflect_cpp_json_without_field_names( const auto res = rfl::json::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -161,7 +161,7 @@ static void BM_canada_read_reflect_cpp_msgpack(benchmark::State &state) { for (auto _ : state) { const auto res = rfl::msgpack::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -174,7 +174,7 @@ static void BM_canada_read_reflect_cpp_msgpack_without_field_names( const auto res = rfl::msgpack::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -185,7 +185,7 @@ static void BM_canada_read_reflect_cpp_toml(benchmark::State &state) { for (auto _ : state) { const auto res = rfl::toml::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -196,7 +196,7 @@ static void BM_canada_read_reflect_cpp_ubjson(benchmark::State &state) { for (auto _ : state) { const auto res = rfl::ubjson::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -209,7 +209,7 @@ static void BM_canada_read_reflect_cpp_ubjson_without_field_names( const auto res = rfl::ubjson::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -220,7 +220,7 @@ static void BM_canada_read_reflect_cpp_yaml(benchmark::State &state) { for (auto _ : state) { const auto res = rfl::yaml::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } diff --git a/benchmarks/all/licenses_read.cpp b/benchmarks/all/licenses_read.cpp index a04e8af1..e0a5f9cd 100644 --- a/benchmarks/all/licenses_read.cpp +++ b/benchmarks/all/licenses_read.cpp @@ -71,7 +71,7 @@ static void BM_licenses_read_reflect_cpp_avro(benchmark::State &state) { for (auto _ : state) { const auto res = rfl::avro::read(data, schema); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -82,7 +82,7 @@ static void BM_licenses_read_reflect_cpp_bson(benchmark::State &state) { for (auto _ : state) { const auto res = rfl::bson::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -94,7 +94,7 @@ static void BM_licenses_read_reflect_cpp_capnproto(benchmark::State &state) { for (auto _ : state) { const auto res = rfl::capnproto::read(data, schema); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -105,7 +105,7 @@ static void BM_licenses_read_reflect_cpp_cbor(benchmark::State &state) { for (auto _ : state) { const auto res = rfl::cbor::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -117,7 +117,7 @@ static void BM_licenses_read_reflect_cpp_cbor_without_field_names( for (auto _ : state) { const auto res = rfl::cbor::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -128,7 +128,7 @@ static void BM_licenses_read_reflect_cpp_flexbuf(benchmark::State &state) { for (auto _ : state) { const auto res = rfl::flexbuf::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -140,7 +140,7 @@ static void BM_licenses_read_reflect_cpp_flexbuf_without_field_names( for (auto _ : state) { const auto res = rfl::flexbuf::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -151,7 +151,7 @@ static void BM_licenses_read_reflect_cpp_json(benchmark::State &state) { for (auto _ : state) { const auto res = rfl::json::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -163,7 +163,7 @@ static void BM_licenses_read_reflect_cpp_json_without_field_names( for (auto _ : state) { const auto res = rfl::json::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -174,7 +174,7 @@ static void BM_licenses_read_reflect_cpp_msgpack(benchmark::State &state) { for (auto _ : state) { const auto res = rfl::msgpack::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -186,7 +186,7 @@ static void BM_licenses_read_reflect_cpp_msgpack_without_field_names( for (auto _ : state) { const auto res = rfl::msgpack::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -197,7 +197,7 @@ static void BM_licenses_read_reflect_cpp_xml(benchmark::State &state) { for (auto _ : state) { const auto res = rfl::xml::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -208,7 +208,7 @@ static void BM_licenses_read_reflect_cpp_toml(benchmark::State &state) { for (auto _ : state) { const auto res = rfl::toml::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -219,7 +219,7 @@ static void BM_licenses_read_reflect_cpp_ubjson(benchmark::State &state) { for (auto _ : state) { const auto res = rfl::ubjson::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -231,7 +231,7 @@ static void BM_licenses_read_reflect_cpp_ubjson_without_field_names( for (auto _ : state) { const auto res = rfl::ubjson::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -242,7 +242,7 @@ static void BM_licenses_read_reflect_cpp_yaml(benchmark::State &state) { for (auto _ : state) { const auto res = rfl::yaml::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } diff --git a/benchmarks/all/person_read.cpp b/benchmarks/all/person_read.cpp index 64114840..85c723ee 100644 --- a/benchmarks/all/person_read.cpp +++ b/benchmarks/all/person_read.cpp @@ -50,7 +50,7 @@ static void BM_person_read_reflect_cpp_avro(benchmark::State &state) { for (auto _ : state) { const auto res = rfl::avro::read(data, schema); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -61,7 +61,7 @@ static void BM_person_read_reflect_cpp_bson(benchmark::State &state) { for (auto _ : state) { const auto res = rfl::bson::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -73,7 +73,7 @@ static void BM_person_read_reflect_cpp_capnproto(benchmark::State &state) { for (auto _ : state) { const auto res = rfl::capnproto::read(data, schema); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -84,7 +84,7 @@ static void BM_person_read_reflect_cpp_cbor(benchmark::State &state) { for (auto _ : state) { const auto res = rfl::cbor::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -96,7 +96,7 @@ static void BM_person_read_reflect_cpp_cbor_without_field_names( for (auto _ : state) { const auto res = rfl::cbor::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -107,7 +107,7 @@ static void BM_person_read_reflect_cpp_flexbuf(benchmark::State &state) { for (auto _ : state) { const auto res = rfl::flexbuf::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -119,7 +119,7 @@ static void BM_person_read_reflect_cpp_flexbuf_without_field_names( for (auto _ : state) { const auto res = rfl::flexbuf::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -130,7 +130,7 @@ static void BM_person_read_reflect_cpp_json(benchmark::State &state) { for (auto _ : state) { const auto res = rfl::json::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -142,7 +142,7 @@ static void BM_person_read_reflect_cpp_json_without_field_names( for (auto _ : state) { const auto res = rfl::json::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -153,7 +153,7 @@ static void BM_person_read_reflect_cpp_msgpack(benchmark::State &state) { for (auto _ : state) { const auto res = rfl::msgpack::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -165,7 +165,7 @@ static void BM_person_read_reflect_cpp_msgpack_without_field_names( for (auto _ : state) { const auto res = rfl::msgpack::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -176,7 +176,7 @@ static void BM_person_read_reflect_cpp_toml(benchmark::State &state) { for (auto _ : state) { const auto res = rfl::toml::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -187,7 +187,7 @@ static void BM_person_read_reflect_cpp_ubjson(benchmark::State &state) { for (auto _ : state) { const auto res = rfl::ubjson::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -199,7 +199,7 @@ static void BM_person_read_reflect_cpp_ubjson_without_field_names( for (auto _ : state) { const auto res = rfl::ubjson::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -210,7 +210,7 @@ static void BM_person_read_reflect_cpp_xml(benchmark::State &state) { for (auto _ : state) { const auto res = rfl::xml::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -221,7 +221,7 @@ static void BM_person_read_reflect_cpp_yaml(benchmark::State &state) { for (auto _ : state) { const auto res = rfl::yaml::read(data); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } diff --git a/benchmarks/json/canada.cpp b/benchmarks/json/canada.cpp index 53ab46f1..b857f765 100644 --- a/benchmarks/json/canada.cpp +++ b/benchmarks/json/canada.cpp @@ -106,7 +106,7 @@ static rfl::Result read_using_nlohmann( auto val = nlohmann::json::parse(_json_string); return nlohmann_to_feature_collection(val); } catch (std::exception &e) { - return rfl::Error(e.what()); + return rfl::error(e.what()); } } @@ -183,15 +183,15 @@ static rfl::Result read_using_rapidjson( d.Parse(_json_string.c_str()); return rapidjson_to_feature_collection(d.GetObject()); } catch (std::exception &e) { - return rfl::Error(e.what()); + return rfl::error(e.what()); } } // ---------------------------------------------------------------------------- // simdjson -simdjson_inline std::vector>> simdjson_to_coordinates( - simdjson::ondemand::array _val); +simdjson_inline std::vector>> +simdjson_to_coordinates(simdjson::ondemand::array _val); simdjson_inline Property simdjson_to_property(simdjson::ondemand::object _val); @@ -199,16 +199,17 @@ simdjson_inline Geometry simdjson_to_geometry(simdjson::ondemand::object _val); simdjson_inline Feature simdjson_to_feature(simdjson::ondemand::object _val); -simdjson_inline FeatureCollection simdjson_to_feature_collection( - simdjson::ondemand::object _val); +simdjson_inline FeatureCollection +simdjson_to_feature_collection(simdjson::ondemand::object _val); -simdjson_inline std::vector>> simdjson_to_coordinates( - simdjson::ondemand::array _val) { +simdjson_inline std::vector>> +simdjson_to_coordinates(simdjson::ondemand::array _val) { std::vector>> coordinates; for (auto arr1 : _val) { std::vector> vec; for (auto val2 : arr1) { - // Instead of indexing x = val2[0] and y = val2[1], we iterate through the two values. + // Instead of indexing x = val2[0] and y = val2[1], we iterate through the + // two values. auto coord = val2.begin(); double x = *coord; ++coord; @@ -245,8 +246,8 @@ simdjson_inline Feature simdjson_to_feature(simdjson::ondemand::object _val) { return feature; } -simdjson_inline FeatureCollection simdjson_to_feature_collection( - simdjson::ondemand::object _val) { +simdjson_inline FeatureCollection +simdjson_to_feature_collection(simdjson::ondemand::object _val) { FeatureCollection feature_collection; feature_collection.type = simdjson_to_string(_val["type"]); for (auto val : _val["features"].get_array()) { @@ -263,7 +264,7 @@ static rfl::Result read_using_simdjson( auto doc = parser.iterate(padded_str); return simdjson_to_feature_collection(doc); } catch (std::exception &e) { - return rfl::Error(e.what()); + return rfl::error(e.what()); } } @@ -346,7 +347,7 @@ static rfl::Result read_using_yyjson( yyjson_doc *doc = yyjson_read(_json_string.c_str(), _json_string.size(), 0); if (!doc) { std::cout << "Could not parse document!" << std::endl; - return rfl::Error("Could not parse document"); + return rfl::error("Could not parse document"); } yyjson_val *root = yyjson_doc_get_root(doc); auto person = yyjson_to_feature_collection(root); @@ -357,7 +358,7 @@ static rfl::Result read_using_yyjson( auto val = nlohmann::json::parse(_json_string); return nlohmann_to_feature_collection(val); } catch (std::exception &e) { - return rfl::Error(e.what()); + return rfl::error(e.what()); } } @@ -368,7 +369,7 @@ static void BM_canada_nlohmann(benchmark::State &state) { for (auto _ : state) { const auto res = read_using_nlohmann(json_string); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -379,7 +380,7 @@ static void BM_canada_rapidjson(benchmark::State &state) { for (auto _ : state) { const auto res = read_using_rapidjson(json_string); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -393,7 +394,7 @@ static void BM_canada_simdjson(benchmark::State &state) { for (auto _ : state) { const auto res = read_using_simdjson(json_string); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -406,7 +407,7 @@ static void BM_canada_yyjson(benchmark::State &state) { for (auto _ : state) { const auto res = read_using_yyjson(json_string); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -417,7 +418,7 @@ static void BM_canada_reflect_cpp(benchmark::State &state) { for (auto _ : state) { const auto res = rfl::json::read(json_string); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -426,4 +427,3 @@ BENCHMARK(BM_canada_reflect_cpp); // ---------------------------------------------------------------------------- } // namespace canada - diff --git a/benchmarks/json/licenses.cpp b/benchmarks/json/licenses.cpp index eb6de0d7..f7d03fae 100644 --- a/benchmarks/json/licenses.cpp +++ b/benchmarks/json/licenses.cpp @@ -141,7 +141,7 @@ static rfl::Result read_using_nlohmann( auto val = nlohmann::json::parse(_json_string); return nlohmann_to_licenses(val); } catch (std::exception &e) { - return rfl::Error(e.what()); + return rfl::error(e.what()); } } @@ -237,7 +237,7 @@ static rfl::Result read_using_rapidjson( d.Parse(_json_string.c_str()); return rapidjson_to_licenses(d.GetObject()); } catch (std::exception &e) { - return rfl::Error(e.what()); + return rfl::error(e.what()); } } @@ -328,7 +328,7 @@ static rfl::Result read_using_simdjson( auto doc = parser.iterate(padded_str).value(); return simdjson_to_licenses(doc.get_object()); } catch (std::exception &e) { - return rfl::Error(e.what()); + return rfl::error(e.what()); } } @@ -430,7 +430,7 @@ static rfl::Result read_using_yyjson( yyjson_doc *doc = yyjson_read(_json_string.c_str(), _json_string.size(), 0); if (!doc) { std::cout << "Could not parse document!" << std::endl; - return rfl::Error("Could not parse document"); + return rfl::error("Could not parse document"); } yyjson_val *root = yyjson_doc_get_root(doc); auto licenses = yyjson_to_licenses(root); @@ -445,7 +445,7 @@ static void BM_licenses_nlohmann(benchmark::State &state) { for (auto _ : state) { const auto res = read_using_nlohmann(json_string); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -456,7 +456,7 @@ static void BM_licenses_rapidjson(benchmark::State &state) { for (auto _ : state) { const auto res = read_using_rapidjson(json_string); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -467,7 +467,7 @@ static void BM_licenses_simdjson(benchmark::State &state) { for (auto _ : state) { const auto res = read_using_simdjson(json_string); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -478,7 +478,7 @@ static void BM_licenses_yyjson(benchmark::State &state) { for (auto _ : state) { const auto res = read_using_yyjson(json_string); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -489,7 +489,7 @@ static void BM_licenses_reflect_cpp(benchmark::State &state) { for (auto _ : state) { const auto res = rfl::json::read(json_string); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -498,4 +498,3 @@ BENCHMARK(BM_licenses_reflect_cpp); // ---------------------------------------------------------------------------- } // namespace licenses - diff --git a/benchmarks/json/person.cpp b/benchmarks/json/person.cpp index 6fde5ad1..af472850 100644 --- a/benchmarks/json/person.cpp +++ b/benchmarks/json/person.cpp @@ -72,7 +72,7 @@ static rfl::Result read_using_nlohmann() { auto val = nlohmann::json::parse(json_string); return nlohmann_to_person(val); } catch (std::exception &e) { - return rfl::Error(e.what()); + return rfl::error(e.what()); } } @@ -105,7 +105,7 @@ static rfl::Result read_using_rapidjson() { d.Parse(json_string.c_str()); return rapidjson_to_person(d.GetObject()); } catch (std::exception &e) { - return rfl::Error(e.what()); + return rfl::error(e.what()); } } @@ -139,7 +139,7 @@ static rfl::Result read_using_simdjson() { auto doc = parser.iterate(padded_str).value(); return simdjson_to_person(doc.get_object()); } catch (std::exception &e) { - return rfl::Error(e.what()); + return rfl::error(e.what()); } } @@ -158,7 +158,7 @@ rfl::Result> yyjson_to_children(yyjson_val *_val) { while ((val = yyjson_arr_iter_next(&iter))) { auto r = yyjson_to_person(val); if (!r) { - return *r.error(); + return error(r.error()); } children.emplace_back(std::move(*r)); } @@ -199,8 +199,8 @@ rfl::Result yyjson_to_person(yyjson_val *_val) { } else if (!std::get<2>(found) && name == "children") { auto children = yyjson_to_children(v); if (!children) { - errors.push_back(rfl::Error("Error reading 'children': " + - children.error()->what())); + errors.push_back( + rfl::Error("Error reading 'children': " + children.error().what())); continue; } person.children = std::move(*children); @@ -221,7 +221,7 @@ rfl::Result yyjson_to_person(yyjson_val *_val) { for (const auto &err : errors) { std::cout << err.what() << std::endl; } - return errors[0]; + return error(errors[0]); } return person; } @@ -230,7 +230,7 @@ static rfl::Result read_using_yyjson() { yyjson_doc *doc = yyjson_read(json_string.c_str(), json_string.size(), 0); if (!doc) { std::cout << "Could not parse document!" << std::endl; - return rfl::Error("Could not parse document"); + return rfl::error("Could not parse document"); } yyjson_val *root = yyjson_doc_get_root(doc); auto person = yyjson_to_person(root); @@ -244,7 +244,7 @@ static void BM_person_read_nlohmann(benchmark::State &state) { for (auto _ : state) { const auto res = read_using_nlohmann(); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -254,7 +254,7 @@ static void BM_person_read_rapidjson(benchmark::State &state) { for (auto _ : state) { const auto res = read_using_rapidjson(); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -264,7 +264,7 @@ static void BM_person_read_simdjson(benchmark::State &state) { for (auto _ : state) { const auto res = read_using_simdjson(); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -274,7 +274,7 @@ static void BM_person_read_yyjson(benchmark::State &state) { for (auto _ : state) { const auto res = read_using_yyjson(); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -284,7 +284,7 @@ static void BM_person_read_reflect_cpp(benchmark::State &state) { for (auto _ : state) { const auto res = rfl::json::read(json_string); if (!res) { - std::cout << res.error()->what() << std::endl; + std::cout << res.error().what() << std::endl; } } } @@ -293,4 +293,3 @@ BENCHMARK(BM_person_read_reflect_cpp); // ---------------------------------------------------------------------------- } // namespace person_read - diff --git a/docs/install.md b/docs/install.md index 224e2a19..ef099db3 100644 --- a/docs/install.md +++ b/docs/install.md @@ -41,7 +41,7 @@ Simply use [this recipe](https://conan.io/center/recipes/reflect-cpp). This will compile reflect-cpp with JSON support only. You can then include reflect-cpp in your project and link to the binary. ```bash -cmake -S . -B build -DCMAKE_BUILD_TYPE=Release +cmake -S . -B build -DCMAKE_CXX_STANDARD=20 -DCMAKE_BUILD_TYPE=Release cmake --build build -j 4 # gcc, clang cmake --build build --config Release -j 4 # MSVC ``` @@ -66,6 +66,14 @@ git submodule update --init # You may be prompted to install additional dependencies. ``` +To compile the library: + +```bash +cmake -S . -B build -DCMAKE_CXX_STANDARD=20 -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 +``` + To use reflect-cpp in your project: ```cmake @@ -84,6 +92,7 @@ set(REFLECTCPP_YAML ON) # Optional target_link_libraries(your_project PRIVATE reflectcpp) # Link against the library ``` + ### Troubleshooting vcpkg vcpkg is a great, but very ambitious and complex project (just like C++ is a great, but very ambitious and complex language). Here are some of the you might run into and how to resolve them: diff --git a/docs/result.md b/docs/result.md index c4e7403e..94bc930d 100644 --- a/docs/result.md +++ b/docs/result.md @@ -32,6 +32,9 @@ in C++-23. However, reflect-cpp is a library for C++-20 and until that changes, If you do not care about these objections to exceptions, you can just call `rfl::json::read<...>(json_string).value()`, which throws an exception, if the result type contains an error and be done with it. +**Note**: If you want to use `std::expected` instead of our own Result type, you can pass `-DREFLECTCPP_USE_STD_EXPECTED` during compilation. +This requires C++-23 support and may not be supported on all C++ compilers. + ## What is `rfl::Result`? `rfl::Result` is similar to `std::optional` it that it contains an object that may or may not be there. However, @@ -115,7 +118,7 @@ if you are wrong. If you want the underlying value of type T or some kind of default value, you can call `.value_or(your_default_value)`. -If you want to retrieve the error, you can call `.error()`, which will return a value of type `std::optional`. +If you want to retrieve the error, you can call `.error()`, which will return a value of type `rfl::Error`. If you want to check whether the result contains an error, you can just use the bool operator: @@ -126,34 +129,26 @@ if (my_result) { auto v = *my_result; } else { // my_result must contain an error. - auto err = my_result.error().value(); + auto err = my_result.error(); } ``` -## Iterating over `rfl::Result` +## `rfl::error` -`rfl::Result` can be iterated over, as it contains either zero or one values of type `T`: +`rfl::error("error message")` is a simple utility function for `rfl::Unexpected(Error("error message"))`. -```cpp -for (const auto& v: my_result) { - // If you are inside this loop, then my_result did not contain an error. -} -``` - -## `.and_other(...)`, `.or_else(...)`, `.or_other(...)` - -`r1.and_other(r2)` expects an `r2` or type `rfl::Result`. It returns an error, if `r1` contains an error and `r2` otherwise. +## `.or_else(...)`, `.transform_error(...)` `r.or_else(f)` expects a function `f` for type `Error -> rfl::Result`. It returns `r` if `r` did not contain an error and the results of `f` otherwise. +`r.transform_error(f)` expects a function `f` for type `Error -> Error`. + This is often used to produce better error messages: ```cpp const auto embellish_error = [&](const Error& _e) -> rfl::Result { - return Error("Failed to parse field '" + key + "': " + _e.what()); + return rfl::error("Failed to parse field '" + key + "': " + _e.what()); }; -return Parser::read(_r, &_var).or_else(embellish_error); +return Parser::read(_r, &_var).transform_error(embellish_error); ``` -`r1.or_other(r2)` expects an `r2` or type `rfl::Result`. It returns an `r1`, if `r1` does not contain an error and `r2` otherwise. - diff --git a/docs/supported_formats/supporting_your_own_format.md b/docs/supported_formats/supporting_your_own_format.md index c6a85ac3..b3f7ba71 100644 --- a/docs/supported_formats/supporting_your_own_format.md +++ b/docs/supported_formats/supporting_your_own_format.md @@ -231,7 +231,7 @@ struct Reader { const InputVarType& _var) const noexcept { // If you do not want to support this functionality, // just return this. - return rfl::Error("Not supported."); + return rfl::error("Not supported."); } }; ``` diff --git a/include/rfl/AddStructName.hpp b/include/rfl/AddStructName.hpp index 5e4a1524..6f6cd5db 100644 --- a/include/rfl/AddStructName.hpp +++ b/include/rfl/AddStructName.hpp @@ -17,14 +17,14 @@ template struct AddStructName { /// Adds the name of the struct as a new field. template - static auto process(auto&& _view) { + static auto process(const auto& _view) { using LiteralType = Literal< internal::remove_namespaces()>()>; using FieldType = Field; - const auto add_new_field = [](auto&&... _fields) { - return make_named_tuple(FieldType(LiteralType()), std::move(_fields)...); + const auto add_new_field = [](const auto&... _fields) { + return make_named_tuple(FieldType(LiteralType()), _fields...); }; - return rfl::apply(add_new_field, std::move(_view.fields())); + return rfl::apply(add_new_field, _view.fields()); } }; diff --git a/include/rfl/AnyOf.hpp b/include/rfl/AnyOf.hpp index 6ef15583..2d74fcc2 100644 --- a/include/rfl/AnyOf.hpp +++ b/include/rfl/AnyOf.hpp @@ -28,23 +28,23 @@ struct AnyOf { } private: - static Error make_error_message(const std::vector& _errors) { + static std::string make_error_message(const std::vector& _errors) { std::stringstream stream; stream << "Expected at least one of the following validations to pass, but " "none of them did:"; for (size_t i = 0; i < _errors.size(); ++i) { stream << "\n" << i + 1 << ") " << _errors.at(i).what(); } - return Error(stream.str()); + return stream.str(); } template static rfl::Result validate_impl(const T& _value, std::vector _errors) { - const auto handle_err = [&](Error&& _err) { + const auto handle_err = [&](Error&& _err) -> rfl::Result { _errors.push_back(std::forward(_err)); if constexpr (sizeof...(Tail) == 0) { - return make_error_message(_errors); + return error(make_error_message(_errors)); } else { return validate_impl( _value, std::forward>(_errors)); diff --git a/include/rfl/Box.hpp b/include/rfl/Box.hpp index e3063246..140f0af1 100644 --- a/include/rfl/Box.hpp +++ b/include/rfl/Box.hpp @@ -26,7 +26,7 @@ class Box { /// return an Error, if the unique_ptr is not set. static Result> make(std::unique_ptr&& _ptr) { if (!_ptr) { - return Error("std::unique_ptr was a nullptr."); + return error("std::unique_ptr was a nullptr."); } return Box(std::move(_ptr)); } diff --git a/include/rfl/Generic.hpp b/include/rfl/Generic.hpp index 9cd4389b..e7463de5 100644 --- a/include/rfl/Generic.hpp +++ b/include/rfl/Generic.hpp @@ -80,31 +80,83 @@ class Generic { /// Casts the underlying value to an rfl::Generic::Array or returns an /// rfl::Error, if the underlying value is not an rfl::Generic::Array. - Result to_array() const noexcept; + Result to_array() const noexcept { + if (const auto* ptr = std::get_if(&value_)) { + return *ptr; + } else { + return error( + "rfl::Generic: Could not cast the underlying value to an " + "rfl::Generic::Array."); + } + } /// Casts the underlying value to a boolean or returns an rfl::Error, if the /// underlying value is not a boolean. - Result to_bool() const noexcept; + Result to_bool() const noexcept { + if (const bool* ptr = std::get_if(&value_)) { + return *ptr; + } else { + return error( + "rfl::Generic: Could not cast the underlying value to a boolean."); + } + } /// Casts the underlying value to a double or returns an rfl::Error, if the /// underlying value is not a double. - Result to_double() const noexcept; + Result to_double() const noexcept { + if (const double* ptr = std::get_if(&value_)) { + return *ptr; + } else { + return error( + "rfl::Generic: Could not cast the underlying value to a double."); + } + } /// Casts the underlying value to an integer or returns an rfl::Error, if the /// underlying value is not an integer. - Result to_int() const noexcept; + Result to_int() const noexcept { + if (const int* ptr = std::get_if(&value_)) { + return *ptr; + } else { + return error( + "rfl::Generic: Could not cast the underlying value to an integer."); + } + } /// Casts the underlying value to an rfl::Generic::Object or returns an /// rfl::Error, if the underlying value is not an rfl::Generic::Object. - Result to_object() const noexcept; + Result to_object() const noexcept { + if (const auto* ptr = std::get_if(&value_)) { + return *ptr; + } else { + return error( + "rfl::Generic: Could not cast the underlying value to an " + "rfl::Generic::Object."); + } + } /// Casts the underlying value to rfl::Generic::Null or returns an /// rfl::Error, if the underlying value is not rfl::Generic::Null. - Result to_null() const noexcept; + Result to_null() const noexcept { + if (const auto* ptr = std::get_if(&value_)) { + return *ptr; + } else { + return error( + "rfl::Generic: Could not cast the underlying value to " + "rfl::Generic::Null."); + } + } /// Casts the underlying value to a string or returns an rfl::Error, if the /// underlying value is not a string. - Result to_string() const noexcept; + Result to_string() const noexcept { + if (const auto* ptr = std::get_if(&value_)) { + return *ptr; + } else { + return error( + "rfl::Generic: Could not cast the underlying value to a string."); + } + } /// Returns the underlying variant. VariantType& variant() noexcept { return value_; }; diff --git a/include/rfl/Literal.hpp b/include/rfl/Literal.hpp index 40d0e9d6..9aa1b39d 100644 --- a/include/rfl/Literal.hpp +++ b/include/rfl/Literal.hpp @@ -75,7 +75,7 @@ class Literal { /// Constructs a new Literal. static Result> from_value(ValueType _value) { if (_value >= num_fields_) { - return Error("Value cannot exceed number of fields."); + return error("Value cannot exceed number of fields."); } return Literal(_value); } @@ -161,7 +161,7 @@ class Literal { /// Assigns the literal from a string Literal& operator=(const std::string& _str) { - value_ = find_value(_str); + value_ = find_value(_str).value(); return *this; } @@ -306,7 +306,7 @@ class Literal { const auto idx = find_value_set_idx( _str, &found, std::make_integer_sequence()); if (!found) { - return Error( + return error( "Literal does not support string '" + _str + "'. The following strings are supported: " + allowed_strings() + "."); } diff --git a/include/rfl/Object.hpp b/include/rfl/Object.hpp index 1fca958a..bdd26e9e 100644 --- a/include/rfl/Object.hpp +++ b/include/rfl/Object.hpp @@ -202,20 +202,20 @@ class Object { Result get(const std::string& _key) const noexcept { const auto i = find(_key); if (i == size()) { - return Error("Key named '" + _key + "' not found."); + return error("Key named '" + _key + "' not found."); } return data_[i].second; } private: size_t find(const std::string& _key) const { - for (auto i = i_; i < size(); ++i) { + for (size_t i = i_; i < size(); ++i) { if (data_[i].first == _key) { i_ = i + 1; return i; } } - for (auto i = 0; i < i_; ++i) { + for (size_t i = 0; i < i_; ++i) { if (data_[i].first == _key) { i_ = i + 1; return i; diff --git a/include/rfl/OneOf.hpp b/include/rfl/OneOf.hpp index c1a8383f..3dd59cf8 100644 --- a/include/rfl/OneOf.hpp +++ b/include/rfl/OneOf.hpp @@ -28,7 +28,7 @@ struct OneOf { } private: - static Error make_error_message(const std::vector& _errors) { + static std::string make_error_message(const std::vector& _errors) { std::stringstream stream; stream << "Expected exactly 1 out of " << sizeof...(Cs) + 1 << " validations to pass, but " << sizeof...(Cs) + 1 - _errors.size() @@ -36,34 +36,31 @@ struct OneOf { for (size_t i = 0; i < _errors.size(); ++i) { stream << "\n" << i + 1 << ") " << _errors.at(i).what(); } - return Error(stream.str()); + return stream.str(); } template static rfl::Result validate_impl(const T& _value, std::vector _errors) { - const auto push_back = [&](Error&& _err) -> rfl::Result { - _errors.emplace_back(std::forward(_err)); - return _err; - }; - - const auto next_validation = [&](rfl::Result&& _r) -> rfl::Result { - _r.or_else(push_back); - - if constexpr (sizeof...(Tail) == 0) { - if (_errors.size() == sizeof...(Cs)) { - return _value; - } - return make_error_message(_errors); - } else { - return validate_impl( - _value, std::forward>(_errors)); - } - }; - return Head::validate(_value) - .and_then(next_validation) - .or_else(next_validation); + .and_then([&](auto&& _res) -> rfl::Result { + if constexpr (sizeof...(Tail) == 0) { + if (_errors.size() == sizeof...(Cs)) { + return _value; + } + return error(make_error_message(_errors)); + } else { + return validate_impl(_value, std::move(_errors)); + } + }) + .or_else([&](auto&& _err) -> rfl::Result { + _errors.emplace_back(std::move(_err)); + if constexpr (sizeof...(Tail) == 0) { + return error(make_error_message(_errors)); + } else { + return validate_impl(_value, std::move(_errors)); + } + }); } }; diff --git a/include/rfl/PatternValidator.hpp b/include/rfl/PatternValidator.hpp index 522fd8b8..c5b77992 100644 --- a/include/rfl/PatternValidator.hpp +++ b/include/rfl/PatternValidator.hpp @@ -29,7 +29,7 @@ struct PatternValidator { std::stringstream stream; stream << "String '" << _str << "' did not match format '" << _name.str() << "': '" << _regex.str() << "'."; - return rfl::Error(stream.str()); + return error(stream.str()); } } diff --git a/include/rfl/Ref.hpp b/include/rfl/Ref.hpp index e26964ab..fce3e6ba 100644 --- a/include/rfl/Ref.hpp +++ b/include/rfl/Ref.hpp @@ -26,7 +26,7 @@ class Ref { /// return an Error, if the shared_ptr is not set. static Result> make(std::shared_ptr&& _ptr) { if (!_ptr) { - return Error("std::shared_ptr was a nullptr."); + return error("std::shared_ptr was a nullptr."); } return Ref(std::move(_ptr)); } @@ -35,7 +35,7 @@ class Ref { /// return an Error, if the shared_ptr is not set. static Result> make(const std::shared_ptr& _ptr) { if (!_ptr) { - return Error("std::shared_ptr was a nullptr."); + return error("std::shared_ptr was a nullptr."); } return Ref(_ptr); } @@ -145,4 +145,3 @@ inline void swap(rfl::Ref& _r1, rfl::Ref& _r2) { } // namespace std #endif // RFL_REF_HPP_ - diff --git a/include/rfl/Result.hpp b/include/rfl/Result.hpp index a21e239c..5309b9aa 100644 --- a/include/rfl/Result.hpp +++ b/include/rfl/Result.hpp @@ -1,26 +1,27 @@ #ifndef RFL_RESULT_HPP_ #define RFL_RESULT_HPP_ +#ifdef REFLECTCPP_USE_STD_EXPECTED +#include +#endif + #include #include +#include #include #include #include #include #include -#include "internal/is_array.hpp" -#include "internal/ptr_cast.hpp" -#include "internal/to_std_array.hpp" - namespace rfl { -/// To be returned +/// Defines the error class to be returned when something went wrong class Error { public: Error(const std::string& _what) : what_(_what) {} - - ~Error() = default; + Error(const Error& e) = default; + Error& operator=(const Error&) = default; /// Returns the error message, equivalent to .what() in std::exception. const std::string& what() const { return what_; } @@ -30,10 +31,37 @@ class Error { std::string what_; }; -/// Can be used when we are simply interested in whether an operation was -/// successful. +/// To be returned when there is nothing to return, but there might be an error. struct Nothing {}; +/// This implementation is for cases where std::expected is defined +#ifdef REFLECTCPP_USE_STD_EXPECTED + +template +using Unexpected = std::unexpected; + +template +using Result = std::expected; + +/// This implementation is for cases where std::expected is not defined +#else // REFLECTCPP_USE_STD_EXPECTED + +template +struct Unexpected { + Unexpected(E&& _err) : err_{std::forward(_err)} {} + Unexpected(const E& _err) : err_{_err} {} + Unexpected(Unexpected&&) = default; + Unexpected(const Unexpected&) = default; + Unexpected& operator=(Unexpected&&) = default; + Unexpected& operator=(const Unexpected&) = default; + const E& error() const& { return err_; } + E&& error() && { return std::move(err_); } + E& error() & { return err_; } + + private: + E err_; +}; + /// The Result class is used for monadic error handling. template class Result { @@ -42,7 +70,9 @@ class Result { using TOrErr = std::array; public: - using Type = T; + // using Type = T; + using value_type = T; + using error_type = rfl::Error; Result(const T& _val) : success_(true) { new (&get_t()) T(_val); } @@ -50,11 +80,16 @@ class Result { new (&get_t()) T(std::move(_val)); } - Result(const Error& _err) : success_(false) { new (&get_err()) Error(_err); } - - Result(Error&& _err) noexcept : success_(false) { - new (&get_err()) Error(std::move(_err)); + Result(const Unexpected& _err) : success_(false) { + new (&get_err()) Error(_err.error()); } + Result(Unexpected&& _err) : success_(false) { + new (&get_err()) Error(std::move(_err.error())); + } + + // Result(Error&& _err) noexcept : success_(false) { + // new (&get_err()) Error(std::move(_err)); + // } Result(Result&& _other) noexcept : success_(_other.success_) { move_from_other(_other); @@ -67,7 +102,7 @@ class Result { template , bool>::type = true> Result(Result&& _other) : success_(_other && true) { - auto temp = std::forward>(_other).transform( + auto temp = std::forward >(_other).transform( [](U&& _u) { return T(std::forward(_u)); }); move_from_other(temp); } @@ -81,14 +116,6 @@ class Result { ~Result() { destroy(); } - /// Returns Result, if successful and error otherwise. - /// Inspired by .and(...) in the Rust std::result type. - template - Result and_other(const Result& _r) const noexcept { - const auto f = [&](const auto& _) { return _r; }; - return and_then(f); - } - /// Monadic operation - F must be a function of type T -> Result. template auto and_then(const F& _f) { @@ -113,56 +140,6 @@ class Result { } } - /// Results types can be iterated over, which even make it possible to use - /// them within a std::range. - T* begin() noexcept { - if (success_) { - return &get_t(); - } else { - return nullptr; - } - } - - /// Results types can be iterated over, which even make it possible to use - /// them within a std::range. - const T* begin() const noexcept { - if (success_) { - return &get_t(); - } else { - return nullptr; - } - } - - /// Results types can be iterated over, which even make it possible to use - /// them within a std::range. - T* end() noexcept { - if (success_) { - return &get_t() + 1; - } else { - return nullptr; - } - } - - /// Results types can be iterated over, which even make it possible to use - /// them within a std::range. - const T* end() const noexcept { - if (success_) { - return &get_t() + 1; - } else { - return nullptr; - } - } - - /// Returns an std::optional if this does in fact contain an error - /// or std::nullopt otherwise. - std::optional error() const noexcept { - if (success_) { - return std::nullopt; - } else { - return get_err(); - } - } - /// Returns true if the result contains a value, false otherwise. operator bool() const noexcept { return success_; } @@ -196,6 +173,19 @@ class Result { return *this; } + Result& operator=(Unexpected&& _err) noexcept { + destroy(); + success_ = false; + new (&get_err()) Error(_err.error()); + return *this; + } + Result& operator=(const Unexpected& _err) noexcept { + destroy(); + success_ = false; + new (&get_err()) Error(_err.error()); + return *this; + } + /// Assigns the underlying object. template , bool>::type = true> @@ -227,13 +217,6 @@ class Result { } } - /// Returns the value contained if successful or the provided result r if - /// not. - Result or_other(const Result& _r) const noexcept { - const auto f = [&](const auto& _) { return _r; }; - return or_else(f); - } - /// Functor operation - F must be a function of type T -> U. template auto transform(const F& _f) { @@ -242,7 +225,7 @@ class Result { if (success_) { return rfl::Result(_f(std::forward(get_t()))); } else { - return rfl::Result(std::forward(get_err())); + return rfl::Result(rfl::Unexpected(std::forward(get_err()))); } } @@ -296,6 +279,59 @@ class Result { } } + // As specified by the standard : + // https://en.cppreference.com/w/cpp/utility/expected + // Observers + template + rfl::Error error_or(G&& _default) const& { + if (success_) { + return _default; + } else { + return get_err(); + } + } + template + rfl::Error error_or(G&& _default) && { + if (success_) { + return _default; + } else { + return get_err(); + } + } + bool has_value() const noexcept { return success_; } + const Error& error() const& { + if (success_) throw std::runtime_error("Expected does not contain value"); + return get_err(); + } + Error& error() & { + if (success_) throw std::runtime_error("Expected does not contain value"); + return get_err(); + } + T* operator->() noexcept { return &get_t(); } + const T* operator->() const noexcept { return &get_t(); } + template + rfl::Result transform_error(F&& f) && { + static_assert( + std::is_same, rfl::Error>(), + "A function passed to transform_error must return an error."); + if (!has_value()) { + return rfl::Result{std::invoke(f, std::move(get_err()))}; + } else { + return rfl::Result{std::move(value())}; + } + } + template + rfl::Result transform_error(F&& f) const& { + static_assert( + std::is_same, rfl::Error>(), + "A function passed to transform_error must return an error."); + if (!has_value()) { + return rfl::Result{std::invoke(f, get_err())}; + } else { + return rfl::Result{value()}; + } + } + private: void copy_from_other(const Result& _other) { if (success_) { @@ -307,7 +343,7 @@ class Result { void destroy() { if (success_) { - if constexpr (std::is_destructible_v>) { + if constexpr (std::is_destructible_v >) { get_t().~T(); } } else { @@ -338,8 +374,6 @@ class Result { new (&get_err()) Error(std::move(_other.get_err())); } } - - private: /// Signifies whether this was a success. bool success_; @@ -347,6 +381,18 @@ class Result { alignas(std::max(alignof(T), alignof(Error))) TOrErr t_or_err_; }; +#endif + +/// Shorthand for unexpected error. +inline Unexpected error(const std::string& _what) { + return Unexpected(Error(_what)); +} + +/// Shorthand for unexpected error. +inline Unexpected error(const Error& _err) { + return Unexpected(_err); +} + } // namespace rfl #endif diff --git a/include/rfl/Size.hpp b/include/rfl/Size.hpp index 5a8b33ca..72f13333 100644 --- a/include/rfl/Size.hpp +++ b/include/rfl/Size.hpp @@ -14,10 +14,11 @@ struct Size { template static rfl::Result validate(const T& _t) { const auto to_t = [&](const auto&) { return _t; }; - const auto embellish_error = [](const auto& _err) { + const auto embellish_error = [](const auto& _err) -> Error { return Error("Size validation failed: " + _err.what()); }; - return V::validate(_t.size()).transform(to_t).or_else(embellish_error); + return V::validate(_t.size()).transform(to_t).transform_error( + embellish_error); } template diff --git a/include/rfl/SnakeCaseToCamelCase.hpp b/include/rfl/SnakeCaseToCamelCase.hpp index 847e1258..2681e1f6 100644 --- a/include/rfl/SnakeCaseToCamelCase.hpp +++ b/include/rfl/SnakeCaseToCamelCase.hpp @@ -11,22 +11,21 @@ struct SnakeCaseToCamelCase { public: /// Replaces all instances of snake_case field names with camelCase. template - static auto process(auto&& _named_tuple) { - const auto handle_one = [](FieldType&& _f) { + static auto process(const auto& _named_tuple) { + return _named_tuple.transform([](const FieldType& _f) { if constexpr (FieldType::name() != "xml_content" && !internal::is_rename_v) { - return handle_one_field(std::move(_f)); + return handle_one_field(_f); } else { - return std::move(_f); + return _f; } - }; - return _named_tuple.transform(handle_one); + }); } private: /// Applies the logic to a single field. template - static auto handle_one_field(FieldType&& _f) { + static auto handle_one_field(const FieldType& _f) { using NewFieldType = Field(), diff --git a/include/rfl/SnakeCaseToPascalCase.hpp b/include/rfl/SnakeCaseToPascalCase.hpp index 623a151b..1eb45437 100644 --- a/include/rfl/SnakeCaseToPascalCase.hpp +++ b/include/rfl/SnakeCaseToPascalCase.hpp @@ -11,13 +11,13 @@ struct SnakeCaseToPascalCase { public: /// Replaces all instances of snake_case field names with PascalCase. template - static auto process(auto&& _named_tuple) { - const auto handle_one = [](FieldType&& _f) { + static auto process(const auto& _named_tuple) { + const auto handle_one = [](const FieldType& _f) { if constexpr (FieldType::name() != "xml_content" && !internal::is_rename_v) { - return handle_one_field(std::move(_f)); + return handle_one_field(_f); } else { - return std::move(_f); + return _f; } }; return _named_tuple.transform(handle_one); @@ -26,7 +26,7 @@ struct SnakeCaseToPascalCase { private: /// Applies the logic to a single field. template - static auto handle_one_field(FieldType&& _f) { + static auto handle_one_field(const FieldType& _f) { using NewFieldType = Field(), diff --git a/include/rfl/Timestamp.hpp b/include/rfl/Timestamp.hpp index b8d57e38..d5302683 100644 --- a/include/rfl/Timestamp.hpp +++ b/include/rfl/Timestamp.hpp @@ -45,7 +45,7 @@ class Timestamp { try { return Timestamp(_str); } catch (std::exception& e) { - return Error(e.what()); + return error(e.what()); } } diff --git a/include/rfl/Validator.hpp b/include/rfl/Validator.hpp index 62e4e570..0673c9e3 100644 --- a/include/rfl/Validator.hpp +++ b/include/rfl/Validator.hpp @@ -25,7 +25,7 @@ struct Validator { try { return Validator(_value); } catch (std::exception& e) { - return Error(e.what()); + return error(e.what()); } } diff --git a/include/rfl/Variant.hpp b/include/rfl/Variant.hpp index fbee31a7..4fe609cb 100644 --- a/include/rfl/Variant.hpp +++ b/include/rfl/Variant.hpp @@ -14,6 +14,7 @@ #include "internal/variant/find_max_size.hpp" #include "internal/variant/is_alternative_type.hpp" #include "internal/variant/result_t.hpp" +#include "internal/ptr_cast.hpp" namespace rfl { diff --git a/include/rfl/avro/Parser.hpp b/include/rfl/avro/Parser.hpp index 73276631..095e6254 100644 --- a/include/rfl/avro/Parser.hpp +++ b/include/rfl/avro/Parser.hpp @@ -48,7 +48,7 @@ struct Parser { template static Result read(const avro::Reader&, const T&) noexcept { static_assert(always_false_v, "Generics are unsupported in Avro."); - return Error("Unsupported"); + return error("Unsupported"); } template diff --git a/include/rfl/avro/Reader.hpp b/include/rfl/avro/Reader.hpp index 528d1c51..3f7fd0be 100644 --- a/include/rfl/avro/Reader.hpp +++ b/include/rfl/avro/Reader.hpp @@ -14,6 +14,7 @@ #include "../Result.hpp" #include "../always_false.hpp" #include "../internal/is_literal.hpp" +#include "../parsing/schemaful/IsSchemafulReader.hpp" namespace rfl::avro { @@ -48,7 +49,9 @@ struct Reader { static constexpr bool has_custom_constructor = (requires(InputVarType var) { T::from_avro_obj(var); }); - bool is_empty(const InputVarType& _var) const noexcept; + bool is_empty(const InputVarType& _var) const noexcept { + return avro_value_get_type(_var.val_) == AVRO_NULL; + } template rfl::Result to_basic_type(const InputVarType& _var) const noexcept { @@ -58,7 +61,7 @@ struct Reader { size_t size = 0; const auto err = avro_value_get_string(_var.val_, &c_str, &size); if (err) { - return Error("Could not cast to string."); + return error("Could not cast to string."); } if (size == 0) { return std::string(""); @@ -70,12 +73,12 @@ struct Reader { size_t size = 0; const auto err = avro_value_get_bytes(_var.val_, &ptr, &size); if (err) { - return Error("Could not cast to bytestring."); + return error("Could not cast to bytestring."); } return rfl::Bytestring(static_cast(ptr), size - 1); } else if constexpr (std::is_same, bool>()) { if (type != AVRO_BOOLEAN) { - return rfl::Error("Could not cast to boolean."); + return rfl::error("Could not cast to boolean."); } int result = 0; avro_value_get_boolean(_var.val_, &result); @@ -87,32 +90,32 @@ struct Reader { double result = 0.0; const auto err = avro_value_get_double(_var.val_, &result); if (err) { - return Error("Could not cast to double."); + return error("Could not cast to double."); } return static_cast(result); } else if (type == AVRO_INT32) { int32_t result = 0; const auto err = avro_value_get_int(_var.val_, &result); if (err) { - return Error("Could not cast to int32."); + return error("Could not cast to int32."); } return static_cast(result); } else if (type == AVRO_INT64) { int64_t result = 0; const auto err = avro_value_get_long(_var.val_, &result); if (err) { - return Error("Could not cast to int64."); + return error("Could not cast to int64."); } return static_cast(result); } else if (type == AVRO_FLOAT) { float result = 0.0; const auto err = avro_value_get_float(_var.val_, &result); if (err) { - return Error("Could not cast to float."); + return error("Could not cast to float."); } return static_cast(result); } - return rfl::Error( + return rfl::error( "Could not cast to numeric value. The type must be integral, float " "or double."); @@ -120,7 +123,7 @@ struct Reader { int value = 0; const auto err = avro_value_get_enum(_var.val_, &value); if (err) { - return Error("Could not cast to enum."); + return error("Could not cast to enum."); } return std::remove_cvref_t::from_value( static_cast::ValueType>(value)); @@ -130,14 +133,39 @@ struct Reader { } } - rfl::Result to_array(const InputVarType& _var) const noexcept; + rfl::Result to_array( + const InputVarType& _var) const noexcept { + if (avro_value_get_type(_var.val_) != AVRO_ARRAY) { + return error("Could not cast to an array."); + } + return InputArrayType{_var.val_}; + } rfl::Result to_object( - const InputVarType& _var) const noexcept; + const InputVarType& _var) const noexcept { + const auto type = avro_value_get_type(_var.val_); + if (type != AVRO_RECORD) { + return error("Could not cast to an object."); + } + return InputObjectType{_var.val_}; + } - rfl::Result to_map(const InputVarType& _var) const noexcept; + rfl::Result to_map(const InputVarType& _var) const noexcept { + const auto type = avro_value_get_type(_var.val_); + if (type != AVRO_MAP) { + return error("Could not cast to a map."); + } + return InputMapType{_var.val_}; + } - rfl::Result to_union(const InputVarType& _var) const noexcept; + rfl::Result to_union( + const InputVarType& _var) const noexcept { + const auto type = avro_value_get_type(_var.val_); + if (type != AVRO_UNION) { + return error("Could not cast to a union."); + } + return InputUnionType{_var.val_}; + } template std::optional read_array(const ArrayReader& _array_reader, @@ -188,12 +216,12 @@ struct Reader { int disc = 0; auto err = avro_value_get_discriminant(_union.val_, &disc); if (err) { - return Error("Could not get the discriminant."); + return error("Could not get the discriminant."); } avro_value_t value; err = avro_value_get_current_branch(_union.val_, &value); if (err) { - return Error("Could not cast the union type."); + return error("Could not cast the union type."); } return UnionReaderType::read(*this, static_cast(disc), InputVarType{&value}); @@ -205,11 +233,14 @@ struct Reader { try { return T::from_avro_obj(_var); } catch (std::exception& e) { - return rfl::Error(e.what()); + return rfl::error(e.what()); } } }; +static_assert(parsing::schemaful::IsSchemafulReader, + "This must be a schemaful reader."); + } // namespace rfl::avro #endif diff --git a/include/rfl/avro/Schema.hpp b/include/rfl/avro/Schema.hpp index 0b4fb2d6..e2bde4fc 100644 --- a/include/rfl/avro/Schema.hpp +++ b/include/rfl/avro/Schema.hpp @@ -20,7 +20,7 @@ class Schema { try { return Schema(_json_str); } catch (std::exception& e) { - return Error(e.what()); + return error(e.what()); } } diff --git a/include/rfl/avro/read.hpp b/include/rfl/avro/read.hpp index 7b343664..be58f88c 100644 --- a/include/rfl/avro/read.hpp +++ b/include/rfl/avro/read.hpp @@ -38,7 +38,7 @@ Result> read( if (err) { avro_value_decref(&root); avro_reader_free(avro_reader); - return Error(std::string("Could not read root value: ") + avro_strerror()); + return error(std::string("Could not read root value: ") + avro_strerror()); } auto result = read(InputVarType{&root}); avro_value_decref(&root); diff --git a/include/rfl/avro/schema/Type.hpp b/include/rfl/avro/schema/Type.hpp index 2ec25522..d44f3589 100644 --- a/include/rfl/avro/schema/Type.hpp +++ b/include/rfl/avro/schema/Type.hpp @@ -8,6 +8,7 @@ #include "../../Literal.hpp" #include "../../Object.hpp" +#include "../../Ref.hpp" #include "../../Rename.hpp" #include "../../Variant.hpp" diff --git a/include/rfl/bson/Reader.hpp b/include/rfl/bson/Reader.hpp index 28302493..494dfc53 100644 --- a/include/rfl/bson/Reader.hpp +++ b/include/rfl/bson/Reader.hpp @@ -50,12 +50,49 @@ struct Reader { (requires(InputVarType var) { T::from_bson_obj(var); }); rfl::Result get_field_from_array( - const size_t _idx, const InputArrayType& _arr) const noexcept; + const size_t _idx, const InputArrayType& _arr) const noexcept { + bson_t b; + bson_iter_t iter; + const auto doc = _arr.val_->value.v_doc; + if (bson_init_static(&b, doc.data, doc.data_len)) { + if (bson_iter_init(&iter, &b)) { + size_t i = 0; + while (bson_iter_next(&iter)) { + if (i == _idx) { + return to_input_var(&iter); + } + ++i; + } + } else { + return error("Could not init the array iteration."); + } + } else { + return error("Could not init array."); + } + return error("Index " + std::to_string(_idx) + " of of bounds."); + } rfl::Result get_field_from_object( - const std::string& _name, const InputObjectType& _obj) const noexcept; + const std::string& _name, const InputObjectType& _obj) const noexcept { + bson_t b; + bson_iter_t iter; + const auto doc = _obj.val_->value.v_doc; + if (bson_init_static(&b, doc.data, doc.data_len)) { + if (bson_iter_init(&iter, &b)) { + while (bson_iter_next(&iter)) { + auto key = std::string(bson_iter_key(&iter)); + if (key == _name) { + return to_input_var(&iter); + } + } + } + } + return error("No field named '" + _name + "' was found."); + } - bool is_empty(const InputVarType& _var) const noexcept; + bool is_empty(const InputVarType& _var) const noexcept { + return _var.val_->value_type == BSON_TYPE_NULL; + } template rfl::Result to_basic_type(const InputVarType& _var) const noexcept { @@ -70,16 +107,16 @@ struct Reader { return std::string(value.v_symbol.symbol, value.v_symbol.len); default: - return rfl::Error( + return error( "Could not cast to string. The type must be UTF8 or symbol."); } } else if constexpr (std::is_same, rfl::Bytestring>()) { if (btype != BSON_TYPE_BINARY) { - return rfl::Error("Could not cast to bytestring."); + return error("Could not cast to bytestring."); } if (value.v_binary.subtype != BSON_SUBTYPE_BINARY) { - return rfl::Error( + return error( "The BSON subtype must be a binary in order to read into a " "bytestring."); } @@ -88,7 +125,7 @@ struct Reader { value.v_binary.data_len); } else if constexpr (std::is_same, bool>()) { if (btype != BSON_TYPE_BOOL) { - return rfl::Error("Could not cast to boolean."); + return error("Could not cast to boolean."); } return value.v_bool; } else if constexpr (std::is_floating_point>() || @@ -107,13 +144,13 @@ struct Reader { return static_cast(value.v_datetime); default: - return rfl::Error( + return error( "Could not cast to numeric value. The type must be double, " "int32, int64 or date_time."); } } else if constexpr (std::is_same, bson_oid_t>()) { if (btype != BSON_TYPE_OID) { - return rfl::Error("Could not cast to OID."); + return error("Could not cast to OID."); } return value.v_oid; } else { @@ -121,7 +158,14 @@ struct Reader { } } - rfl::Result to_array(const InputVarType& _var) const noexcept; + rfl::Result to_array( + const InputVarType& _var) const noexcept { + const auto btype = _var.val_->value_type; + if (btype != BSON_TYPE_ARRAY && btype != BSON_TYPE_DOCUMENT) { + return error("Could not cast to an array."); + } + return InputArrayType{_var.val_}; + } template std::optional read_array(const ArrayReader& _array_reader, @@ -168,7 +212,13 @@ struct Reader { } rfl::Result to_object( - const InputVarType& _var) const noexcept; + const InputVarType& _var) const noexcept { + const auto btype = _var.val_->value_type; + if (btype != BSON_TYPE_DOCUMENT) { + return error("Could not cast to a document."); + } + return InputObjectType{_var.val_}; + } template rfl::Result use_custom_constructor( @@ -176,12 +226,14 @@ struct Reader { try { return T::from_bson_obj(_var); } catch (std::exception& e) { - return rfl::Error(e.what()); + return error(e.what()); } } private: - InputVarType to_input_var(bson_iter_t* _iter) const noexcept; + InputVarType to_input_var(bson_iter_t* _iter) const noexcept { + return InputVarType{bson_iter_value(_iter)}; + } }; } // namespace bson diff --git a/include/rfl/capnproto/Parser.hpp b/include/rfl/capnproto/Parser.hpp index 0112095b..3a966336 100644 --- a/include/rfl/capnproto/Parser.hpp +++ b/include/rfl/capnproto/Parser.hpp @@ -53,7 +53,7 @@ struct Parser { static Result read(const capnproto::Reader&, const T&) noexcept { static_assert(always_false_v, "Generics are unsupported in Cap'n Proto."); - return Error("Unsupported"); + return error("Unsupported"); } template @@ -87,7 +87,7 @@ struct Parser, "rfl::Skip is unsupported in Cap'n Proto."); - return Error("Unsupported"); + return error("Unsupported"); } template diff --git a/include/rfl/capnproto/Reader.hpp b/include/rfl/capnproto/Reader.hpp index d8d10971..5009a499 100644 --- a/include/rfl/capnproto/Reader.hpp +++ b/include/rfl/capnproto/Reader.hpp @@ -50,21 +50,23 @@ class Reader { static constexpr bool has_custom_constructor = (requires(InputVarType var) { T::from_capnproto_obj(var); }); - bool is_empty(const InputVarType& _var) const noexcept; + bool is_empty(const InputVarType& _var) const noexcept { + return _var.val_.getType() == capnp::DynamicValue::VOID; + } template rfl::Result to_basic_type(const InputVarType& _var) const noexcept { const auto type = _var.val_.getType(); if constexpr (std::is_same, std::string>()) { if (type != capnp::DynamicValue::TEXT) { - return Error("Could not cast to string."); + return error("Could not cast to string."); } return std::string(_var.val_.as().cStr()); } else if constexpr (std::is_same, rfl::Bytestring>()) { if (type != capnp::DynamicValue::DATA) { - return Error("Could not cast to bytestring."); + return error("Could not cast to bytestring."); } const auto data = _var.val_.as(); return rfl::Bytestring(internal::ptr_cast(data.begin()), @@ -72,7 +74,7 @@ class Reader { } else if constexpr (std::is_same, bool>()) { if (type != capnp::DynamicValue::BOOL) { - return rfl::Error("Could not cast to boolean."); + return error("Could not cast to boolean."); } return _var.val_.as(); @@ -89,14 +91,14 @@ class Reader { return static_cast(_var.val_.as()); default: - return rfl::Error( + return error( "Could not cast to numeric value. The type must be integral, " "float or double."); } } else if constexpr (internal::is_literal_v) { if (type != capnp::DynamicValue::ENUM) { - return rfl::Error("Could not cast to an enum."); + return error("Could not cast to an enum."); } return T::from_value(_var.val_.as().getRaw()); @@ -105,14 +107,36 @@ class Reader { } } - rfl::Result to_array(const InputVarType& _var) const noexcept; + rfl::Result to_array( + const InputVarType& _var) const noexcept { + if (_var.val_.getType() != capnp::DynamicValue::LIST) { + return error("Could not cast to a list."); + } + return InputArrayType{_var.val_.as()}; + } rfl::Result to_object( - const InputVarType& _var) const noexcept; + const InputVarType& _var) const noexcept { + if (_var.val_.getType() != capnp::DynamicValue::STRUCT) { + return error("Could not cast to a struct."); + } + return InputObjectType{_var.val_.as()}; + } - rfl::Result to_map(const InputVarType& _var) const noexcept; + rfl::Result to_map(const InputVarType& _var) const noexcept { + if (_var.val_.getType() != capnp::DynamicValue::STRUCT) { + return error("Could not cast to a map."); + } + return InputMapType{_var.val_.as()}; + } - rfl::Result to_union(const InputVarType& _var) const noexcept; + rfl::Result 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()}; + } template std::optional read_array(const ArrayReader& _array_reader, @@ -157,7 +181,7 @@ class Reader { const InputUnionType& _union) const noexcept { const auto opt_pair = identify_discriminant(_union); if (!opt_pair) { - return Error("Could not get the discriminant."); + return error("Could not get the discriminant."); } const auto& [field, disc] = *opt_pair; return UnionReaderType::read(*this, disc, @@ -170,7 +194,7 @@ class Reader { try { return T::from_capnproto_obj(_var); } catch (std::exception& e) { - return rfl::Error(e.what()); + return error(e.what()); } } diff --git a/include/rfl/capnproto/Schema.hpp b/include/rfl/capnproto/Schema.hpp index 2c4e8893..a453b7fd 100644 --- a/include/rfl/capnproto/Schema.hpp +++ b/include/rfl/capnproto/Schema.hpp @@ -21,7 +21,7 @@ class Schema { try { return Schema(_str); } catch (std::exception& e) { - return Error(e.what()); + return error(e.what()); } } diff --git a/include/rfl/capnproto/SchemaImpl.hpp b/include/rfl/capnproto/SchemaImpl.hpp index b9142a77..090d7e01 100644 --- a/include/rfl/capnproto/SchemaImpl.hpp +++ b/include/rfl/capnproto/SchemaImpl.hpp @@ -6,6 +6,7 @@ #include #include +#include "../Box.hpp" #include "../Result.hpp" namespace rfl::capnproto { diff --git a/include/rfl/capnproto/schema/Type.hpp b/include/rfl/capnproto/schema/Type.hpp index 12bf3be6..ed4814c4 100644 --- a/include/rfl/capnproto/schema/Type.hpp +++ b/include/rfl/capnproto/schema/Type.hpp @@ -9,6 +9,7 @@ #include "../../Literal.hpp" #include "../../Object.hpp" +#include "../../Ref.hpp" #include "../../Rename.hpp" #include "../../Variant.hpp" diff --git a/include/rfl/cbor/Reader.hpp b/include/rfl/cbor/Reader.hpp index 3d891bb7..bb01bf00 100644 --- a/include/rfl/cbor/Reader.hpp +++ b/include/rfl/cbor/Reader.hpp @@ -43,31 +43,45 @@ class Reader { (requires(InputVarType var) { T::from_cbor_obj(var); }); rfl::Result get_field_from_array( - const size_t _idx, const InputArrayType& _arr) const noexcept; + const size_t _idx, const InputArrayType& _arr) const noexcept { + if (_idx >= _arr.val_->size()) { + return error("Index out of range."); + } + return InputVarType{&_arr.val_->at(_idx)}; + } rfl::Result get_field_from_object( - const std::string& _name, const InputObjectType& _obj) const noexcept; + const std::string& _name, const InputObjectType& _obj) const noexcept { + for (auto& kv : _obj.val_->object_range()) { + if (kv.key() == _name) { + return InputVarType{&kv.value()}; + }; + } + return error("Field name '" + _name + "' not found."); + } - bool is_empty(const InputVarType& _var) const noexcept; + bool is_empty(const InputVarType& _var) const noexcept { + return _var.val_->is_null(); + } template rfl::Result to_basic_type(const InputVarType& _var) const noexcept { if constexpr (std::is_same, std::string>()) { if (!_var.val_->is_string()) { - return Error("Could not cast to string."); + return error("Could not cast to string."); } return _var.val_->as(); } else if constexpr (std::is_same, rfl::Bytestring>()) { if (!_var.val_->is_byte_string()) { - return Error("Could not cast to bytestring."); + return error("Could not cast to bytestring."); } const auto vec = _var.val_->as>(); return rfl::Bytestring(internal::ptr_cast(vec.data()), vec.size()); } else if constexpr (std::is_same, bool>()) { if (!_var.val_->is_bool()) { - return rfl::Error("Could not cast to boolean."); + return error("Could not cast to boolean."); } return _var.val_->as(); } else if constexpr (std::is_floating_point>() || @@ -81,7 +95,7 @@ class Reader { if (_var.val_->is_uint64()) { return static_cast(_var.val_->as()); } - return rfl::Error( + return error( "Could not cast to numeric value. The type must be integral, " "float or double."); } else { @@ -89,10 +103,21 @@ class Reader { } } - rfl::Result to_array(const InputVarType& _var) const noexcept; + rfl::Result to_array( + const InputVarType& _var) const noexcept { + if (!_var.val_->is_array()) { + return error("Could not cast to an array."); + } + return InputArrayType{_var.val_}; + } rfl::Result to_object( - const InputVarType& _var) const noexcept; + const InputVarType& _var) const noexcept { + if (!_var.val_->is_object()) { + return error("Could not cast to an object."); + } + return InputObjectType{_var.val_}; + } template std::optional read_array(const ArrayReader& _array_reader, @@ -121,7 +146,7 @@ class Reader { try { return T::from_cbor_obj(_var); } catch (std::exception& e) { - return rfl::Error(e.what()); + return error(e.what()); } } }; diff --git a/include/rfl/comparisons.hpp b/include/rfl/comparisons.hpp index 30ca1aa0..f4a73907 100644 --- a/include/rfl/comparisons.hpp +++ b/include/rfl/comparisons.hpp @@ -14,7 +14,7 @@ struct EqualTo { static Result validate(T _value) noexcept { constexpr auto threshold = static_cast(_threshold); if (_value != threshold) { - return Error("Value expected to be equal to " + + return error("Value expected to be equal to " + std::to_string(threshold) + ", but got " + std::to_string(_value) + "."); } @@ -38,7 +38,7 @@ struct Minimum { static Result validate(T _value) noexcept { constexpr auto threshold = static_cast(_threshold); if (_value < threshold) { - return Error("Value expected to be greater than or equal to " + + return error("Value expected to be greater than or equal to " + std::to_string(threshold) + ", but got " + std::to_string(_value) + "."); } @@ -62,7 +62,7 @@ struct ExclusiveMinimum { static Result validate(T _value) noexcept { constexpr auto threshold = static_cast(_threshold); if (_value <= threshold) { - return Error("Value expected to be greater than " + + return error("Value expected to be greater than " + std::to_string(threshold) + ", but got " + std::to_string(_value) + "."); } @@ -86,7 +86,7 @@ struct Maximum { static Result validate(T _value) noexcept { constexpr auto threshold = static_cast(_threshold); if (_value > threshold) { - return Error("Value expected to be less than or equal to " + + return error("Value expected to be less than or equal to " + std::to_string(threshold) + ", but got " + std::to_string(_value) + "."); } @@ -110,7 +110,7 @@ struct ExclusiveMaximum { static Result validate(T _value) noexcept { constexpr auto threshold = static_cast(_threshold); if (_value >= threshold) { - return Error("Value expected to be less than " + + return error("Value expected to be less than " + std::to_string(threshold) + ", but got " + std::to_string(_value) + "."); } @@ -134,7 +134,7 @@ struct NotEqualTo { static Result validate(T _value) noexcept { constexpr auto threshold = static_cast(_threshold); if (_value == threshold) { - return Error("Value expected to not be equal to " + + return error("Value expected to not be equal to " + std::to_string(threshold) + ", but got " + std::to_string(_value) + "."); } diff --git a/include/rfl/flexbuf/Reader.hpp b/include/rfl/flexbuf/Reader.hpp index ee6a7621..0cbe7b0c 100644 --- a/include/rfl/flexbuf/Reader.hpp +++ b/include/rfl/flexbuf/Reader.hpp @@ -45,41 +45,56 @@ struct Reader { static constexpr bool has_custom_constructor = has_from_flexbuf::value; rfl::Result get_field_from_array( - const size_t _idx, const InputArrayType& _arr) const noexcept; + const size_t _idx, const InputArrayType& _arr) const noexcept { + if (_idx >= _arr.size()) { + return error("Index " + std::to_string(_idx) + " of of bounds."); + } + return _arr[_idx]; + } rfl::Result get_field_from_object( - const std::string& _name, const InputObjectType& _obj) const noexcept; + const std::string& _name, const InputObjectType& _obj) const noexcept { + const auto keys = _obj.Keys(); + for (size_t i = 0; i < keys.size(); ++i) { + if (_name == keys[i].AsString().c_str()) { + return _obj.Values()[i]; + } + } + return error("Map does not contain any element called '" + _name + "'."); + } - bool is_empty(const InputVarType& _var) const noexcept; + bool is_empty(const InputVarType& _var) const noexcept { + return _var.IsNull(); + } template rfl::Result to_basic_type(const InputVarType& _var) const noexcept { if constexpr (std::is_same, std::string>()) { if (!_var.IsString()) { - return rfl::Error("Could not cast to a string."); + return error("Could not cast to a string."); } return std::string(_var.AsString().c_str()); } else if constexpr (std::is_same, rfl::Bytestring>()) { if (!_var.IsBlob()) { - return rfl::Error("Could not cast to a bytestring."); + return error("Could not cast to a bytestring."); } const auto blob = _var.AsBlob(); return rfl::Bytestring(internal::ptr_cast(blob.data()), blob.size()); } else if constexpr (std::is_same, bool>()) { if (!_var.IsBool()) { - return rfl::Error("Could not cast to boolean."); + return error("Could not cast to boolean."); } return _var.AsBool(); } else if constexpr (std::is_floating_point>()) { if (!_var.IsNumeric()) { - return rfl::Error("Could not cast to double."); + return error("Could not cast to double."); } return static_cast(_var.AsDouble()); } else if constexpr (std::is_integral>()) { if (!_var.IsNumeric()) { - return rfl::Error("Could not cast to int."); + return error("Could not cast to int."); } return static_cast(_var.AsInt64()); } else { @@ -115,10 +130,21 @@ struct Reader { return std::nullopt; } - rfl::Result to_array(const InputVarType& _var) const noexcept; + rfl::Result to_array( + const InputVarType& _var) const noexcept { + if (!_var.IsVector()) { + return error("Could not cast to Vector."); + } + return _var.AsVector(); + } rfl::Result to_object( - const InputVarType& _var) const noexcept; + const InputVarType& _var) const noexcept { + if (!_var.IsMap()) { + return error("Could not cast to Map!"); + } + return _var.AsMap(); + } template rfl::Result use_custom_constructor( @@ -126,7 +152,7 @@ struct Reader { try { return T::from_flexbuf(_var); } catch (std::exception& e) { - return rfl::Error(e.what()); + return error(e.what()); } } }; diff --git a/include/rfl/generic/Reader.hpp b/include/rfl/generic/Reader.hpp index 5da2ebe6..c31a4aaa 100644 --- a/include/rfl/generic/Reader.hpp +++ b/include/rfl/generic/Reader.hpp @@ -27,12 +27,21 @@ struct Reader { static constexpr bool has_custom_constructor = false; rfl::Result get_field_from_array( - const size_t _idx, const InputArrayType& _arr) const noexcept; + const size_t _idx, const InputArrayType& _arr) const noexcept { + if (_idx >= _arr.size()) { + return error("Index " + std::to_string(_idx) + " of of bounds."); + } + return _arr[_idx]; + } rfl::Result get_field_from_object( - const std::string& _name, const InputObjectType& _obj) const noexcept; + const std::string& _name, const InputObjectType& _obj) const noexcept { + return _obj.get(_name); + } - bool is_empty(const InputVarType& _var) const noexcept; + bool is_empty(const InputVarType& _var) const noexcept { + return _var.is_null(); + } template rfl::Result to_basic_type(const InputVarType& _var) const noexcept { @@ -72,15 +81,20 @@ struct Reader { return std::nullopt; } - rfl::Result to_array(const InputVarType& _var) const noexcept; + rfl::Result to_array( + const InputVarType& _var) const noexcept { + return _var.to_array(); + } rfl::Result to_object( - const InputVarType& _var) const noexcept; + const InputVarType& _var) const noexcept { + return _var.to_object(); + } template rfl::Result use_custom_constructor( const InputVarType _var) const noexcept { - return rfl::Error("Not supported for generic types"); + return error("Not supported for generic types"); } }; diff --git a/include/rfl/internal/enums/StringConverter.hpp b/include/rfl/internal/enums/StringConverter.hpp index 4e6a0e7a..b2f3d1b6 100644 --- a/include/rfl/internal/enums/StringConverter.hpp +++ b/include/rfl/internal/enums/StringConverter.hpp @@ -98,7 +98,7 @@ class StringConverter { try { return static_cast(std::stoi(_str)); } catch (std::exception& exp) { - return Error(exp.what()); + return error(exp.what()); } } } diff --git a/include/rfl/internal/get_type_name.hpp b/include/rfl/internal/get_type_name.hpp index 1be1e1cd..38ab1c4c 100644 --- a/include/rfl/internal/get_type_name.hpp +++ b/include/rfl/internal/get_type_name.hpp @@ -47,7 +47,7 @@ consteval auto get_type_name_str_view() { } template -consteval auto get_type_name() { +consteval auto get_type_name() { static_assert(get_type_name_str_view() == "int", "Expected 'int', got something else."); constexpr auto name = get_type_name_str_view(); diff --git a/include/rfl/io/load_bytes.hpp b/include/rfl/io/load_bytes.hpp index ed8932fa..84bd21fc 100644 --- a/include/rfl/io/load_bytes.hpp +++ b/include/rfl/io/load_bytes.hpp @@ -19,7 +19,7 @@ inline Result> load_bytes(const std::string& _fname) { input.close(); return bytes; } else { - return rfl::Error("File '" + _fname + "' not found!"); + return error("File '" + _fname + "' not found!"); } } diff --git a/include/rfl/io/load_string.hpp b/include/rfl/io/load_string.hpp index 8baa2641..a279aab5 100644 --- a/include/rfl/io/load_string.hpp +++ b/include/rfl/io/load_string.hpp @@ -18,7 +18,7 @@ inline Result load_string(const std::string& _fname) { infile.close(); return r; } else { - return Error("Unable to open file '" + _fname + + return error("Unable to open file '" + _fname + "' or file could not be found."); } } diff --git a/include/rfl/io/save_bytes.hpp b/include/rfl/io/save_bytes.hpp index e52c1a3d..d0eb1176 100644 --- a/include/rfl/io/save_bytes.hpp +++ b/include/rfl/io/save_bytes.hpp @@ -19,7 +19,7 @@ Result save_bytes(const std::string& _fname, const T& _obj, _write(_obj, output); output.close(); } catch (std::exception& e) { - return Error(e.what()); + return error(e.what()); } return Nothing{}; } diff --git a/include/rfl/io/save_string.hpp b/include/rfl/io/save_string.hpp index e7e6a173..8f02336a 100644 --- a/include/rfl/io/save_string.hpp +++ b/include/rfl/io/save_string.hpp @@ -19,7 +19,7 @@ Result save_string(const std::string& _fname, const T& _obj, _write(_obj, outfile); outfile.close(); } catch (std::exception& e) { - return Error(e.what()); + return error(e.what()); } return Nothing{}; } diff --git a/include/rfl/json/Reader.hpp b/include/rfl/json/Reader.hpp index ef54f2bd..5cc032d7 100644 --- a/include/rfl/json/Reader.hpp +++ b/include/rfl/json/Reader.hpp @@ -52,12 +52,26 @@ struct Reader { (requires(InputVarType var) { T::from_json_obj(var); }); rfl::Result get_field_from_array( - const size_t _idx, const InputArrayType _arr) const noexcept; + const size_t _idx, const InputArrayType _arr) const noexcept { + const auto var = InputVarType(yyjson_arr_get(_arr.val_, _idx)); + if (!var.val_) { + return error("Index " + std::to_string(_idx) + " of of bounds."); + } + return var; + } rfl::Result get_field_from_object( - const std::string& _name, const InputObjectType _obj) const noexcept; + const std::string& _name, const InputObjectType _obj) const noexcept { + const auto var = InputVarType(yyjson_obj_get(_obj.val_, _name.c_str())); + if (!var.val_) { + return error("Object contains no field named '" + _name + "'."); + } + return var; + } - bool is_empty(const InputVarType _var) const noexcept; + bool is_empty(const InputVarType _var) const noexcept { + return !_var.val_ || yyjson_is_null(_var.val_); + } template std::optional read_array(const ArrayReader& _array_reader, @@ -92,27 +106,27 @@ struct Reader { if constexpr (std::is_same, std::string>()) { const auto r = yyjson_get_str(_var.val_); if (r == NULL) { - return rfl::Error("Could not cast to string."); + return error("Could not cast to string."); } return std::string(r); } else if constexpr (std::is_same, bool>()) { if (!yyjson_is_bool(_var.val_)) { - return rfl::Error("Could not cast to boolean."); + return error("Could not cast to boolean."); } return yyjson_get_bool(_var.val_); } else if constexpr (std::is_floating_point>()) { if (!yyjson_is_num(_var.val_)) { - return rfl::Error("Could not cast to double."); + return error("Could not cast to double."); } return static_cast(yyjson_get_num(_var.val_)); } else if constexpr (std::is_unsigned>()) { if (!yyjson_is_int(_var.val_)) { - return rfl::Error("Could not cast to int."); + return error("Could not cast to int."); } return static_cast(yyjson_get_uint(_var.val_)); } else if constexpr (std::is_integral>()) { if (!yyjson_is_int(_var.val_)) { - return rfl::Error("Could not cast to int."); + return error("Could not cast to int."); } return static_cast(yyjson_get_sint(_var.val_)); } else { @@ -120,10 +134,20 @@ struct Reader { } } - rfl::Result to_array(const InputVarType _var) const noexcept; + rfl::Result to_array(const InputVarType _var) const noexcept { + if (!yyjson_is_arr(_var.val_)) { + return error("Could not cast to array!"); + } + return InputArrayType(_var.val_); + } rfl::Result to_object( - const InputVarType _var) const noexcept; + const InputVarType _var) const noexcept { + if (!yyjson_is_obj(_var.val_)) { + return error("Could not cast to object!"); + } + return InputObjectType(_var.val_); + } template rfl::Result use_custom_constructor( @@ -131,7 +155,7 @@ struct Reader { try { return T::from_json_obj(_var); } catch (std::exception& e) { - return rfl::Error(e.what()); + return error(e.what()); } } }; diff --git a/include/rfl/json/read.hpp b/include/rfl/json/read.hpp index c4465498..2abd9261 100644 --- a/include/rfl/json/read.hpp +++ b/include/rfl/json/read.hpp @@ -30,10 +30,11 @@ auto read(const InputVarType& _obj) { /// Parses an object from JSON using reflection. template -Result> read(std::string_view const _json_str) { +Result> read( + std::string_view const _json_str) { yyjson_doc* doc = yyjson_read(_json_str.data(), _json_str.size(), 0); if (!doc) { - return Error("Could not parse document"); + return error("Could not parse document"); } yyjson_val* root = yyjson_doc_get_root(doc); const auto r = Reader(); diff --git a/include/rfl/msgpack/Reader.hpp b/include/rfl/msgpack/Reader.hpp index 6085c6f1..815eb436 100644 --- a/include/rfl/msgpack/Reader.hpp +++ b/include/rfl/msgpack/Reader.hpp @@ -27,33 +27,54 @@ struct Reader { (requires(InputVarType var) { T::from_msgpack_obj(var); }); rfl::Result get_field_from_array( - const size_t _idx, const InputArrayType _arr) const noexcept; + const size_t _idx, const InputArrayType _arr) const noexcept { + if (_idx >= _arr.size) { + return error("Index " + std::to_string(_idx) + " of of bounds."); + } + return _arr.ptr[_idx]; + } rfl::Result get_field_from_object( - const std::string& _name, const InputObjectType& _obj) const noexcept; + const std::string& _name, const InputObjectType& _obj) const noexcept { + for (uint32_t i = 0; i < _obj.size; ++i) { + const auto& key = _obj.ptr[i].key; + if (key.type != MSGPACK_OBJECT_STR) { + return error("Key in element " + std::to_string(i) + + " was not a string."); + } + const auto current_name = + std::string_view(key.via.str.ptr, key.via.str.size); + if (_name == current_name) { + return _obj.ptr[i].val; + } + } + return error("No field named '" + _name + "' was found."); + } - bool is_empty(const InputVarType& _var) const noexcept; + bool is_empty(const InputVarType& _var) const noexcept { + return _var.type == MSGPACK_OBJECT_NIL; + } template rfl::Result to_basic_type(const InputVarType& _var) const noexcept { const auto type = _var.type; if constexpr (std::is_same, std::string>()) { if (type != MSGPACK_OBJECT_STR) { - return Error("Could not cast to string."); + return error("Could not cast to string."); } const auto str = _var.via.str; return std::string(str.ptr, str.size); } else if constexpr (std::is_same, rfl::Bytestring>()) { if (type != MSGPACK_OBJECT_BIN) { - return Error("Could not cast to a bytestring."); + return error("Could not cast to a bytestring."); } const auto bin = _var.via.bin; return rfl::Bytestring(internal::ptr_cast(bin.ptr), bin.size); } else if constexpr (std::is_same, bool>()) { if (type != MSGPACK_OBJECT_BOOLEAN) { - return Error("Could not cast to boolean."); + return error("Could not cast to boolean."); } return _var.via.boolean; } else if constexpr (std::is_floating_point>() || @@ -66,7 +87,7 @@ struct Reader { } else if (type == MSGPACK_OBJECT_NEGATIVE_INTEGER) { return static_cast(_var.via.i64); } - return rfl::Error( + return error( "Could not cast to numeric value. The type must be integral, float " "or double."); } else { @@ -74,10 +95,21 @@ struct Reader { } } - rfl::Result to_array(const InputVarType& _var) const noexcept; + rfl::Result to_array( + const InputVarType& _var) const noexcept { + if (_var.type != MSGPACK_OBJECT_ARRAY) { + return error("Could not cast to an array."); + } + return _var.via.array; + } rfl::Result to_object( - const InputVarType& _var) const noexcept; + const InputVarType& _var) const noexcept { + if (_var.type != MSGPACK_OBJECT_MAP) { + return error("Could not cast to a map."); + } + return _var.via.map; + } template std::optional read_array(const ArrayReader& _array_reader, @@ -98,8 +130,8 @@ struct Reader { const auto& key = _obj.ptr[i].key; const auto& val = _obj.ptr[i].val; if (key.type != MSGPACK_OBJECT_STR) { - return Error("Key in element " + std::to_string(i) + - " was not a string."); + return rfl::Error("Key in element " + std::to_string(i) + + " was not a string."); } const auto name = std::string_view(key.via.str.ptr, key.via.str.size); _object_reader.read(name, val); @@ -113,7 +145,7 @@ struct Reader { try { return T::from_msgpack_obj(_var); } catch (std::exception& e) { - return rfl::Error(e.what()); + return error(e.what()); } } }; diff --git a/include/rfl/parsing/ArrayReader.hpp b/include/rfl/parsing/ArrayReader.hpp index 9724b68e..ef56e6f4 100644 --- a/include/rfl/parsing/ArrayReader.hpp +++ b/include/rfl/parsing/ArrayReader.hpp @@ -47,7 +47,7 @@ class ArrayReader { move_to(&((*array_)[num_set_]), &(*res)); } else { return Error("Failed to parse element " + std::to_string(num_set_) + - ": " + res.error()->what()); + ": " + res.error().what()); } ++num_set_; return std::optional(); diff --git a/include/rfl/parsing/CustomParser.hpp b/include/rfl/parsing/CustomParser.hpp index 88f8be09..7bd7ecb8 100644 --- a/include/rfl/parsing/CustomParser.hpp +++ b/include/rfl/parsing/CustomParser.hpp @@ -32,7 +32,7 @@ struct CustomParser { return rfl::apply(class_from_ptrs, ptr_field_tuple); } } catch (std::exception& e) { - return Error(e.what()); + return error(e.what()); } }; return Parser::read(_r, diff --git a/include/rfl/parsing/FieldVariantParser.hpp b/include/rfl/parsing/FieldVariantParser.hpp index 2929e4d8..9374f6ee 100644 --- a/include/rfl/parsing/FieldVariantParser.hpp +++ b/include/rfl/parsing/FieldVariantParser.hpp @@ -21,7 +21,7 @@ namespace parsing { /// To be used when all options of the variants are rfl::Field. Essentially, /// this is an externally tagged union. template -requires AreReaderAndWriter> + requires AreReaderAndWriter> struct FieldVariantParser { using FieldVariantType = rfl::Variant; using ResultType = Result; @@ -43,10 +43,10 @@ struct FieldVariantParser { &_r, &field_variant); auto err = _r.read_object(reader, _obj); if (err) { - return *err; + return error(*err); } if (!field_variant) { - return Error( + return error( "Could not parse: Expected the object to have " "exactly one field, but found more than one."); } diff --git a/include/rfl/parsing/FieldVariantReader.hpp b/include/rfl/parsing/FieldVariantReader.hpp index 487ffe2d..06ed2b41 100644 --- a/include/rfl/parsing/FieldVariantReader.hpp +++ b/include/rfl/parsing/FieldVariantReader.hpp @@ -40,7 +40,7 @@ class FieldVariantReader { stream << "Could not parse rfl::Variant, could not match field named " "'" << _disc_value << "'."; - *field_variant_ = Error(stream.str()); + *field_variant_ = error(stream.str()); } } @@ -71,7 +71,7 @@ class FieldVariantReader { }; *field_variant_ = Parser::read(*r_, _var) .transform(to_variant) - .or_else(embellish_error); + .transform_error(embellish_error); } } diff --git a/include/rfl/parsing/MapParser.hpp b/include/rfl/parsing/MapParser.hpp index 65805266..e53239e0 100644 --- a/include/rfl/parsing/MapParser.hpp +++ b/include/rfl/parsing/MapParser.hpp @@ -68,16 +68,16 @@ struct MapParser { if constexpr (schemaful::IsSchemafulReader) { const auto err = _r.read_map(map_reader, _obj_or_map); if (err) { - return *err; + return error(*err); } } else { const auto err = _r.read_object(map_reader, _obj_or_map); if (err) { - return *err; + return error(*err); } } if (errors.size() != 0) { - return to_single_error_message(errors); + return error(to_single_error_message(errors)); } return map; } diff --git a/include/rfl/parsing/MapReader.hpp b/include/rfl/parsing/MapReader.hpp index 8c62843a..3ee890fa 100644 --- a/include/rfl/parsing/MapReader.hpp +++ b/include/rfl/parsing/MapReader.hpp @@ -33,7 +33,7 @@ class MapReader { map_->emplace(std::move(*res)); } else { errors_->push_back(Error("Failed to parse field '" + std::string(_name) + - "': " + res.error()->what())); + "': " + res.error().what())); } } @@ -51,7 +51,7 @@ class MapReader { static_assert(always_false_v, "Unsupported type"); } } catch (std::exception& e) { - return Error(e.what()); + return error(e.what()); } } @@ -62,7 +62,7 @@ class MapReader { return std::make_pair(KeyType(std::move(_key)), std::move(_pair.second)); } catch (std::exception& e) { - return Error(e.what()); + return error(e.what()); } }; diff --git a/include/rfl/parsing/NamedTupleParser.hpp b/include/rfl/parsing/NamedTupleParser.hpp index eb530271..88200a27 100644 --- a/include/rfl/parsing/NamedTupleParser.hpp +++ b/include/rfl/parsing/NamedTupleParser.hpp @@ -92,7 +92,7 @@ struct NamedTupleParser { Parser::read_view(_r, _var, &view); if (err) [[unlikely]] { call_destructors_where_necessary(set, &view); - return *err; + return error(*err); } auto res = Result>(std::move(*ptr)); call_destructors_where_necessary(set, &view); @@ -110,6 +110,7 @@ struct NamedTupleParser { auto arr = _r.to_array(_var); if (!arr) [[unlikely]] { auto set = std::array{}; + // return std::make_pair(set, arr.error()); return std::make_pair(set, arr.error()); } return read_object_or_array(_r, *arr, _view); diff --git a/include/rfl/parsing/Parser_array.hpp b/include/rfl/parsing/Parser_array.hpp index d83f2e6a..3646f363 100644 --- a/include/rfl/parsing/Parser_array.hpp +++ b/include/rfl/parsing/Parser_array.hpp @@ -40,12 +40,12 @@ struct Parser, ProcessorsType> { auto err = _r.read_array(array_reader, _arr); if (err) { call_destructors_on_array_where_necessary(array_reader.num_set(), ptr); - return *err; + return error(*err); } err = array_reader.check_size(); if (err) { call_destructors_on_array_where_necessary(array_reader.num_set(), ptr); - return *err; + return error(*err); } auto result = Result>(std::move(*ptr)); call_destructors_on_array_where_necessary(array_reader.num_set(), ptr); diff --git a/include/rfl/parsing/Parser_default.hpp b/include/rfl/parsing/Parser_default.hpp index 8ff5b1a5..0d7c8502 100644 --- a/include/rfl/parsing/Parser_default.hpp +++ b/include/rfl/parsing/Parser_default.hpp @@ -50,7 +50,7 @@ struct Parser { try { return Reflector::to(_named_tuple); } catch (std::exception& e) { - return Error(e.what()); + return error(e.what()); } }; return Parser::ReflType, @@ -71,7 +71,7 @@ struct Parser { try { return T{_named_tuple}; } catch (std::exception& e) { - return Error(e.what()); + return error(e.what()); } }; return Parser::read(_r, _var) @@ -278,7 +278,7 @@ struct Parser { Parser::read_view(_r, _var, &view); if (err) [[unlikely]] { call_destructors_where_necessary(set, &view); - return *err; + return error(err->what()); } auto res = Result(std::move(*ptr)); call_destructors_where_necessary(set, &view); @@ -298,7 +298,7 @@ struct Parser { Parser::read_view_with_default(_r, _var, &view); if (err) [[unlikely]] { - return *err; + return error(*err); } return t; } diff --git a/include/rfl/parsing/Parser_filepath.hpp b/include/rfl/parsing/Parser_filepath.hpp index e19f352f..b5c93ca3 100644 --- a/include/rfl/parsing/Parser_filepath.hpp +++ b/include/rfl/parsing/Parser_filepath.hpp @@ -12,7 +12,7 @@ namespace rfl { namespace parsing { template -requires AreReaderAndWriter + requires AreReaderAndWriter struct Parser { using InputVarType = typename R::InputVarType; @@ -24,7 +24,7 @@ struct Parser { try { return std::filesystem::path(_str); } catch (std::exception& e) { - return Error(e.what()); + return error(e.what()); } }; return Parser::read(_r, _var).and_then( diff --git a/include/rfl/parsing/Parser_ptr.hpp b/include/rfl/parsing/Parser_ptr.hpp index d2e68ffa..33ec7383 100644 --- a/include/rfl/parsing/Parser_ptr.hpp +++ b/include/rfl/parsing/Parser_ptr.hpp @@ -15,7 +15,7 @@ namespace rfl { namespace parsing { template -requires AreReaderAndWriter + requires AreReaderAndWriter struct Parser { using InputVarType = typename R::InputVarType; @@ -36,7 +36,7 @@ struct Parser { "Please note that it is then YOUR responsibility " "to delete the allocated memory. Please also refer " "to the related documentation (in the section on processors)."); - return Error("Unsupported."); + return error("Unsupported."); } else { if (_r.is_empty(_var)) { return nullptr; diff --git a/include/rfl/parsing/Parser_reference_wrapper.hpp b/include/rfl/parsing/Parser_reference_wrapper.hpp index 7a6c2376..5642e8ab 100644 --- a/include/rfl/parsing/Parser_reference_wrapper.hpp +++ b/include/rfl/parsing/Parser_reference_wrapper.hpp @@ -14,19 +14,19 @@ namespace rfl { namespace parsing { template -requires AreReaderAndWriter> + requires AreReaderAndWriter> struct Parser, ProcessorsType> { using InputVarType = typename R::InputVarType; - static Result> read( - const R&, const InputVarType&) noexcept { + static Result> read(const R&, + const InputVarType&) noexcept { static_assert(always_false_v, "Reading into std::reference_wrapper is dangerous and " "therefore unsupported. " "Please consider using std::unique_ptr, rfl::Box, " "std::shared_ptr, or" "rfl::Ref instead."); - return Error("Unsupported."); + return error("Unsupported."); } template diff --git a/include/rfl/parsing/Parser_result.hpp b/include/rfl/parsing/Parser_result.hpp index f287c59a..c6e46104 100644 --- a/include/rfl/parsing/Parser_result.hpp +++ b/include/rfl/parsing/Parser_result.hpp @@ -14,7 +14,7 @@ namespace rfl { namespace parsing { template -requires AreReaderAndWriter> + requires AreReaderAndWriter> struct Parser, ProcessorsType> { using InputVarType = typename R::InputVarType; @@ -26,7 +26,7 @@ struct Parser, ProcessorsType> { const auto handle = [](auto&& _t) -> Result { using Type = std::remove_cvref_t; if constexpr (std::is_same()) { - return Error(_t.template get<"error">()); + return error(_t.template get<"error">()); } else { return std::forward>(_t); } @@ -44,19 +44,26 @@ struct Parser, ProcessorsType> { template static void write(const W& _w, const Result& _r, const P& _parent) noexcept { - const auto write_t = [&](const auto& _t) -> Nothing { - Parser, ProcessorsType>::write(_w, _t, - _parent); - return Nothing{}; - }; + // const auto write_t = [&](const auto& _t) -> Nothing { + // Parser, ProcessorsType>::write(_w, _t, + // _parent); + // return Nothing{}; + // }; - const auto write_err = [&](const auto& _err) -> Nothing { + // const auto write_err = [&](const auto& _err) -> Nothing { + // Parser::write( + // _w, ErrorType(make_field<"error">(_err.what())), _parent); + // return Nothing{}; + // }; + if (_r) { + Parser, ProcessorsType>::write( + _w, _r.value(), _parent); + } else { Parser::write( - _w, ErrorType(make_field<"error">(_err.what())), _parent); - return Nothing{}; - }; + _w, ErrorType(make_field<"error">(_r.error().what())), _parent); + } - _r.transform(write_t).or_else(write_err); + // _r.transform(write_t).transform_error(write_err); } static schema::Type to_schema( diff --git a/include/rfl/parsing/Parser_rfl_variant.hpp b/include/rfl/parsing/Parser_rfl_variant.hpp index c15acc86..88d6d71a 100644 --- a/include/rfl/parsing/Parser_rfl_variant.hpp +++ b/include/rfl/parsing/Parser_rfl_variant.hpp @@ -74,7 +74,7 @@ class Parser, ProcessorsType> { if (result) { return std::move(*result); } else { - return Error( + return error( to_single_error_message(errors, "Could not parse the variant. Each of the " "possible alternatives failed " @@ -187,7 +187,7 @@ class Parser, ProcessorsType> { if (res) { *_result = std::move(*res); } else { - _errors->emplace_back(*res.error()); + _errors->emplace_back(res.error()); } } } diff --git a/include/rfl/parsing/Parser_string_view.hpp b/include/rfl/parsing/Parser_string_view.hpp index 3df17ce2..c507bb18 100644 --- a/include/rfl/parsing/Parser_string_view.hpp +++ b/include/rfl/parsing/Parser_string_view.hpp @@ -15,24 +15,22 @@ namespace rfl { namespace parsing { template -requires AreReaderAndWriter + requires AreReaderAndWriter struct Parser { using InputVarType = typename R::InputVarType; - static Result read(const R&, - const InputVarType&) noexcept { + static Result read(const R&, const InputVarType&) noexcept { static_assert(always_false_v, "Reading into std::string_view is dangerous and " "therefore unsupported. " "Please consider using std::string instead."); - return Error("Unsupported."); + return error("Unsupported."); } template static void write(const W& _w, const std::string_view& _str, const P& _p) noexcept { - Parser::write(_w, std::string(_str), - _p); + Parser::write(_w, std::string(_str), _p); } static schema::Type to_schema( diff --git a/include/rfl/parsing/Parser_tagged_union.hpp b/include/rfl/parsing/Parser_tagged_union.hpp index 2f9b493b..fcef6c2e 100644 --- a/include/rfl/parsing/Parser_tagged_union.hpp +++ b/include/rfl/parsing/Parser_tagged_union.hpp @@ -104,7 +104,7 @@ struct Parser, possible_tags_t>; static_assert(!PossibleTags::has_duplicates(), "Duplicate tags are not allowed inside tagged unions."); - ResultType res = Error(""); + ResultType res = error(""); bool match_found = false; (set_if_disc_value_matches<_is>(_r, _disc_value, _var, &res, &match_found), ...); @@ -117,7 +117,7 @@ struct Parser, << _discriminator.str() << " '" << _disc_value << "'. The following tags are allowed: " << internal::strings::join(", ", names); - return Error(stream.str()); + return error(stream.str()); } } @@ -144,7 +144,7 @@ struct Parser, std::move(_val)); }; - const auto embellish_error = [&](Error&& _e) { + const auto embellish_error = [&](auto&& _e) { std::stringstream stream; stream << "Could not parse tagged union with " "discrimininator " @@ -159,11 +159,11 @@ struct Parser, *_res = Parser::read(_r, _var) .transform(get_fields) .transform(to_tagged_union) - .or_else(embellish_error); + .transform_error(embellish_error); } else { *_res = Parser::read(_r, _var) .transform(to_tagged_union) - .or_else(embellish_error); + .transform_error(embellish_error); } *_match_found = true; @@ -187,11 +187,11 @@ struct Parser, if constexpr (no_field_names_) { return _r.get_field_from_array(0, _obj_or_arr) .and_then(to_type) - .or_else(embellish_error); + .transform_error(embellish_error); } else { return _r.get_field_from_object(_discriminator.str(), _obj_or_arr) .and_then(to_type) - .or_else(embellish_error); + .transform_error(embellish_error); } } diff --git a/include/rfl/parsing/Parser_variant.hpp b/include/rfl/parsing/Parser_variant.hpp index 5663220c..ac05e08d 100644 --- a/include/rfl/parsing/Parser_variant.hpp +++ b/include/rfl/parsing/Parser_variant.hpp @@ -91,7 +91,7 @@ class Parser, ProcessorsType> { if (result) { return std::move(*result); } else { - return Error( + return error( to_single_error_message(errors, "Could not parse the variant. Each of the " "possible alternatives failed " @@ -215,7 +215,7 @@ class Parser, ProcessorsType> { if (res) { *_result = std::move(*res); } else { - _errors->emplace_back(*res.error()); + _errors->emplace_back(res.error()); } } } diff --git a/include/rfl/parsing/Parser_wstring.hpp b/include/rfl/parsing/Parser_wstring.hpp index b3853996..1f3a8339 100644 --- a/include/rfl/parsing/Parser_wstring.hpp +++ b/include/rfl/parsing/Parser_wstring.hpp @@ -14,7 +14,7 @@ namespace rfl { namespace parsing { template -requires AreReaderAndWriter + requires AreReaderAndWriter struct Parser { public: using InputVarType = typename R::InputVarType; @@ -28,9 +28,12 @@ struct Parser { } auto inStr = Parser::read(_r, _var); - if (auto err = inStr.error(); err.has_value()) { - return Result(err.value()); + if (!inStr) { + return Result(error(inStr.error())); } + // if (auto err = inStr.error(); err.has_value()) { + // return Result(err.value()); + // } std::mbstate_t state = std::mbstate_t(); auto val = inStr.value(); diff --git a/include/rfl/parsing/TupleParser.hpp b/include/rfl/parsing/TupleParser.hpp index e09b24ab..0c16b425 100644 --- a/include/rfl/parsing/TupleParser.hpp +++ b/include/rfl/parsing/TupleParser.hpp @@ -55,13 +55,13 @@ struct TupleParser { if (err) { call_destructors_on_tuple_where_necessary(tuple_reader.num_set(), ptr); - return *err; + return error(*err); } err = tuple_reader.handle_missing_fields(); if (err) { call_destructors_on_tuple_where_necessary(tuple_reader.num_set(), ptr); - return *err; + return error(*err); } auto res = Result(std::move(*ptr)); call_destructors_on_tuple_where_necessary(tuple_reader.num_set(), ptr); diff --git a/include/rfl/parsing/TupleReader.hpp b/include/rfl/parsing/TupleReader.hpp index 4f43e180..6883a9c4 100644 --- a/include/rfl/parsing/TupleReader.hpp +++ b/include/rfl/parsing/TupleReader.hpp @@ -79,7 +79,7 @@ class TupleReader { } else { std::stringstream stream; stream << "Failed to parse field " << _i << ": " - << res.error()->what(); + << res.error().what(); *_err = Error(stream.str()); } return; diff --git a/include/rfl/parsing/VectorParser.hpp b/include/rfl/parsing/VectorParser.hpp index c95bb682..e40ddd4f 100644 --- a/include/rfl/parsing/VectorParser.hpp +++ b/include/rfl/parsing/VectorParser.hpp @@ -57,7 +57,7 @@ struct VectorParser { VectorReader(&_r, &vec); const auto err = _r.read_array(vector_reader, _arr); if (err) { - return *err; + return error(*err); } return vec; }; diff --git a/include/rfl/parsing/VectorReader.hpp b/include/rfl/parsing/VectorReader.hpp index 1837aa87..87dfe32c 100644 --- a/include/rfl/parsing/VectorReader.hpp +++ b/include/rfl/parsing/VectorReader.hpp @@ -38,8 +38,13 @@ class VectorReader { } return std::nullopt; }; - - return parse(_var).transform(insert).error(); + auto res = parse(_var).transform(insert); + if (res) { + return std::nullopt; + } else { + return res.error(); + } + // return parse(_var).transform(insert).error(); } private: diff --git a/include/rfl/parsing/ViewReader.hpp b/include/rfl/parsing/ViewReader.hpp index a9d97c82..93a79707 100644 --- a/include/rfl/parsing/ViewReader.hpp +++ b/include/rfl/parsing/ViewReader.hpp @@ -74,7 +74,7 @@ class ViewReader { if (!res) { std::stringstream stream; stream << "Failed to parse field '" << std::string(name) - << "': " << res.error()->what(); + << "': " << res.error().what(); _errors->emplace_back(Error(stream.str())); return; } @@ -106,7 +106,7 @@ class ViewReader { if (!res) { std::stringstream stream; stream << "Failed to parse field '" << _current_name - << "': " << res.error()->what(); + << "': " << res.error().what(); _errors->emplace_back(Error(stream.str())); return; } diff --git a/include/rfl/parsing/ViewReaderWithDefault.hpp b/include/rfl/parsing/ViewReaderWithDefault.hpp index f73caee0..22d488e8 100644 --- a/include/rfl/parsing/ViewReaderWithDefault.hpp +++ b/include/rfl/parsing/ViewReaderWithDefault.hpp @@ -51,7 +51,7 @@ class ViewReaderWithDefault { if (!res) { std::stringstream stream; stream << "Failed to parse field '" << std::string(name) - << "': " << res.error()->what(); + << "': " << res.error().what(); _errors->emplace_back(Error(stream.str())); return; } @@ -77,7 +77,7 @@ class ViewReaderWithDefault { if (!res) { std::stringstream stream; stream << "Failed to parse field '" << _current_name - << "': " << res.error()->what(); + << "': " << res.error().what(); _errors->emplace_back(Error(stream.str())); return; } diff --git a/include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp b/include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp index 04f92827..1bb2e67f 100644 --- a/include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp +++ b/include/rfl/parsing/ViewReaderWithDefaultAndStrippedFieldNames.hpp @@ -56,7 +56,7 @@ class ViewReaderWithDefaultAndStrippedFieldNames { if (!res) { std::stringstream stream; stream << "Failed to parse field '" << std::string(name) - << "': " << res.error()->what(); + << "': " << res.error().what(); _errors->emplace_back(Error(stream.str())); return; } diff --git a/include/rfl/parsing/ViewReaderWithStrippedFieldNames.hpp b/include/rfl/parsing/ViewReaderWithStrippedFieldNames.hpp index 5e040bc1..e438e40d 100644 --- a/include/rfl/parsing/ViewReaderWithStrippedFieldNames.hpp +++ b/include/rfl/parsing/ViewReaderWithStrippedFieldNames.hpp @@ -65,7 +65,7 @@ class ViewReaderWithStrippedFieldNames { if (!res) { std::stringstream stream; stream << "Failed to parse field '" << std::string(name) - << "': " << res.error()->what(); + << "': " << res.error().what(); _errors->emplace_back(Error(stream.str())); return; } diff --git a/include/rfl/parsing/schemaful/IsSchemafulReader.hpp b/include/rfl/parsing/schemaful/IsSchemafulReader.hpp index 3b1eac2a..c78ae7bd 100644 --- a/include/rfl/parsing/schemaful/IsSchemafulReader.hpp +++ b/include/rfl/parsing/schemaful/IsSchemafulReader.hpp @@ -23,7 +23,7 @@ template struct MockUnionReader { static rfl::Result read(const R&, const size_t, typename R::InputVarType&) { - return Error("This is a mock type."); + return error("This is a mock type."); } }; diff --git a/include/rfl/parsing/schemaful/VariantReader.hpp b/include/rfl/parsing/schemaful/VariantReader.hpp index eb2f5f9d..00857f8e 100644 --- a/include/rfl/parsing/schemaful/VariantReader.hpp +++ b/include/rfl/parsing/schemaful/VariantReader.hpp @@ -18,7 +18,7 @@ class VariantReader { const typename R::InputVarType& _var) noexcept { return [&](std::integer_sequence) { Result result = - Error("Could not parse union: Index out of bounds."); + error("Could not parse union: Index out of bounds."); (try_one_type<_is>(_r, _index, _var, &result), ...); return result; }(std::make_integer_sequence()); diff --git a/include/rfl/parsing/to_single_error_message.hpp b/include/rfl/parsing/to_single_error_message.hpp index 3d42b7c6..e4669ac4 100644 --- a/include/rfl/parsing/to_single_error_message.hpp +++ b/include/rfl/parsing/to_single_error_message.hpp @@ -11,12 +11,12 @@ namespace rfl::parsing { /// Combines a set of errors to a single, readable error message. -inline Error to_single_error_message( +inline std::string to_single_error_message( std::vector _errors, std::optional _msg_prefix = std::nullopt, size_t _err_limit = 10) { if (_errors.size() == 1) { - return std::move(_errors[0]); + return std::move(_errors[0].what()); } else { std::stringstream stream; stream << (_msg_prefix @@ -34,7 +34,7 @@ inline Error to_single_error_message( "first " << _err_limit << "."; } - return Error(stream.str()); + return stream.str(); } } diff --git a/include/rfl/toml/Reader.hpp b/include/rfl/toml/Reader.hpp index 41ae2f95..2dda297d 100644 --- a/include/rfl/toml/Reader.hpp +++ b/include/rfl/toml/Reader.hpp @@ -29,37 +29,50 @@ struct Reader { (requires(InputVarType var) { T::from_toml_obj(var); }); rfl::Result get_field_from_array( - const size_t _idx, const InputArrayType _arr) const noexcept; + const size_t _idx, const InputArrayType _arr) const noexcept { + if (_idx >= _arr->size()) { + return error("Index " + std::to_string(_idx) + " of of bounds."); + } + return _arr->get(_idx); + } rfl::Result get_field_from_object( - const std::string& _name, const InputObjectType& _obj) const noexcept; + const std::string& _name, const InputObjectType& _obj) const noexcept { + auto var = (*_obj)[_name]; + if (!var) { + return error("Object contains no field named '" + _name + "'."); + } + return var.node(); + } - bool is_empty(const InputVarType& _var) const noexcept; + bool is_empty(const InputVarType& _var) const noexcept { + return !_var && true; + } template rfl::Result to_basic_type(const InputVarType& _var) const noexcept { if constexpr (std::is_same, std::string>()) { const auto ptr = _var->as(); if (!ptr) { - return Error("Could not cast the node to std::string!"); + return error("Could not cast the node to std::string!"); } return **ptr; } else if constexpr (std::is_same, bool>()) { const auto ptr = _var->as(); if (!ptr) { - return Error("Could not cast the node to bool!"); + return error("Could not cast the node to bool!"); } return **ptr; } else if constexpr (std::is_floating_point>()) { const auto ptr = _var->as(); if (!ptr) { - return Error("Could not cast the node to double!"); + return error("Could not cast the node to double!"); } return static_cast>(**ptr); } else if constexpr (std::is_integral>()) { const auto ptr = _var->as(); if (!ptr) { - return Error("Could not cast the node to int64_t!"); + return error("Could not cast the node to int64_t!"); } return static_cast>(**ptr); } else { @@ -67,7 +80,14 @@ struct Reader { } } - rfl::Result to_array(const InputVarType& _var) const noexcept; + rfl::Result to_array( + const InputVarType& _var) const noexcept { + const auto ptr = _var->as_array(); + if (!ptr) { + return error("Could not cast to an array!"); + } + return ptr; + } template std::optional read_array(const ArrayReader& _array_reader, @@ -91,7 +111,13 @@ struct Reader { } rfl::Result to_object( - const InputVarType& _var) const noexcept; + const InputVarType& _var) const noexcept { + const auto ptr = _var->as_table(); + if (!ptr) { + return error("Could not cast to a table!"); + } + return ptr; + } template rfl::Result use_custom_constructor( @@ -99,7 +125,7 @@ struct Reader { try { return T::from_toml_obj(_var); } catch (std::exception& e) { - return rfl::Error(e.what()); + return error(e.what()); } } }; diff --git a/include/rfl/ubjson/Reader.hpp b/include/rfl/ubjson/Reader.hpp index 84b308f4..e245735f 100644 --- a/include/rfl/ubjson/Reader.hpp +++ b/include/rfl/ubjson/Reader.hpp @@ -43,31 +43,45 @@ class Reader { (requires(InputVarType var) { T::from_ubjson_obj(var); }); rfl::Result get_field_from_array( - const size_t _idx, const InputArrayType& _arr) const noexcept; + const size_t _idx, const InputArrayType& _arr) const noexcept { + if (_idx >= _arr.val_->size()) { + return error("Index out of range."); + } + return InputVarType{&_arr.val_->at(_idx)}; + } rfl::Result get_field_from_object( - const std::string& _name, const InputObjectType& _obj) const noexcept; + const std::string& _name, const InputObjectType& _obj) const noexcept { + for (auto& kv : _obj.val_->object_range()) { + if (kv.key() == _name) { + return InputVarType{&kv.value()}; + }; + } + return error("Field name '" + _name + "' not found."); + } - bool is_empty(const InputVarType& _var) const noexcept; + bool is_empty(const InputVarType& _var) const noexcept { + return _var.val_->is_null(); + } template rfl::Result to_basic_type(const InputVarType& _var) const noexcept { if constexpr (std::is_same, std::string>()) { if (!_var.val_->is_string()) { - return Error("Could not cast to string."); + return error("Could not cast to string."); } return _var.val_->as(); } else if constexpr (std::is_same, rfl::Bytestring>()) { if (!_var.val_->is>()) { - return Error("Could not cast to bytestring."); + return error("Could not cast to bytestring."); } const auto vec = _var.val_->as>(); return rfl::Bytestring(internal::ptr_cast(vec.data()), vec.size()); } else if constexpr (std::is_same, bool>()) { if (!_var.val_->is_bool()) { - return rfl::Error("Could not cast to boolean."); + return error("Could not cast to boolean."); } return _var.val_->as(); } else if constexpr (std::is_floating_point>() || @@ -81,7 +95,7 @@ class Reader { if (_var.val_->is_uint64()) { return static_cast(_var.val_->as()); } - return rfl::Error( + return error( "Could not cast to numeric value. The type must be integral, " "float or double."); } else { @@ -89,10 +103,21 @@ class Reader { } } - rfl::Result to_array(const InputVarType& _var) const noexcept; + rfl::Result to_array( + const InputVarType& _var) const noexcept { + if (!_var.val_->is_array()) { + return error("Could not cast to an array."); + } + return InputArrayType{_var.val_}; + } rfl::Result to_object( - const InputVarType& _var) const noexcept; + const InputVarType& _var) const noexcept { + if (!_var.val_->is_object()) { + return error("Could not cast to an object."); + } + return InputObjectType{_var.val_}; + } template std::optional read_array(const ArrayReader& _array_reader, @@ -121,7 +146,7 @@ class Reader { try { return T::from_ubjson_obj(_var); } catch (std::exception& e) { - return rfl::Error(e.what()); + return error(e.what()); } } }; diff --git a/include/rfl/xml/Reader.hpp b/include/rfl/xml/Reader.hpp index a5961bb6..3ef521df 100644 --- a/include/rfl/xml/Reader.hpp +++ b/include/rfl/xml/Reader.hpp @@ -43,12 +43,32 @@ struct Reader { static constexpr bool has_custom_constructor = false; rfl::Result get_field_from_array( - const size_t _idx, const InputArrayType& _arr) const noexcept; + const size_t _idx, const InputArrayType& _arr) const noexcept { + const auto name = _arr.node_.name(); + size_t i = 0; + for (auto node = _arr.node_; node; node = node.next_sibling(name)) { + if (i == _idx) { + return InputVarType(node); + } + } + return error("Index " + std::to_string(_idx) + " of of bounds."); + } rfl::Result get_field_from_object( - const std::string& _name, const InputObjectType _obj) const noexcept; + const std::string& _name, const InputObjectType _obj) const noexcept { + const auto node = _obj.node_.child(_name.c_str()); + if (!node) { + return error("Object contains no field named '" + _name + "'."); + } + return InputVarType(node); + } - bool is_empty(const InputVarType _var) const noexcept; + bool is_empty(const InputVarType _var) const noexcept { + const auto wrap = [](const auto& _node) { return !_node; }; + return std::visit(cast_as_node, _var.node_or_attribute_) + .transform(wrap) + .value_or(false); + } template rfl::Result to_basic_type(const InputVarType _var) const noexcept { @@ -70,7 +90,7 @@ struct Reader { try { return static_cast(std::stod(str)); } catch (std::exception& e) { - return Error("Could not cast '" + std::string(str) + + return error("Could not cast '" + std::string(str) + "' to floating point value."); } } else if constexpr (std::is_integral>()) { @@ -78,14 +98,17 @@ struct Reader { try { return static_cast(std::stoi(str)); } catch (std::exception& e) { - return Error("Could not cast '" + std::string(str) + "' to integer."); + return error("Could not cast '" + std::string(str) + "' to integer."); } } else { static_assert(rfl::always_false_v, "Unsupported type."); } } - rfl::Result to_array(const InputVarType _var) const noexcept; + rfl::Result to_array(const InputVarType _var) const noexcept { + const auto wrap = [](const auto& _node) { return InputArrayType(_node); }; + return std::visit(cast_as_node, _var.node_or_attribute_).transform(wrap); + } template std::optional read_array(const ArrayReader& _array_reader, @@ -122,12 +145,32 @@ struct Reader { } rfl::Result to_object( - const InputVarType _var) const noexcept; + const InputVarType _var) const noexcept { + const auto wrap = [](const auto& _node) { return InputObjectType(_node); }; + return std::visit(cast_as_node, _var.node_or_attribute_).transform(wrap); + } template rfl::Result use_custom_constructor( const InputVarType _var) const noexcept { - return rfl::Error("TODO"); + return error("TODO"); + } + + private: + /// XML-only helper function. This is needed because XML distinguishes between + /// nodes and attributes. + static rfl::Result cast_as_node( + const std::variant& + _node_or_attribute) { + const auto cast = [](const auto& _n) -> Result { + using Type = std::remove_cvref_t; + if constexpr (std::is_same()) { + return _n; + } else { + return error("Field '" + std::string(_n.name()) + "' is an attribute."); + } + }; + return std::visit(cast, _node_or_attribute); } }; diff --git a/include/rfl/xml/Writer.hpp b/include/rfl/xml/Writer.hpp index e0eb3972..54631118 100644 --- a/include/rfl/xml/Writer.hpp +++ b/include/rfl/xml/Writer.hpp @@ -1,6 +1,7 @@ #ifndef RFL_XML_WRITER_HPP_ #define RFL_XML_WRITER_HPP_ +#include #include #include #include diff --git a/include/rfl/xml/read.hpp b/include/rfl/xml/read.hpp index 20fc5a22..c37d7776 100644 --- a/include/rfl/xml/read.hpp +++ b/include/rfl/xml/read.hpp @@ -33,7 +33,7 @@ Result read(const std::string& _xml_str) { pugi::xml_document doc; const auto result = doc.load_string(_xml_str.c_str()); if (!result) { - return Error("XML string could not be parsed: " + + return error("XML string could not be parsed: " + std::string(result.description())); } const auto var = InputVarType(doc.first_child()); diff --git a/include/rfl/yaml/Reader.hpp b/include/rfl/yaml/Reader.hpp index 451a86ce..c6c97501 100644 --- a/include/rfl/yaml/Reader.hpp +++ b/include/rfl/yaml/Reader.hpp @@ -49,12 +49,25 @@ struct Reader { (requires(InputVarType var) { T::from_yaml_obj(var); }); rfl::Result get_field_from_array( - const size_t _idx, const InputArrayType& _arr) const noexcept; + const size_t _idx, const InputArrayType& _arr) const noexcept { + if (_idx >= _arr.node_.size()) { + return error("Index " + std::to_string(_idx) + " of of bounds."); + } + return InputVarType(_arr.node_[_idx]); + } rfl::Result get_field_from_object( - const std::string& _name, const InputObjectType& _obj) const noexcept; + const std::string& _name, const InputObjectType& _obj) const noexcept { + auto var = InputVarType(_obj.node_[_name]); + if (!var.node_) { + return error("Object contains no field named '" + _name + "'."); + } + return var; + } - bool is_empty(const InputVarType& _var) const noexcept; + bool is_empty(const InputVarType& _var) const noexcept { + return !_var.node_ && true; + } template rfl::Result to_basic_type(const InputVarType& _var) const noexcept { @@ -69,11 +82,17 @@ struct Reader { static_assert(rfl::always_false_v, "Unsupported type."); } } catch (std::exception& e) { - return rfl::Error(e.what()); + return error(e.what()); } } - rfl::Result to_array(const InputVarType& _var) const noexcept; + rfl::Result to_array( + const InputVarType& _var) const noexcept { + if (!_var.node_.IsSequence()) { + return error("Could not cast to sequence!"); + } + return InputArrayType(_var.node_); + } template std::optional read_array(const ArrayReader& _array_reader, @@ -102,7 +121,12 @@ struct Reader { } rfl::Result to_object( - const InputVarType& _var) const noexcept; + const InputVarType& _var) const noexcept { + if (!_var.node_.IsMap()) { + return error("Could not cast to map!"); + } + return InputObjectType(_var.node_); + } template rfl::Result use_custom_constructor( @@ -110,7 +134,7 @@ struct Reader { try { return T::from_yaml_obj(_var); } catch (std::exception& e) { - return rfl::Error(e.what()); + return error(e.what()); } } }; diff --git a/include/rfl/yaml/read.hpp b/include/rfl/yaml/read.hpp index d25744ee..29ce03b4 100644 --- a/include/rfl/yaml/read.hpp +++ b/include/rfl/yaml/read.hpp @@ -33,7 +33,7 @@ Result> read(const std::string& _yaml_str) { const auto var = InputVarType(YAML::Load(_yaml_str)); return read(var); } catch (std::exception& e) { - return Error(e.what()); + return error(e.what()); } } diff --git a/src/reflectcpp.cpp b/src/reflectcpp.cpp index 5fa52a99..ae3c4b3b 100644 --- a/src/reflectcpp.cpp +++ b/src/reflectcpp.cpp @@ -30,7 +30,6 @@ SOFTWARE. // compilation. #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" diff --git a/src/reflectcpp_avro.cpp b/src/reflectcpp_avro.cpp index d7b64f63..e981badf 100644 --- a/src/reflectcpp_avro.cpp +++ b/src/reflectcpp_avro.cpp @@ -29,7 +29,6 @@ SOFTWARE. // 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" diff --git a/src/reflectcpp_bson.cpp b/src/reflectcpp_bson.cpp index 11be3f60..4fa2e671 100644 --- a/src/reflectcpp_bson.cpp +++ b/src/reflectcpp_bson.cpp @@ -29,5 +29,4 @@ SOFTWARE. // Also, this speeds up compile time, compared to multiple separate .cpp files // compilation. -#include "rfl/bson/Reader.cpp" #include "rfl/bson/Writer.cpp" diff --git a/src/reflectcpp_cbor.cpp b/src/reflectcpp_cbor.cpp index 0c9890e0..1a813fba 100644 --- a/src/reflectcpp_cbor.cpp +++ b/src/reflectcpp_cbor.cpp @@ -29,5 +29,4 @@ SOFTWARE. // Also, this speeds up compile time, compared to multiple separate .cpp files // compilation. -#include "rfl/cbor/Reader.cpp" #include "rfl/cbor/Writer.cpp" diff --git a/src/reflectcpp_flexbuf.cpp b/src/reflectcpp_flexbuf.cpp index 0d636abf..73508179 100644 --- a/src/reflectcpp_flexbuf.cpp +++ b/src/reflectcpp_flexbuf.cpp @@ -29,5 +29,4 @@ SOFTWARE. // Also, this speeds up compile time, compared to multiple separate .cpp files // compilation. -#include "rfl/flexbuf/Reader.cpp" #include "rfl/flexbuf/Writer.cpp" diff --git a/src/reflectcpp_json.cpp b/src/reflectcpp_json.cpp index e1e9a032..7b7bd66e 100644 --- a/src/reflectcpp_json.cpp +++ b/src/reflectcpp_json.cpp @@ -29,6 +29,5 @@ SOFTWARE. // Also, this speeds up compile time, compared to multiple separate .cpp files // compilation. -#include "rfl/json/Reader.cpp" #include "rfl/json/Writer.cpp" #include "rfl/json/to_schema.cpp" diff --git a/src/reflectcpp_msgpack.cpp b/src/reflectcpp_msgpack.cpp index 529b7903..235062e3 100644 --- a/src/reflectcpp_msgpack.cpp +++ b/src/reflectcpp_msgpack.cpp @@ -29,5 +29,4 @@ SOFTWARE. // Also, this speeds up compile time, compared to multiple separate .cpp files // compilation. -#include "rfl/msgpack/Reader.cpp" #include "rfl/msgpack/Writer.cpp" diff --git a/src/reflectcpp_toml.cpp b/src/reflectcpp_toml.cpp index bac9d211..bc25e137 100644 --- a/src/reflectcpp_toml.cpp +++ b/src/reflectcpp_toml.cpp @@ -29,5 +29,4 @@ SOFTWARE. // Also, this speeds up compile time, compared to multiple separate .cpp files // compilation. -#include "rfl/toml/Reader.cpp" #include "rfl/toml/Writer.cpp" diff --git a/src/reflectcpp_ubjson.cpp b/src/reflectcpp_ubjson.cpp index b3dc8db7..a9f7c2fa 100644 --- a/src/reflectcpp_ubjson.cpp +++ b/src/reflectcpp_ubjson.cpp @@ -29,5 +29,4 @@ SOFTWARE. // Also, this speeds up compile time, compared to multiple separate .cpp files // compilation. -#include "rfl/ubjson/Reader.cpp" #include "rfl/ubjson/Writer.cpp" diff --git a/src/reflectcpp_xml.cpp b/src/reflectcpp_xml.cpp index a20066a3..bb7949b5 100644 --- a/src/reflectcpp_xml.cpp +++ b/src/reflectcpp_xml.cpp @@ -29,5 +29,4 @@ SOFTWARE. // Also, this speeds up compile time, compared to multiple separate .cpp files // compilation. -#include "rfl/xml/Reader.cpp" #include "rfl/xml/Writer.cpp" diff --git a/src/reflectcpp_yaml.cpp b/src/reflectcpp_yaml.cpp index 8e6b2aad..3f3f1bea 100644 --- a/src/reflectcpp_yaml.cpp +++ b/src/reflectcpp_yaml.cpp @@ -29,5 +29,4 @@ SOFTWARE. // Also, this speeds up compile time, compared to multiple separate .cpp files // compilation. -#include "rfl/yaml/Reader.cpp" #include "rfl/yaml/Writer.cpp" diff --git a/src/rfl/Generic.cpp b/src/rfl/Generic.cpp index 2065de59..1d94a097 100644 --- a/src/rfl/Generic.cpp +++ b/src/rfl/Generic.cpp @@ -74,70 +74,4 @@ Generic::ReflectionType Generic::reflection() const noexcept { value_); } -Result Generic::to_array() const noexcept { - if (const auto* ptr = std::get_if(&value_)) { - return *ptr; - } else { - return Error( - "rfl::Generic: Could not cast the underlying value to an " - "rfl::Generic::Array."); - } -} - -Result Generic::to_bool() const noexcept { - if (const bool* ptr = std::get_if(&value_)) { - return *ptr; - } else { - return Error( - "rfl::Generic: Could not cast the underlying value to a boolean."); - } -} - -Result Generic::to_double() const noexcept { - if (const double* ptr = std::get_if(&value_)) { - return *ptr; - } else { - return Error( - "rfl::Generic: Could not cast the underlying value to a double."); - } -} - -Result Generic::to_int() const noexcept { - if (const int* ptr = std::get_if(&value_)) { - return *ptr; - } else { - return Error( - "rfl::Generic: Could not cast the underlying value to an integer."); - } -} - -Result Generic::to_object() const noexcept { - if (const auto* ptr = std::get_if(&value_)) { - return *ptr; - } else { - return Error( - "rfl::Generic: Could not cast the underlying value to an " - "rfl::Generic::Object."); - } -} - -Result Generic::to_null() const noexcept { - if (const auto* ptr = std::get_if(&value_)) { - return *ptr; - } else { - return Error( - "rfl::Generic: Could not cast the underlying value to " - "rfl::Generic::Null."); - } -} - -Result Generic::to_string() const noexcept { - if (const auto* ptr = std::get_if(&value_)) { - return *ptr; - } else { - return Error( - "rfl::Generic: Could not cast the underlying value to a string."); - } -} - } // namespace rfl diff --git a/src/rfl/avro/Reader.cpp b/src/rfl/avro/Reader.cpp deleted file mode 100644 index 6d8bd18e..00000000 --- a/src/rfl/avro/Reader.cpp +++ /dev/null @@ -1,49 +0,0 @@ -#include "rfl/avro/Reader.hpp" - -#include "rfl/parsing/schemaful/IsSchemafulReader.hpp" - -namespace rfl::avro { - -static_assert(parsing::schemaful::IsSchemafulReader, - "This must be a schemaful reader."); - -bool Reader::is_empty(const InputVarType& _var) const noexcept { - return avro_value_get_type(_var.val_) == AVRO_NULL; -} - -rfl::Result Reader::to_array( - const InputVarType& _var) const noexcept { - if (avro_value_get_type(_var.val_) != AVRO_ARRAY) { - return Error("Could not cast to an array."); - } - return InputArrayType{_var.val_}; -} - -rfl::Result Reader::to_object( - const InputVarType& _var) const noexcept { - const auto type = avro_value_get_type(_var.val_); - if (type != AVRO_RECORD) { - return Error("Could not cast to an object."); - } - return InputObjectType{_var.val_}; -} - -rfl::Result Reader::to_map( - const InputVarType& _var) const noexcept { - const auto type = avro_value_get_type(_var.val_); - if (type != AVRO_MAP) { - return Error("Could not cast to a map."); - } - return InputMapType{_var.val_}; -} - -rfl::Result Reader::to_union( - const InputVarType& _var) const noexcept { - const auto type = avro_value_get_type(_var.val_); - if (type != AVRO_UNION) { - return Error("Could not cast to a union."); - } - return InputUnionType{_var.val_}; -} - -} // namespace rfl::avro diff --git a/src/rfl/bson/Reader.cpp b/src/rfl/bson/Reader.cpp deleted file mode 100644 index 6d28b770..00000000 --- a/src/rfl/bson/Reader.cpp +++ /dev/null @@ -1,72 +0,0 @@ -#include "rfl/bson/Reader.hpp" - -namespace rfl::bson { - -rfl::Result Reader::get_field_from_array( - const size_t _idx, const InputArrayType& _arr) const noexcept { - bson_t b; - bson_iter_t iter; - const auto doc = _arr.val_->value.v_doc; - if (bson_init_static(&b, doc.data, doc.data_len)) { - if (bson_iter_init(&iter, &b)) { - size_t i = 0; - while (bson_iter_next(&iter)) { - if (i == _idx) { - return to_input_var(&iter); - } - ++i; - } - } else { - return Error("Could not init the array iteration."); - } - } else { - return Error("Could not init array."); - } - return Error("Index " + std::to_string(_idx) + " of of bounds."); -} - -rfl::Result Reader::get_field_from_object( - const std::string& _name, const InputObjectType& _obj) const noexcept { - bson_t b; - bson_iter_t iter; - const auto doc = _obj.val_->value.v_doc; - if (bson_init_static(&b, doc.data, doc.data_len)) { - if (bson_iter_init(&iter, &b)) { - while (bson_iter_next(&iter)) { - auto key = std::string(bson_iter_key(&iter)); - if (key == _name) { - return to_input_var(&iter); - } - } - } - } - return Error("No field named '" + _name + "' was found."); -} - -bool Reader::is_empty(const InputVarType& _var) const noexcept { - return _var.val_->value_type == BSON_TYPE_NULL; -} - -rfl::Result Reader::to_array( - const InputVarType& _var) const noexcept { - const auto btype = _var.val_->value_type; - if (btype != BSON_TYPE_ARRAY && btype != BSON_TYPE_DOCUMENT) { - return Error("Could not cast to an array."); - } - return InputArrayType{_var.val_}; -} - -rfl::Result Reader::to_object( - const InputVarType& _var) const noexcept { - const auto btype = _var.val_->value_type; - if (btype != BSON_TYPE_DOCUMENT) { - return Error("Could not cast to a document."); - } - return InputObjectType{_var.val_}; -} - -Reader::InputVarType Reader::to_input_var(bson_iter_t* _iter) const noexcept { - return InputVarType{bson_iter_value(_iter)}; -} - -} // namespace rfl::bson diff --git a/src/rfl/capnproto/Reader.cpp b/src/rfl/capnproto/Reader.cpp index f6fa03bf..08ea2bad 100644 --- a/src/rfl/capnproto/Reader.cpp +++ b/src/rfl/capnproto/Reader.cpp @@ -16,43 +16,7 @@ Reader::identify_discriminant(const InputUnionType& _union) const noexcept { } ++ix; } - return std::nullopt; -} - -bool Reader::is_empty(const InputVarType& _var) const noexcept { - return _var.val_.getType() == capnp::DynamicValue::VOID; -} - -rfl::Result Reader::to_array( - const InputVarType& _var) const noexcept { - if (_var.val_.getType() != capnp::DynamicValue::LIST) { - return Error("Could not cast to a list."); - } - return InputArrayType{_var.val_.as()}; -} - -rfl::Result Reader::to_object( - const InputVarType& _var) const noexcept { - if (_var.val_.getType() != capnp::DynamicValue::STRUCT) { - return Error("Could not cast to a struct."); - } - return InputObjectType{_var.val_.as()}; -} - -rfl::Result Reader::to_map( - const InputVarType& _var) const noexcept { - if (_var.val_.getType() != capnp::DynamicValue::STRUCT) { - return Error("Could not cast to a map."); - } - return InputMapType{_var.val_.as()}; -} - -rfl::Result Reader::to_union( - const InputVarType& _var) const noexcept { - if (_var.val_.getType() != capnp::DynamicValue::STRUCT) { - return Error("Could not cast to a struct."); - } - return InputUnionType{_var.val_.as()}; + return std::optional>(); } } // namespace rfl::capnproto diff --git a/src/rfl/cbor/Reader.cpp b/src/rfl/cbor/Reader.cpp deleted file mode 100644 index 32014948..00000000 --- a/src/rfl/cbor/Reader.cpp +++ /dev/null @@ -1,43 +0,0 @@ -#include "rfl/cbor/Reader.hpp" - -namespace rfl::cbor { - -rfl::Result Reader::get_field_from_array( - const size_t _idx, const InputArrayType& _arr) const noexcept { - if (_idx >= _arr.val_->size()) { - return Error("Index out of range."); - } - return InputVarType{&_arr.val_->at(_idx)}; -} - -rfl::Result Reader::get_field_from_object( - const std::string& _name, const InputObjectType& _obj) const noexcept { - for (auto& kv : _obj.val_->object_range()) { - if (kv.key() == _name) { - return InputVarType{&kv.value()}; - }; - } - return Error("Field name '" + _name + "' not found."); -} - -bool Reader::is_empty(const InputVarType& _var) const noexcept { - return _var.val_->is_null(); -} - -rfl::Result Reader::to_array( - const InputVarType& _var) const noexcept { - if (!_var.val_->is_array()) { - return Error("Could not cast to an array."); - } - return InputArrayType{_var.val_}; -} - -rfl::Result Reader::to_object( - const InputVarType& _var) const noexcept { - if (!_var.val_->is_object()) { - return Error("Could not cast to an object."); - } - return InputObjectType{_var.val_}; -} - -} // namespace rfl::cbor diff --git a/src/rfl/flexbuf/Reader.cpp b/src/rfl/flexbuf/Reader.cpp deleted file mode 100644 index ff5888f1..00000000 --- a/src/rfl/flexbuf/Reader.cpp +++ /dev/null @@ -1,44 +0,0 @@ -#include "rfl/flexbuf/Reader.hpp" - -namespace rfl::flexbuf { - -rfl::Result Reader::get_field_from_array( - const size_t _idx, const InputArrayType& _arr) const noexcept { - if (_idx >= _arr.size()) { - return rfl::Error("Index " + std::to_string(_idx) + " of of bounds."); - } - return _arr[_idx]; -} - -rfl::Result Reader::get_field_from_object( - const std::string& _name, const InputObjectType& _obj) const noexcept { - const auto keys = _obj.Keys(); - for (size_t i = 0; i < keys.size(); ++i) { - if (_name == keys[i].AsString().c_str()) { - return _obj.Values()[i]; - } - } - return rfl::Error("Map does not contain any element called '" + _name + "'."); -} - -bool Reader::is_empty(const InputVarType& _var) const noexcept { - return _var.IsNull(); -} - -rfl::Result Reader::to_array( - const InputVarType& _var) const noexcept { - if (!_var.IsVector()) { - return rfl::Error("Could not cast to Vector."); - } - return _var.AsVector(); -} - -rfl::Result Reader::to_object( - const InputVarType& _var) const noexcept { - if (!_var.IsMap()) { - return rfl::Error("Could not cast to Map!"); - } - return _var.AsMap(); -} - -} // namespace rfl::flexbuf diff --git a/src/rfl/generic/Reader.cpp b/src/rfl/generic/Reader.cpp deleted file mode 100644 index e49000ef..00000000 --- a/src/rfl/generic/Reader.cpp +++ /dev/null @@ -1,58 +0,0 @@ -/* - -MIT License - -Copyright (c) 2023-2024 Code17 GmbH - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - -*/ - -#include "rfl/generic/Reader.hpp" - -namespace rfl::generic { - -rfl::Result Reader::get_field_from_array( - const size_t _idx, const InputArrayType& _arr) const noexcept { - if (_idx >= _arr.size()) { - return rfl::Error("Index " + std::to_string(_idx) + " of of bounds."); - } - return _arr[_idx]; -} - -rfl::Result Reader::get_field_from_object( - const std::string& _name, const InputObjectType& _obj) const noexcept { - return _obj.get(_name); -} - -bool Reader::is_empty(const InputVarType& _var) const noexcept { - return _var.is_null(); -} - -rfl::Result Reader::to_array( - const InputVarType& _var) const noexcept { - return _var.to_array(); -} - -rfl::Result Reader::to_object( - const InputVarType& _var) const noexcept { - return _var.to_object(); -} - -} // namespace rfl::generic diff --git a/src/rfl/json/Reader.cpp b/src/rfl/json/Reader.cpp deleted file mode 100644 index 7aa4cbf9..00000000 --- a/src/rfl/json/Reader.cpp +++ /dev/null @@ -1,69 +0,0 @@ -/* - -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/json/Reader.hpp" - -namespace rfl::json { - -rfl::Result Reader::get_field_from_array( - const size_t _idx, const InputArrayType _arr) const noexcept { - const auto var = InputVarType(yyjson_arr_get(_arr.val_, _idx)); - if (!var.val_) { - return rfl::Error("Index " + std::to_string(_idx) + " of of bounds."); - } - return var; -} - -rfl::Result Reader::get_field_from_object( - const std::string& _name, const InputObjectType _obj) const noexcept { - const auto var = InputVarType(yyjson_obj_get(_obj.val_, _name.c_str())); - if (!var.val_) { - return rfl::Error("Object contains no field named '" + _name + "'."); - } - return var; -} - -bool Reader::is_empty(const InputVarType _var) const noexcept { - return !_var.val_ || yyjson_is_null(_var.val_); -} - -rfl::Result Reader::to_array( - const InputVarType _var) const noexcept { - if (!yyjson_is_arr(_var.val_)) { - return rfl::Error("Could not cast to array!"); - } - return InputArrayType(_var.val_); -} - -rfl::Result Reader::to_object( - const InputVarType _var) const noexcept { - if (!yyjson_is_obj(_var.val_)) { - return rfl::Error("Could not cast to object!"); - } - return InputObjectType(_var.val_); -} - -} // namespace rfl::json diff --git a/src/rfl/msgpack/Reader.cpp b/src/rfl/msgpack/Reader.cpp deleted file mode 100644 index 5c88b7fe..00000000 --- a/src/rfl/msgpack/Reader.cpp +++ /dev/null @@ -1,50 +0,0 @@ -#include "rfl/msgpack/Reader.hpp" - -namespace rfl::msgpack { - -rfl::Result Reader::get_field_from_array( - const size_t _idx, const InputArrayType _arr) const noexcept { - if (_idx >= _arr.size) { - return rfl::Error("Index " + std::to_string(_idx) + " of of bounds."); - } - return _arr.ptr[_idx]; -} - -rfl::Result Reader::get_field_from_object( - const std::string& _name, const InputObjectType& _obj) const noexcept { - for (uint32_t i = 0; i < _obj.size; ++i) { - const auto& key = _obj.ptr[i].key; - if (key.type != MSGPACK_OBJECT_STR) { - return Error("Key in element " + std::to_string(i) + - " was not a string."); - } - const auto current_name = - std::string_view(key.via.str.ptr, key.via.str.size); - if (_name == current_name) { - return _obj.ptr[i].val; - } - } - return Error("No field named '" + _name + "' was found."); -} - -bool Reader::is_empty(const InputVarType& _var) const noexcept { - return _var.type == MSGPACK_OBJECT_NIL; -} - -rfl::Result Reader::to_array( - const InputVarType& _var) const noexcept { - if (_var.type != MSGPACK_OBJECT_ARRAY) { - return Error("Could not cast to an array."); - } - return _var.via.array; -} - -rfl::Result Reader::to_object( - const InputVarType& _var) const noexcept { - if (_var.type != MSGPACK_OBJECT_MAP) { - return Error("Could not cast to a map."); - } - return _var.via.map; -} - -} // namespace rfl::msgpack diff --git a/src/rfl/toml/Reader.cpp b/src/rfl/toml/Reader.cpp deleted file mode 100644 index 74b91d8d..00000000 --- a/src/rfl/toml/Reader.cpp +++ /dev/null @@ -1,44 +0,0 @@ -#include "rfl/toml/Reader.hpp" - -namespace rfl::toml { - -rfl::Result Reader::get_field_from_array( - const size_t _idx, const InputArrayType _arr) const noexcept { - if (_idx >= _arr->size()) { - return rfl::Error("Index " + std::to_string(_idx) + " of of bounds."); - } - return _arr->get(_idx); -} - -rfl::Result Reader::get_field_from_object( - const std::string& _name, const InputObjectType& _obj) const noexcept { - auto var = (*_obj)[_name]; - if (!var) { - return rfl::Error("Object contains no field named '" + _name + "'."); - } - return var.node(); -} - -bool Reader::is_empty(const InputVarType& _var) const noexcept { - return !_var && true; -} - -rfl::Result Reader::to_array( - const InputVarType& _var) const noexcept { - const auto ptr = _var->as_array(); - if (!ptr) { - return rfl::Error("Could not cast to an array!"); - } - return ptr; -} - -rfl::Result Reader::to_object( - const InputVarType& _var) const noexcept { - const auto ptr = _var->as_table(); - if (!ptr) { - return rfl::Error("Could not cast to a table!"); - } - return ptr; -} - -} // namespace rfl::toml diff --git a/src/rfl/ubjson/Reader.cpp b/src/rfl/ubjson/Reader.cpp deleted file mode 100644 index 17d82e71..00000000 --- a/src/rfl/ubjson/Reader.cpp +++ /dev/null @@ -1,43 +0,0 @@ -#include "rfl/ubjson/Reader.hpp" - -namespace rfl::ubjson { - -rfl::Result Reader::get_field_from_array( - const size_t _idx, const InputArrayType& _arr) const noexcept { - if (_idx >= _arr.val_->size()) { - return Error("Index out of range."); - } - return InputVarType{&_arr.val_->at(_idx)}; -} - -rfl::Result Reader::get_field_from_object( - const std::string& _name, const InputObjectType& _obj) const noexcept { - for (auto& kv : _obj.val_->object_range()) { - if (kv.key() == _name) { - return InputVarType{&kv.value()}; - }; - } - return Error("Field name '" + _name + "' not found."); -} - -bool Reader::is_empty(const InputVarType& _var) const noexcept { - return _var.val_->is_null(); -} - -rfl::Result Reader::to_array( - const InputVarType& _var) const noexcept { - if (!_var.val_->is_array()) { - return Error("Could not cast to an array."); - } - return InputArrayType{_var.val_}; -} - -rfl::Result Reader::to_object( - const InputVarType& _var) const noexcept { - if (!_var.val_->is_object()) { - return Error("Could not cast to an object."); - } - return InputObjectType{_var.val_}; -} - -} // namespace rfl::ubjson diff --git a/src/rfl/xml/Reader.cpp b/src/rfl/xml/Reader.cpp deleted file mode 100644 index c06ed912..00000000 --- a/src/rfl/xml/Reader.cpp +++ /dev/null @@ -1,87 +0,0 @@ -/* - -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/xml/Reader.hpp" - -namespace rfl::xml { - -/// XML-only helper function. This is needed because XML distinguishes between -/// nodes and attributes. -static rfl::Result cast_as_node( - const std::variant& - _node_or_attribute) { - const auto cast = [](const auto& _n) -> Result { - using Type = std::remove_cvref_t; - if constexpr (std::is_same()) { - return _n; - } else { - return Error("Field '" + std::string(_n.name()) + "' is an attribute."); - } - }; - return std::visit(cast, _node_or_attribute); -} - -rfl::Result Reader::get_field_from_array( - const size_t _idx, const InputArrayType& _arr) const noexcept { - const auto name = _arr.node_.name(); - size_t i = 0; - for (auto node = _arr.node_; node; node = node.next_sibling(name)) { - if (i == _idx) { - return InputVarType(node); - } - } - return rfl::Error("Index " + std::to_string(_idx) + " of of bounds."); -} - -rfl::Result Reader::get_field_from_object( - const std::string& _name, const InputObjectType _obj) const noexcept { - const auto node = _obj.node_.child(_name.c_str()); - if (!node) { - return rfl::Error("Object contains no field named '" + _name + "'."); - } - return InputVarType(node); -} - -bool Reader::is_empty(const InputVarType _var) const noexcept { - const auto wrap = [](const auto& _node) { return !_node; }; - return std::visit(cast_as_node, _var.node_or_attribute_) - .transform(wrap) - .value_or(false); -} - -rfl::Result Reader::to_array( - const InputVarType _var) const noexcept { - const auto wrap = [](const auto& _node) { return InputArrayType(_node); }; - return std::visit(cast_as_node, _var.node_or_attribute_).transform(wrap); -} - -rfl::Result Reader::to_object( - const InputVarType _var) const noexcept { - const auto wrap = [](const auto& _node) { return InputObjectType(_node); }; - return std::visit(cast_as_node, _var.node_or_attribute_).transform(wrap); -} - -} // namespace rfl::xml diff --git a/src/rfl/yaml/Reader.cpp b/src/rfl/yaml/Reader.cpp deleted file mode 100644 index 8f77f65d..00000000 --- a/src/rfl/yaml/Reader.cpp +++ /dev/null @@ -1,42 +0,0 @@ -#include "rfl/yaml/Reader.hpp" - -namespace rfl::yaml { - -rfl::Result Reader::get_field_from_array( - const size_t _idx, const InputArrayType& _arr) const noexcept { - if (_idx >= _arr.node_.size()) { - return rfl::Error("Index " + std::to_string(_idx) + " of of bounds."); - } - return InputVarType(_arr.node_[_idx]); -} - -rfl::Result Reader::get_field_from_object( - const std::string& _name, const InputObjectType& _obj) const noexcept { - auto var = InputVarType(_obj.node_[_name]); - if (!var.node_) { - return rfl::Error("Object contains no field named '" + _name + "'."); - } - return var; -} - -bool Reader::is_empty(const InputVarType& _var) const noexcept { - return !_var.node_ && true; -} - -rfl::Result Reader::to_array( - const InputVarType& _var) const noexcept { - if (!_var.node_.IsSequence()) { - return rfl::Error("Could not cast to sequence!"); - } - return InputArrayType(_var.node_); -} - -rfl::Result Reader::to_object( - const InputVarType& _var) const noexcept { - if (!_var.node_.IsMap()) { - return rfl::Error("Could not cast to map!"); - } - return InputObjectType(_var.node_); -} - -} // namespace rfl::yaml diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index cdd1a6d5..0ccde04c 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -3,7 +3,7 @@ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -O2") if (MSVC) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std:c++20") else() - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O3 -Wall -ggdb -ftemplate-backtrace-limit=0") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O3 -Wall -Werror -ggdb -ftemplate-backtrace-limit=0") endif() if (REFLECTCPP_JSON) @@ -12,18 +12,10 @@ if (REFLECTCPP_JSON) add_subdirectory(json_c_arrays_and_inheritance) endif () -if (REFLECTCPP_AVRO) - add_subdirectory(avro) -endif() - if (REFLECTCPP_BSON) add_subdirectory(bson) endif() -if (REFLECTCPP_CAPNPROTO) - add_subdirectory(capnproto) -endif() - if (REFLECTCPP_CBOR) add_subdirectory(cbor) endif() diff --git a/tests/README.md b/tests/README.md index 67ccb3b8..0715a987 100644 --- a/tests/README.md +++ b/tests/README.md @@ -16,7 +16,7 @@ git submodule update --init To compile the tests, do the following: ```bash -cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DREFLECTCPP_BUILD_TESTS=ON +cmake -S . -B build -DCMAKE_CXX_STANDARD=20 -DCMAKE_BUILD_TYPE=Release -DREFLECTCPP_BUILD_TESTS=ON cmake --build build -j 4 # gcc, clang cmake --build build --config Release -j 4 # MSVC ``` @@ -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_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 -S . -B build -DCMAKE_CXX_STANDARD=20 -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 ``` diff --git a/tests/bson/write_and_read.hpp b/tests/bson/write_and_read.hpp index fc9814a0..3a4242b3 100644 --- a/tests/bson/write_and_read.hpp +++ b/tests/bson/write_and_read.hpp @@ -13,7 +13,7 @@ void write_and_read(const auto& _struct) { const auto serialized1 = rfl::bson::write(_struct); const auto res = rfl::bson::read(serialized1); EXPECT_TRUE(res && true) << "Test failed on read. Error: " - << res.error().value().what(); + << res.error().what(); const auto serialized2 = rfl::bson::write(res.value()); EXPECT_EQ(serialized1, serialized2); } diff --git a/tests/cbor/CMakeLists.txt b/tests/cbor/CMakeLists.txt index d839f46d..b55da773 100644 --- a/tests/cbor/CMakeLists.txt +++ b/tests/cbor/CMakeLists.txt @@ -16,3 +16,4 @@ target_link_libraries( find_package(GTest) gtest_discover_tests(reflect-cpp-cbor-tests) + diff --git a/tests/cbor/write_and_read.hpp b/tests/cbor/write_and_read.hpp index 8bbf4d0f..5a4cd180 100644 --- a/tests/cbor/write_and_read.hpp +++ b/tests/cbor/write_and_read.hpp @@ -13,7 +13,7 @@ void write_and_read(const auto& _struct) { const auto serialized1 = rfl::cbor::write(_struct); const auto res = rfl::cbor::read(serialized1); EXPECT_TRUE(res && true) << "Test failed on read. Error: " - << res.error().value().what(); + << res.error().what(); const auto serialized2 = rfl::cbor::write(res.value()); EXPECT_EQ(serialized1, serialized2); } diff --git a/tests/flexbuffers/CMakeLists.txt b/tests/flexbuffers/CMakeLists.txt index 6e5cc200..32ebe45e 100644 --- a/tests/flexbuffers/CMakeLists.txt +++ b/tests/flexbuffers/CMakeLists.txt @@ -18,3 +18,4 @@ target_link_libraries( find_package(GTest) gtest_discover_tests(reflect-cpp-flexbuffers-tests) + diff --git a/tests/flexbuffers/write_and_read.hpp b/tests/flexbuffers/write_and_read.hpp index daab3062..1a10fc30 100644 --- a/tests/flexbuffers/write_and_read.hpp +++ b/tests/flexbuffers/write_and_read.hpp @@ -13,7 +13,7 @@ void write_and_read(const auto& _struct) { const auto serialized1 = rfl::flexbuf::write(_struct); const auto res = rfl::flexbuf::read(serialized1); EXPECT_TRUE(res && true) << "Test failed on read. Error: " - << res.error().value().what(); + << res.error().what(); const auto serialized2 = rfl::flexbuf::write(res.value()); EXPECT_EQ(serialized1, serialized2); } diff --git a/tests/generic/CMakeLists.txt b/tests/generic/CMakeLists.txt index 0e3b03a7..3ac9ae31 100644 --- a/tests/generic/CMakeLists.txt +++ b/tests/generic/CMakeLists.txt @@ -17,3 +17,4 @@ target_link_libraries( find_package(GTest) gtest_discover_tests(reflect-cpp-generic-tests) + diff --git a/tests/generic/write_and_read.hpp b/tests/generic/write_and_read.hpp index 7aa0e7da..66cc17c7 100644 --- a/tests/generic/write_and_read.hpp +++ b/tests/generic/write_and_read.hpp @@ -14,7 +14,7 @@ void write_and_read(const auto& _struct) { EXPECT_EQ(rfl::json::write(serialized1), rfl::json::write(_struct)); const auto res = rfl::from_generic(serialized1); EXPECT_TRUE(res && true) << "Test failed on read. Error: " - << res.error().value().what(); + << res.error().what(); EXPECT_EQ(rfl::json::write(serialized1), rfl::json::write(res.value())); } diff --git a/tests/json/CMakeLists.txt b/tests/json/CMakeLists.txt index ac468c3c..9889ef01 100644 --- a/tests/json/CMakeLists.txt +++ b/tests/json/CMakeLists.txt @@ -18,3 +18,4 @@ target_link_libraries( find_package(GTest) gtest_discover_tests(reflect-cpp-json-tests) + diff --git a/tests/json/test_error_messages.cpp b/tests/json/test_error_messages.cpp index 5b092137..f57a7653 100644 --- a/tests/json/test_error_messages.cpp +++ b/tests/json/test_error_messages.cpp @@ -1,11 +1,11 @@ +#include + #include #include #include #include #include -#include - namespace test_error_messages { struct Person { @@ -26,8 +26,8 @@ TEST(json, test_error_messages) { 2) Failed to parse field 'birthday': String '04/19/1987' did not match format '%Y-%m-%d'. 3) Field named 'children' not found.)"; - EXPECT_TRUE(result.error() && true); + EXPECT_TRUE(!result.has_value() && true); - EXPECT_EQ(result.error().value().what(), expected); + EXPECT_EQ(result.error().what(), expected); } } // namespace test_error_messages diff --git a/tests/json/test_result.cpp b/tests/json/test_result.cpp index bc369790..b72c767e 100644 --- a/tests/json/test_result.cpp +++ b/tests/json/test_result.cpp @@ -19,7 +19,7 @@ TEST(json, test_result) { const rfl::Result lisa = Person{.first_name = "Lisa"}; - const rfl::Result maggie = rfl::Error("Some error occurred."); + const rfl::Result maggie = rfl::error("Some error occurred."); const auto homer = Person{ .first_name = "Homer", diff --git a/tests/json/write_and_read.hpp b/tests/json/write_and_read.hpp index c7169c51..830791f8 100644 --- a/tests/json/write_and_read.hpp +++ b/tests/json/write_and_read.hpp @@ -25,7 +25,7 @@ void read(const std::string& _json, const auto& _expected) { using T = std::remove_cvref_t; const auto res = rfl::json::read(_json); EXPECT_TRUE(res && true) << "Test failed on read. Error: " - << res.error().value().what(); + << res.error().what(); } template @@ -40,7 +40,7 @@ void write_and_read(const auto& _struct, const std::string& _expected) { << std::endl; const auto res = rfl::json::read(json_string1); EXPECT_TRUE(res && true) << "Test failed on read. Error: " - << res.error().value().what(); + << res.error().what(); const auto json_string2 = rfl::json::write(res.value()); EXPECT_EQ(json_string2, _expected) << "Test failed on read. Expected:" << std::endl diff --git a/tests/json_c_arrays_and_inheritance/CMakeLists.txt b/tests/json_c_arrays_and_inheritance/CMakeLists.txt index cb411bcd..280f8abc 100644 --- a/tests/json_c_arrays_and_inheritance/CMakeLists.txt +++ b/tests/json_c_arrays_and_inheritance/CMakeLists.txt @@ -21,3 +21,4 @@ target_link_libraries( find_package(GTest) gtest_discover_tests(reflect-cpp-json-c-arrays-and-inheritance-tests) + diff --git a/tests/json_c_arrays_and_inheritance/write_and_read.hpp b/tests/json_c_arrays_and_inheritance/write_and_read.hpp index c7169c51..830791f8 100644 --- a/tests/json_c_arrays_and_inheritance/write_and_read.hpp +++ b/tests/json_c_arrays_and_inheritance/write_and_read.hpp @@ -25,7 +25,7 @@ void read(const std::string& _json, const auto& _expected) { using T = std::remove_cvref_t; const auto res = rfl::json::read(_json); EXPECT_TRUE(res && true) << "Test failed on read. Error: " - << res.error().value().what(); + << res.error().what(); } template @@ -40,7 +40,7 @@ void write_and_read(const auto& _struct, const std::string& _expected) { << std::endl; const auto res = rfl::json::read(json_string1); EXPECT_TRUE(res && true) << "Test failed on read. Error: " - << res.error().value().what(); + << res.error().what(); const auto json_string2 = rfl::json::write(res.value()); EXPECT_EQ(json_string2, _expected) << "Test failed on read. Expected:" << std::endl diff --git a/tests/msgpack/CMakeLists.txt b/tests/msgpack/CMakeLists.txt index 26a77a07..9793cc83 100644 --- a/tests/msgpack/CMakeLists.txt +++ b/tests/msgpack/CMakeLists.txt @@ -18,3 +18,4 @@ target_link_libraries( find_package(GTest) gtest_discover_tests(reflect-cpp-msgpack-tests) + diff --git a/tests/msgpack/write_and_read.hpp b/tests/msgpack/write_and_read.hpp index eb6d14b6..f122c6cc 100644 --- a/tests/msgpack/write_and_read.hpp +++ b/tests/msgpack/write_and_read.hpp @@ -13,7 +13,7 @@ void write_and_read(const auto& _struct) { const auto serialized1 = rfl::msgpack::write(_struct); const auto res = rfl::msgpack::read(serialized1); EXPECT_TRUE(res && true) << "Test failed on read. Error: " - << res.error().value().what(); + << res.error().what(); const auto serialized2 = rfl::msgpack::write(res.value()); EXPECT_EQ(serialized1, serialized2); } diff --git a/tests/toml/CMakeLists.txt b/tests/toml/CMakeLists.txt index ddf21e26..5e7beb2c 100644 --- a/tests/toml/CMakeLists.txt +++ b/tests/toml/CMakeLists.txt @@ -16,3 +16,4 @@ target_link_libraries( find_package(GTest) gtest_discover_tests(reflect-cpp-toml-tests) + diff --git a/tests/toml/write_and_read.hpp b/tests/toml/write_and_read.hpp index a46c8fe6..e1dd4af6 100644 --- a/tests/toml/write_and_read.hpp +++ b/tests/toml/write_and_read.hpp @@ -13,7 +13,7 @@ void write_and_read(const auto& _struct) { const auto serialized1 = rfl::toml::write(_struct); const auto res = rfl::toml::read(serialized1); EXPECT_TRUE(res && true) << "Test failed on read. Error: " - << res.error().value().what(); + << res.error().what(); const auto serialized2 = rfl::toml::write(res.value()); EXPECT_EQ(serialized1, serialized2); } diff --git a/tests/ubjson/CMakeLists.txt b/tests/ubjson/CMakeLists.txt index aa62b2ad..e375fcd0 100644 --- a/tests/ubjson/CMakeLists.txt +++ b/tests/ubjson/CMakeLists.txt @@ -16,3 +16,4 @@ target_link_libraries( find_package(GTest) gtest_discover_tests(reflect-cpp-ubjson-tests) + diff --git a/tests/ubjson/write_and_read.hpp b/tests/ubjson/write_and_read.hpp index a7f0c84f..50e5b33b 100644 --- a/tests/ubjson/write_and_read.hpp +++ b/tests/ubjson/write_and_read.hpp @@ -13,7 +13,7 @@ void write_and_read(const auto& _struct) { const auto serialized1 = rfl::ubjson::write(_struct); const auto res = rfl::ubjson::read(serialized1); EXPECT_TRUE(res && true) << "Test failed on read. Error: " - << res.error().value().what(); + << res.error().what(); const auto serialized2 = rfl::ubjson::write(res.value()); EXPECT_EQ(serialized1, serialized2); } diff --git a/tests/xml/CMakeLists.txt b/tests/xml/CMakeLists.txt index 8999f1e3..d2669ebe 100644 --- a/tests/xml/CMakeLists.txt +++ b/tests/xml/CMakeLists.txt @@ -18,3 +18,4 @@ target_link_libraries( find_package(GTest) gtest_discover_tests(reflect-cpp-xml-tests) + diff --git a/tests/xml/write_and_read.hpp b/tests/xml/write_and_read.hpp index a992b5f9..8fbce474 100644 --- a/tests/xml/write_and_read.hpp +++ b/tests/xml/write_and_read.hpp @@ -14,7 +14,7 @@ void write_and_read(const auto& _struct) { const auto serialized1 = rfl::xml::write<_root_name, Ps...>(_struct); const auto res = rfl::xml::read(serialized1); EXPECT_TRUE(res && true) << "Test failed on read. Error: " - << res.error().value().what(); + << res.error().what(); const auto serialized2 = rfl::xml::write<_root_name, Ps...>(res.value()); EXPECT_EQ(serialized1, serialized2); } diff --git a/tests/yaml/CMakeLists.txt b/tests/yaml/CMakeLists.txt index a514a479..899eef04 100644 --- a/tests/yaml/CMakeLists.txt +++ b/tests/yaml/CMakeLists.txt @@ -18,3 +18,4 @@ target_link_libraries( find_package(GTest) gtest_discover_tests(reflect-cpp-yaml-tests) + diff --git a/tests/yaml/write_and_read.hpp b/tests/yaml/write_and_read.hpp index 87cd642e..d49fa999 100644 --- a/tests/yaml/write_and_read.hpp +++ b/tests/yaml/write_and_read.hpp @@ -13,7 +13,7 @@ void write_and_read(const auto& _struct) { const auto serialized1 = rfl::yaml::write(_struct); const auto res = rfl::yaml::read(serialized1); EXPECT_TRUE(res && true) << "Test failed on read. Error: " - << res.error().value().what(); + << res.error().what(); const auto serialized2 = rfl::yaml::write(res.value()); EXPECT_EQ(serialized1, serialized2); }