diff --git a/.github/workflows/linux.yaml b/.github/workflows/linux.yaml index 82807af94..d136faf6b 100644 --- a/.github/workflows/linux.yaml +++ b/.github/workflows/linux.yaml @@ -7,7 +7,7 @@ jobs: strategy: fail-fast: false matrix: - format: ["JSON", "AVRO", "BOOST_SERIALIZATION", "CAPNPROTO", "CBOR", "CEREAL", "FLEXBUFFERS", "MSGPACK", "PARQUET", "TOML", "UBJSON", "XML", "YAML", "benchmarks", "headers"] + format: ["JSON", "AVRO", "BOOST_SERIALIZATION", "CAPNPROTO", "CBOR", "CEREAL", "FLEXBUFFERS", "MSGPACK", "NLOHMANN", "PARQUET", "TOML", "UBJSON", "XML", "YAML", "benchmarks", "headers"] compiler: [llvm, gcc] compiler-version: [11, 12, 13, 14, 16, 17, 18] cxx: [20, 23] diff --git a/.github/workflows/windows.yaml b/.github/workflows/windows.yaml index 8b4af4ad5..a9594f2c9 100644 --- a/.github/workflows/windows.yaml +++ b/.github/workflows/windows.yaml @@ -7,7 +7,7 @@ jobs: strategy: fail-fast: false matrix: - format: ["JSON", "AVRO", "BOOST_SERIALIZATION", "CAPNPROTO", "CBOR", "CEREAL", "FLEXBUFFERS", "MSGPACK", "PARQUET", "TOML", "UBJSON", "XML", "YAML", "benchmarks"] + format: ["JSON", "AVRO", "BOOST_SERIALIZATION", "CAPNPROTO", "CBOR", "CEREAL", "FLEXBUFFERS", "MSGPACK", "NLOHMANN", "PARQUET", "TOML", "UBJSON", "XML", "YAML", "benchmarks"] name: "windows-msvc (${{ matrix.format }})" concurrency: group: "windows-${{ github.ref }}-${{ github.job }}-${{ matrix.format }}" @@ -76,7 +76,7 @@ jobs: strategy: fail-fast: false matrix: - format: ["JSON", "BOOST_SERIALIZATION", "CAPNPROTO", "CBOR", "FLEXBUFFERS", "MSGPACK", "PARQUET", "TOML", "UBJSON", "XML", "YAML"] + format: ["JSON", "BOOST_SERIALIZATION", "CAPNPROTO", "CBOR", "FLEXBUFFERS", "MSGPACK", "NLOHMANN", "PARQUET", "TOML", "UBJSON", "XML", "YAML"] name: "windows-msvc-shared (${{ matrix.format }})" runs-on: windows-latest steps: diff --git a/CMakeLists.txt b/CMakeLists.txt index aae285585..f4599caef 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -16,6 +16,7 @@ option(REFLECTCPP_CEREAL "Enable Cereal support" ${REFLECTCPP_ALL_FORMATS}) option(REFLECTCPP_CSV "Enable CSV support" ${REFLECTCPP_ALL_FORMATS}) option(REFLECTCPP_FLEXBUFFERS "Enable flexbuffers support" ${REFLECTCPP_ALL_FORMATS}) option(REFLECTCPP_MSGPACK "Enable msgpack support" ${REFLECTCPP_ALL_FORMATS}) +option(REFLECTCPP_NLOHMANN "Enable nlohmann/json support" ${REFLECTCPP_ALL_FORMATS}) option(REFLECTCPP_PARQUET "Enable parquet support" ${REFLECTCPP_ALL_FORMATS}) option(REFLECTCPP_XML "Enable XML support" ${REFLECTCPP_ALL_FORMATS}) option(REFLECTCPP_TOML "Enable TOML support" ${REFLECTCPP_ALL_FORMATS}) @@ -82,6 +83,7 @@ if ( REFLECTCPP_CSV OR REFLECTCPP_FLEXBUFFERS OR REFLECTCPP_MSGPACK OR + REFLECTCPP_NLOHMANN OR REFLECTCPP_PARQUET OR REFLECTCPP_XML OR REFLECTCPP_TOML OR @@ -158,6 +160,10 @@ if (REFLECTCPP_USE_VCPKG) list(APPEND VCPKG_MANIFEST_FEATURES "msgpack") endif() + if (REFLECTCPP_NLOHMANN OR REFLECTCPP_CHECK_HEADERS) + list(APPEND VCPKG_MANIFEST_FEATURES "nlohmann") + endif() + if (REFLECTCPP_PARQUET OR REFLECTCPP_CHECK_HEADERS) list(APPEND VCPKG_MANIFEST_FEATURES "parquet") endif() @@ -403,6 +409,13 @@ if (REFLECTCPP_MSGPACK OR REFLECTCPP_CHECK_HEADERS) target_link_libraries(reflectcpp PUBLIC $,msgpack-c,$,msgpackc,msgpack-c>>) endif () +if (REFLECTCPP_NLOHMANN OR REFLECTCPP_CHECK_HEADERS) + if (NOT TARGET nlohmann_json::nlohmann_json) + find_package(nlohmann_json 3.11.3 CONFIG REQUIRED) + endif () + target_link_libraries(reflectcpp PUBLIC nlohmann_json::nlohmann_json) +endif () + if (REFLECTCPP_PARQUET OR REFLECTCPP_CHECK_HEADERS) if (NOT TARGET Arrow) find_package(Arrow CONFIG REQUIRED) diff --git a/README.md b/README.md index 9cfdfa223..2b2b4d688 100644 --- a/README.md +++ b/README.md @@ -79,6 +79,7 @@ The following table lists the serialization formats currently supported by refle | CSV | [Apache Arrow](https://arrow.apache.org/) | >= 21.0.0 | Apache 2.0 | Tabular textual format | | flexbuffers | [flatbuffers](https://github.com/google/flatbuffers) | >= 23.5.26 | Apache 2.0 | Schema-less version of flatbuffers, binary format | | msgpack | [msgpack-c](https://github.com/msgpack/msgpack-c) | >= 6.0.0 | BSL 1.0 | JSON-like binary format | +| nlohmann/json| [nlohmann/json](https://github.com/nlohmann/json) | >= 3.11.3 | MIT | Header-only DOM adapter (`nlohmann::json`, `ordered_json`) | | parquet | [Apache Arrow](https://arrow.apache.org/) | >= 21.0.0 | Apache 2.0 | Tabular binary format | | TOML | [toml++](https://github.com/marzer/tomlplusplus) | >= 3.4.0 | MIT | Textual format with an emphasis on readability | | UBJSON | [jsoncons](https://github.com/danielaparker/jsoncons)| >= 0.176.0 | BSL 1.0 | JSON-like binary format | diff --git a/conanfile.py b/conanfile.py index a6a1ade85..371985be5 100644 --- a/conanfile.py +++ b/conanfile.py @@ -45,6 +45,7 @@ class ReflectCppConan(ConanFile): "with_csv": [True, False], "with_flatbuffers": [True, False], "with_msgpack": [True, False], + "with_nlohmann": [True, False], "with_parquet": [True, False], "with_toml": [True, False], "with_ubjson": [True, False], @@ -62,6 +63,7 @@ class ReflectCppConan(ConanFile): "with_csv": False, "with_flatbuffers": False, "with_msgpack": False, + "with_nlohmann": False, "with_parquet": False, "with_toml": False, "with_ubjson": False, @@ -96,6 +98,8 @@ def requirements(self): self.requires("flatbuffers/24.3.25", transitive_headers=True) if self.options.with_msgpack: self.requires("msgpack-c/6.0.0", transitive_headers=True) + if self.options.with_nlohmann: + self.requires("nlohmann_json/3.11.3", transitive_headers=True) if self.options.with_toml: self.requires("tomlplusplus/3.4.0", transitive_headers=True) if self.options.with_xml: @@ -136,6 +140,7 @@ def generate(self): tc.cache_variables["REFLECTCPP_CSV"] = self.options.with_csv tc.cache_variables["REFLECTCPP_FLEXBUFFERS"] = self.options.with_flatbuffers tc.cache_variables["REFLECTCPP_MSGPACK"] = self.options.with_msgpack + tc.cache_variables["REFLECTCPP_NLOHMANN"] = self.options.with_nlohmann tc.cache_variables["REFLECTCPP_PARQUET"] = self.options.with_parquet tc.cache_variables["REFLECTCPP_TOML"] = self.options.with_toml tc.cache_variables["REFLECTCPP_XML"] = self.options.with_xml diff --git a/docs/content/supported_formats/_index.md b/docs/content/supported_formats/_index.md index 91bd2e458..eb6a27749 100644 --- a/docs/content/supported_formats/_index.md +++ b/docs/content/supported_formats/_index.md @@ -18,6 +18,7 @@ Human-readable formats for configuration, data exchange, and legacy integration. {{< cards >}} {{< card link="json" title="JSON" icon="book-open" subtitle="Out-of-the-box support via yyjson. Standard for web APIs and data interchange." >}} + {{< card link="nlohmann" title="nlohmann/json" icon="book-open" subtitle="Header-only direct DOM interop with nlohmann::json and nlohmann::ordered_json." >}} {{< card link="yaml" title="YAML" icon="book-open" subtitle="Textual format with an emphasis on readability. Widely used in Docker, Kubernetes, and CI/CD configuration." >}} {{< card link="toml" title="TOML" icon="book-open" subtitle="Textual format with an emphasis on readability. Popular for application configuration in the Rust ecosystem." >}} {{< card link="csv" title="CSV" icon="book-open" subtitle="Tabular textual format. The universal interchange format for spreadsheets, databases, and ETL pipelines." >}} diff --git a/docs/content/supported_formats/nlohmann.md b/docs/content/supported_formats/nlohmann.md new file mode 100644 index 000000000..1ff4d8969 --- /dev/null +++ b/docs/content/supported_formats/nlohmann.md @@ -0,0 +1,71 @@ +--- +breadcrumbs: true +--- + +# nlohmann/json + +For `nlohmann::json` interoperability, include `` and enable `-DREFLECTCPP_NLOHMANN=ON` when building reflect-cpp (or link `nlohmann_json::nlohmann_json` directly — the adapter is header-only and requires `nlohmann/json >= 3.11.3`). It has no dependency on `yyjson` and works with `-DREFLECTCPP_JSON=OFF`. + +## Reading and writing (`nlohmann::json` and `nlohmann::ordered_json`) + +Convert reflected structs directly to and from `nlohmann::basic_json` without string round-trips: + +```cpp +#include + +struct Person { + std::string first_name; + rfl::Validator> age; + std::optional nickname; +}; + +const Person src{.first_name = "Ada", .age = 36, .nickname = "countess"}; + +// Serialize to nlohmann::json (supports reflect-cpp processors) +const nlohmann::json j = rfl::nlohmann::write(src); + +// Deserialize without throwing (errors are returned via rfl::Result) +const rfl::Result res = + rfl::nlohmann::read(j); + +// Preserve struct field order with nlohmann::ordered_json +const nlohmann::ordered_json oj = rfl::nlohmann::write(src); +``` + +Note that `nlohmann::ordered_json` uses `nlohmann::ordered_map` (backed by a contiguous sequence), so key lookup and insertion are $O(N)$ per field rather than $O(\log N)$ as with `nlohmann::json`. + +## Opt-in `nlohmann::adl_serializer` + +`` always declares `rfl::nlohmann::enable_adl_serializer`. When C++ exceptions are enabled and `JSON_NOEXCEPTION` is not defined, it also defines the opt-in `nlohmann::adl_serializer` specialization. Specialize `rfl::nlohmann::enable_adl_serializer` to `std::true_type` to opt specific types into `nlohmann::json` conversions without affecting any other types: + +```cpp +struct User { + const std::string name; + rfl::Validator> age; +}; + +template <> +struct rfl::nlohmann::enable_adl_serializer : std::true_type {}; + +nlohmann::json j = User{.name = "Grace", .age = 42}; +User u = j.get(); // throws nlohmann::json::other_error (a nlohmann::json::exception) on error +``` + +Because `adl_serializer` uses the returning 1-argument `from_json` overload, `j.get()` works cleanly with `rfl::Validator`, `const` fields, and non-default-constructible structs. + +## Dynamic `nlohmann::json` fields in reflected structs + +`nlohmann::json` and `nlohmann::ordered_json` (and other `nlohmann::basic_json` specializations) can be embedded directly as fields inside reflected structs and serialized across `rfl::nlohmann`, `rfl::json`, `rfl::generic`, and other formats: + +```cpp +struct Event { + std::string kind; + nlohmann::json payload; + nlohmann::ordered_json metadata; +}; +``` + +- `rfl::Bytestring` and `rfl::Vectorstring` serialize as RFC 4648 Base64 strings and accept either Base64 strings or native `nlohmann::json::binary_t` values on read. +- When writing `nlohmann::basic_json` values containing `binary_t` to other formats, binary formats (CBOR, msgpack, flexbuffers, UBJSON, BSON, etc.) receive native `rfl::Bytestring` values, `rfl::json` Base64-encodes `rfl::Bytestring`, and text/generic formats without `Bytestring` support fall back to Base64 strings. +- Cross-`basic_json` conversions (`nlohmann::json` ↔ `nlohmann::ordered_json`) preserve exact integer signedness (`uint64_t`/`int64_t`), booleans, strings, binary payloads, and key order. +- Mirroring `rfl::Generic` in `rfl/xml/Parser.hpp`, writing `nlohmann::basic_json` fields to XML is supported, while reading XML into `nlohmann::basic_json` is rejected at compile time because XML is untyped without a schema. diff --git a/include/rfl/nlohmann.hpp b/include/rfl/nlohmann.hpp new file mode 100644 index 000000000..d8d5a1a0f --- /dev/null +++ b/include/rfl/nlohmann.hpp @@ -0,0 +1,12 @@ +#ifndef RFL_NLOHMANN_HPP_ +#define RFL_NLOHMANN_HPP_ + +#include "../rfl.hpp" +#include "nlohmann/Parser.hpp" +#include "nlohmann/Reader.hpp" +#include "nlohmann/Writer.hpp" +#include "nlohmann/adl_serializer.hpp" +#include "nlohmann/read.hpp" +#include "nlohmann/write.hpp" + +#endif diff --git a/include/rfl/nlohmann/Parser.hpp b/include/rfl/nlohmann/Parser.hpp new file mode 100644 index 000000000..099d14a8c --- /dev/null +++ b/include/rfl/nlohmann/Parser.hpp @@ -0,0 +1,477 @@ +#ifndef RFL_NLOHMANN_PARSER_HPP_ +#define RFL_NLOHMANN_PARSER_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../Bytestring.hpp" +#include "../Generic.hpp" +#include "../Result.hpp" +#include "../always_false.hpp" +#include "../internal/base64.hpp" +#include "../parsing/AreReaderAndWriter.hpp" +#include "../parsing/Parent.hpp" +#include "../parsing/Parser.hpp" +#include "../parsing/schema/Type.hpp" +#include "Reader.hpp" +#include "Writer.hpp" + +namespace rfl::nlohmann { + +template +using Parser = + parsing::Parser, Writer, T, ProcessorsType>; + +namespace internal { + +template +void reserve_array(BasicJson& _arr, const size_t _size) { + if (_size == 0) return; + if constexpr (requires(typename BasicJson::array_t& a, size_t n) { + a.reserve(n); + }) { + if (auto* vec = _arr.template get_ptr()) + vec->reserve(_size); + } +} + +template +void reserve_object(BasicJson& _obj, const size_t _size) { + if (_size == 0) return; + if constexpr (requires(typename BasicJson::object_t& o, size_t n) { + o.reserve(n); + }) { + if (auto* map = _obj.template get_ptr()) + map->reserve(_size); + } +} + +template +void emplace_field(BasicJson& _obj, typename BasicJson::string_t _key, + BasicJson&& _val) { + if constexpr (requires(typename BasicJson::object_t& o, + typename BasicJson::string_t k, BasicJson v) { + o.insert_or_assign(std::move(k), std::move(v)); + }) { + if (auto* map = _obj.template get_ptr()) { + map->insert_or_assign(std::move(_key), std::move(_val)); + return; + } + } + _obj[std::move(_key)] = std::move(_val); +} + +/// Lossless conversion between distinct nlohmann::basic_json instantiations +/// (e.g., nlohmann::json <-> nlohmann::ordered_json). +template +TargetBasicJson convert_basic_json(const SourceBasicJson& _src) { + if (_src.is_null()) { + return TargetBasicJson(nullptr); + } + if (const auto* b = _src.template get_ptr< + const typename SourceBasicJson::boolean_t*>()) { + return TargetBasicJson( + static_cast(*b)); + } + if (const auto* u = _src.template get_ptr< + const typename SourceBasicJson::number_unsigned_t*>()) { + return TargetBasicJson( + static_cast(*u)); + } + if (const auto* i = _src.template get_ptr< + const typename SourceBasicJson::number_integer_t*>()) { + return TargetBasicJson( + static_cast(*i)); + } + if (const auto* f = _src.template get_ptr< + const typename SourceBasicJson::number_float_t*>()) { + return TargetBasicJson( + static_cast(*f)); + } + if (const auto* s = _src.template get_ptr< + const typename SourceBasicJson::string_t*>()) { + return TargetBasicJson( + typename TargetBasicJson::string_t(s->data(), s->size())); + } + if (_src.is_binary()) { + const auto& src_bin = _src.get_binary(); + typename TargetBasicJson::binary_t::container_type dst_bytes; + if constexpr (requires { dst_bytes.reserve(src_bin.size()); }) { + dst_bytes.reserve(src_bin.size()); + } + using DstByte = typename TargetBasicJson::binary_t::value_type; + for (const auto b : src_bin) { + dst_bytes.push_back(static_cast(b)); + } + if (src_bin.has_subtype()) { + return TargetBasicJson::binary(std::move(dst_bytes), src_bin.subtype()); + } + return TargetBasicJson::binary(std::move(dst_bytes)); + } + if (_src.is_array()) { + auto arr = TargetBasicJson::array(); + reserve_array(arr, _src.size()); + for (const auto& elem : _src) { + arr.push_back(convert_basic_json(elem)); + } + return arr; + } + if (_src.is_object()) { + auto obj = TargetBasicJson::object(); + reserve_object(obj, _src.size()); + for (auto it = _src.begin(); it != _src.end(); ++it) { + emplace_field(obj, + typename TargetBasicJson::string_t(it.key().data(), + it.key().size()), + convert_basic_json(it.value())); + } + return obj; + } + return TargetBasicJson(nullptr); +} + +// Detects rfl::json::Reader via dependent ADL so compiles +// without or yyjson.h. +template +concept IsYYJSONReader = requires(const typename R::InputVarType& v) { + { yyjson_is_null(v.val_) } -> std::convertible_to; + { yyjson_is_uint(v.val_) } -> std::convertible_to; + { yyjson_get_uint(v.val_) } -> std::convertible_to; + { yyjson_get_sint(v.val_) } -> std::convertible_to; +}; + +// Detects rfl::xml::Reader without including or pugixml. +template +concept IsXMLReader = requires(const typename R::InputVarType& v) { + v.node_or_attribute_; +}; + +// Detects writers whose add_value_to_* rejects rfl::Bytestring via +// static_assert instead of encoding or storing bytes natively. +template +concept IsNonBytestringWriter = + std::is_same_v::OutputVarType, + rfl::Generic> || + requires { typename std::remove_cvref_t::YAMLVar; } || + requires { typename std::remove_cvref_t::XMLOutputVar; } || + requires { typename std::remove_cvref_t::TOMLVar; } || + requires { typename std::remove_cvref_t::BoostOutputVar; } || + requires(const typename std::remove_cvref_t::OutputObjectType& o) { + o.prefix; + o.fields; + }; + +template +Result read_from_yyjson(ValPtr _val) { + if (!_val || yyjson_is_null(_val)) return BasicJson(nullptr); + if (yyjson_is_bool(_val)) + return BasicJson( + static_cast(yyjson_get_bool(_val))); + if (yyjson_is_uint(_val)) + return BasicJson(static_cast( + yyjson_get_uint(_val))); + if (yyjson_is_sint(_val)) + return BasicJson(static_cast( + yyjson_get_sint(_val))); + if (yyjson_is_real(_val)) + return BasicJson(static_cast( + yyjson_get_real(_val))); + if (yyjson_is_str(_val)) + return BasicJson(typename BasicJson::string_t(yyjson_get_str(_val), + yyjson_get_len(_val))); + if (yyjson_is_arr(_val)) { + auto arr = BasicJson::array(); + reserve_array(arr, yyjson_arr_size(_val)); + auto iter = yyjson_arr_iter_with(_val); + while (auto* elem = yyjson_arr_iter_next(&iter)) { + auto res = read_from_yyjson(elem); + if (!res) return error(std::move(res.error())); + arr.push_back(std::move(*res)); + } + return arr; + } + if (yyjson_is_obj(_val)) { + auto obj = BasicJson::object(); + reserve_object(obj, yyjson_obj_size(_val)); + auto iter = yyjson_obj_iter_with(_val); + while (auto* key = yyjson_obj_iter_next(&iter)) { + auto res = read_from_yyjson(yyjson_obj_iter_get_val(key)); + if (!res) return error(std::move(res.error())); + emplace_field( + obj, + typename BasicJson::string_t(yyjson_get_str(key), yyjson_get_len(key)), + std::move(*res)); + } + return obj; + } + return error("Unsupported yyjson value type."); +} + +template +Result read_from_generic_reader( + const R& _r, const typename R::InputVarType& _var) { + if (_r.is_empty(_var)) return BasicJson(nullptr); + if (auto obj_res = _r.to_object(_var)) { + auto obj = BasicJson::object(); + std::optional first_err; + struct ObjReader { + const R& r_; + BasicJson& obj_; + std::optional& err_; + void read(const std::string_view _key, + const typename R::InputVarType& _v) const { + if (err_) return; + auto val_res = read_from_generic_reader(r_, _v); + if (!val_res) { + err_ = std::move(val_res.error()); + return; + } + emplace_field(obj_, typename BasicJson::string_t(_key), + std::move(*val_res)); + } + }; + if (auto err = _r.read_object(ObjReader{_r, obj, first_err}, *obj_res)) + return error(std::move(*err)); + if (first_err) return error(std::move(*first_err)); + return obj; + } + if (auto arr_res = _r.to_array(_var)) { + auto arr = BasicJson::array(); + struct ArrReader { + const R& r_; + BasicJson& arr_; + std::optional read(const typename R::InputVarType& _v) const { + auto val_res = read_from_generic_reader(r_, _v); + if (!val_res) return std::move(val_res.error()); + arr_.push_back(std::move(*val_res)); + return std::nullopt; + } + }; + if (auto err = _r.read_array(ArrReader{_r, arr}, *arr_res)) + return error(std::move(*err)); + return arr; + } + // Preserve explicitly quoted YAML strings (Tag() == "!") without coercing + // them into booleans or numbers. + if constexpr (requires(const typename R::InputVarType& v) { + { v.node_.Tag() == "!" } -> std::convertible_to; + }) { + if (_var.node_.Tag() == "!") { + if (auto s = _r.template to_basic_type(_var)) + return BasicJson(typename BasicJson::string_t(std::move(*s))); + } + } + if (auto b = _r.template to_basic_type(_var)) + return BasicJson(static_cast(*b)); + // Preserve native unsigned 64-bit integers in readers that distinguish them + // (jsoncons CBOR/UBJSON, msgpack-c, flexbuffers) so values > INT64_MAX do + // not wrap to negative signed integers. + if constexpr (requires(const typename R::InputVarType& v) { + { v.val_->is_uint64() } -> std::convertible_to; + }) { + if (_var.val_ && _var.val_->is_uint64()) { + if (auto u = _r.template to_basic_type(_var)) + return BasicJson( + static_cast(*u)); + } + } + if constexpr (requires(const typename R::InputVarType& v) { + { v.type } -> std::convertible_to; + { v.via.u64 } -> std::convertible_to; + { v.via.i64 } -> std::convertible_to; + { v.via.boolean } -> std::convertible_to; + }) { + // MSGPACK_OBJECT_POSITIVE_INTEGER == 0x02 in msgpack-c's ABI. + if (static_cast(_var.type) == 0x02) { + return BasicJson( + static_cast(_var.via.u64)); + } + } + if constexpr (requires(const typename R::InputVarType& v) { + { v.IsUInt() } -> std::convertible_to; + }) { + if (_var.IsUInt()) { + if constexpr (requires(const typename R::InputVarType& v) { + { v.AsUInt64() } -> std::convertible_to; + }) { + return BasicJson(static_cast( + _var.AsUInt64())); + } else if (auto u = _r.template to_basic_type(_var)) { + return BasicJson( + static_cast(*u)); + } + } + } + if (auto i = _r.template to_basic_type(_var)) { + return BasicJson(static_cast(*i)); + } + if (auto u = _r.template to_basic_type(_var)) { + return BasicJson(static_cast(*u)); + } + if (auto d = _r.template to_basic_type(_var)) + return BasicJson(static_cast(*d)); + if (auto s = _r.template to_basic_type(_var)) + return BasicJson(typename BasicJson::string_t(std::move(*s))); + return error("Could not parse value into nlohmann::basic_json."); +} + +template +void write_to_writer(const W& _w, const BasicJson& _val, const P& _parent) { + using ParentType = parsing::Parent; + if (_val.is_null()) { + ParentType::add_null(_w, _parent); + } else if (const auto* b = _val.template get_ptr< + const typename BasicJson::boolean_t*>()) { + ParentType::add_value(_w, static_cast(*b), _parent); + } else if (const auto* u = _val.template get_ptr< + const typename BasicJson::number_unsigned_t*>()) { + ParentType::add_value(_w, static_cast(*u), _parent); + } else if (const auto* i = _val.template get_ptr< + const typename BasicJson::number_integer_t*>()) { + ParentType::add_value(_w, static_cast(*i), _parent); + } else if (const auto* f = _val.template get_ptr< + const typename BasicJson::number_float_t*>()) { + ParentType::add_value(_w, static_cast(*f), _parent); + } else if (const auto* s = + _val.template get_ptr()) { + if constexpr (std::is_same_v) + ParentType::add_value(_w, *s, _parent); + else + ParentType::add_value(_w, std::string(*s), _parent); + } else if (_val.is_binary()) { + const auto& bin = _val.get_binary(); + Bytestring bytes; + bytes.reserve(bin.size()); + for (const auto b : bin) { + bytes.push_back(static_cast(b)); + } + if constexpr (IsNonBytestringWriter) { + ParentType::add_value(_w, ::rfl::internal::encode_base64(bytes), _parent); + } else { + ParentType::add_value(_w, bytes, _parent); + } + } else if (_val.is_array()) { + auto arr = ParentType::add_array(_w, _val.size(), _parent); + const auto elem_parent = typename ParentType::Array{&arr}; + for (const auto& elem : _val) write_to_writer(_w, elem, elem_parent); + _w.end_array(&arr); + } else if (_val.is_object()) { + auto obj = ParentType::add_object(_w, _val.size(), _parent); + for (auto it = _val.begin(); it != _val.end(); ++it) { + const auto field_parent = + typename ParentType::Object{std::string_view(it.key()), &obj}; + write_to_writer(_w, it.value(), field_parent); + } + _w.end_object(&obj); + } else { + ParentType::add_null(_w, _parent); + } +} + +} // namespace internal +} // namespace rfl::nlohmann + +namespace rfl::parsing { + +/// Parser specialization enabling nlohmann::basic_json as a field type inside +/// reflected structs across rfl::nlohmann, rfl::json, rfl::generic, etc. +template class ObjectType, + template class ArrayType, + class StringType, class BooleanType, class NumberIntegerType, + class NumberUnsignedType, class NumberFloatType, + template class AllocatorType, + template class JSONSerializer, + class BinaryType, class CustomBaseClass, class ProcessorsType> + requires AreReaderAndWriter< + R, W, + ::nlohmann::basic_json> +struct Parser< + R, W, + ::nlohmann::basic_json, + ProcessorsType> { + using BasicJson = + ::nlohmann::basic_json; + using InputVarType = typename R::InputVarType; + using ParentType = Parent; + + static Result read(const R& _r, const InputVarType& _var) { + if constexpr (std::is_same_v, + rfl::nlohmann::Reader>) { + return _var.val_ ? *_var.val_ : BasicJson(nullptr); + } else if constexpr (rfl::nlohmann::is_nlohmann_reader_v) { + return _var.val_ + ? rfl::nlohmann::internal::convert_basic_json( + *_var.val_) + : BasicJson(nullptr); + } else if constexpr (rfl::nlohmann::internal::IsYYJSONReader) { + return rfl::nlohmann::internal::read_from_yyjson(_var.val_); + } else if constexpr (rfl::nlohmann::internal::IsXMLReader) { + (void)_r; + (void)_var; + static_assert( + rfl::always_false_v, + "XML does not support reading into nlohmann::basic_json."); + return error("XML does not support reading into nlohmann::basic_json."); + } else { + return rfl::nlohmann::internal::read_from_generic_reader(_r, + _var); + } + } + + template + static void write(const W& _w, const BasicJson& _val, const P& _parent) { + using PType = std::remove_cvref_t

; + if constexpr (std::is_same_v, + rfl::nlohmann::Writer>) { + if constexpr (std::is_same_v) + _w.raw_as_root(_val); + else if constexpr (std::is_same_v) + _w.add_raw_to_array(_val, _parent.arr_); + else if constexpr (std::is_same_v) + _w.add_raw_to_object(_parent.name_, _val, _parent.obj_); + else + rfl::nlohmann::internal::write_to_writer(_w, _val, _parent); + } else if constexpr (rfl::nlohmann::is_nlohmann_writer_v) { + using TargetBasicJson = typename std::remove_cvref_t::BasicJsonType; + const auto converted = + rfl::nlohmann::internal::convert_basic_json(_val); + if constexpr (std::is_same_v) + _w.raw_as_root(converted); + else if constexpr (std::is_same_v) + _w.add_raw_to_array(converted, _parent.arr_); + else if constexpr (std::is_same_v) + _w.add_raw_to_object(_parent.name_, converted, _parent.obj_); + else + rfl::nlohmann::internal::write_to_writer(_w, _val, _parent); + } else { + rfl::nlohmann::internal::write_to_writer(_w, _val, _parent); + } + } + + static schema::Type to_schema( + std::map* _definitions) { + return Parser::to_schema(_definitions); + } +}; + +} // namespace rfl::parsing + +#endif diff --git a/include/rfl/nlohmann/Reader.hpp b/include/rfl/nlohmann/Reader.hpp new file mode 100644 index 000000000..be710f4c4 --- /dev/null +++ b/include/rfl/nlohmann/Reader.hpp @@ -0,0 +1,248 @@ +#ifndef RFL_NLOHMANN_READER_HPP_ +#define RFL_NLOHMANN_READER_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../Bytestring.hpp" +#include "../Result.hpp" +#include "../Vectorstring.hpp" +#include "../always_false.hpp" +#include "../internal/base64.hpp" + +static_assert( + (NLOHMANN_JSON_VERSION_MAJOR > 3) || + (NLOHMANN_JSON_VERSION_MAJOR == 3 && + NLOHMANN_JSON_VERSION_MINOR > 11) || + (NLOHMANN_JSON_VERSION_MAJOR == 3 && + NLOHMANN_JSON_VERSION_MINOR == 11 && + NLOHMANN_JSON_VERSION_PATCH >= 3), + "reflect-cpp requires nlohmann/json >= 3.11.3 (11-parameter " + "nlohmann::basic_json template with CustomBaseClass)."); + +namespace rfl::nlohmann { + +template +struct is_basic_json : std::false_type {}; + +template