diff --git a/docs/content/supported_formats/json.md b/docs/content/supported_formats/json.md index e85d91c39..5f20946cd 100644 --- a/docs/content/supported_formats/json.md +++ b/docs/content/supported_formats/json.md @@ -118,3 +118,29 @@ rfl::Result Person::from_json_obj(const JSONVar& _obj) { This will force the compiler to only compile the JSON parsing when the source file is compiled. +## Raw JSON Passthrough (`rfl::json::Raw`) + +Use `rfl::json::Raw` when a struct contains a JSON subtree that you want to +pass through without converting into intermediate C++ types: + +```cpp +struct Envelope { + int id; + rfl::json::Raw payload; +}; + +const auto env = rfl::json::read( + R"({"id":1,"payload":{"nested":[1,2,3]}})").value(); +const auto out = rfl::json::write(env); +``` + +When constructing `rfl::json::Raw` from untrusted input, prefer the validating +factory `rfl::json::Raw::from_string(...)` (which returns `rfl::Result`) +rather than the unchecked `explicit` constructors, because writing emits the +stored JSON text verbatim via `yyjson_mut_rawncpy`. + +On read, `rfl::json::Raw` captures the parsed `yyjson` subtree via +`yyjson_val_write`, which canonicalizes whitespace. Pass `YYJSON_READ_BIGNUM_AS_RAW` +to `rfl::json::read` if integers wider than 64 bits must be preserved verbatim. +`rfl::json::Raw` is supported with `rfl::json` only. + diff --git a/include/rfl/json.hpp b/include/rfl/json.hpp index cac6b0e23..a42bd82fa 100644 --- a/include/rfl/json.hpp +++ b/include/rfl/json.hpp @@ -3,6 +3,7 @@ #include "../rfl.hpp" #include "json/Parser.hpp" +#include "json/Raw.hpp" #include "json/Reader.hpp" #include "json/Writer.hpp" #include "json/load.hpp" diff --git a/include/rfl/json/Raw.hpp b/include/rfl/json/Raw.hpp new file mode 100644 index 000000000..5a5efbac4 --- /dev/null +++ b/include/rfl/json/Raw.hpp @@ -0,0 +1,149 @@ +#ifndef RFL_JSON_RAW_HPP_ +#define RFL_JSON_RAW_HPP_ + +#if __has_include() +#include +#else +#include "../thirdparty/yyjson.h" +#endif + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../Generic.hpp" +#include "../Result.hpp" +#include "../always_false.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::json { + +/// Holds a raw JSON value for passthrough serialization and deserialization +/// without converting into intermediate C++ structures. +/// +/// Note on reading vs. writing: +/// - Writing emits the stored JSON text verbatim via `yyjson_mut_rawncpy` +/// without re-parsing. Use `Raw::from_string()` when constructing from +/// untrusted input so malformed JSON is rejected up front. +/// - Reading captures the parsed yyjson subtree via `yyjson_val_write`, which +/// canonicalizes whitespace. Pass `YYJSON_READ_BIGNUM_AS_RAW` to +/// `rfl::json::read` if you need integers wider than 64 bits preserved +/// verbatim. +class Raw { + public: + Raw() = default; + + explicit Raw(std::string _value) + : value_(_value.empty() ? std::string("null") : std::move(_value)) {} + + explicit Raw(const std::string_view _value) + : value_(_value.empty() ? std::string("null") : std::string(_value)) {} + + explicit Raw(const char* _value) + : value_((_value && _value[0] != '\0') ? std::string(_value) + : std::string("null")) {} + + /// Validates that `_str` contains a single well-formed JSON value and + /// constructs a `Raw` holding `_str` verbatim. + static Result from_string(const std::string_view _str, + const yyjson_read_flag _flag = 0) { + if (_flag & YYJSON_READ_INSITU) { + return error("YYJSON_READ_INSITU is not supported"); + } + yyjson_read_err err{}; + yyjson_doc* doc = yyjson_read_opts(const_cast(_str.data()), + _str.size(), _flag, nullptr, &err); + if (!doc) { + return error("Invalid raw JSON: " + + std::string(err.msg ? err.msg : "parse error")); + } + yyjson_doc_free(doc); + return Raw(_str); + } + + const std::string& str() const noexcept { return value_; } + + const std::string& value() const noexcept { return value_; } + + const char* c_str() const noexcept { return value_.c_str(); } + + bool operator==(const Raw&) const = default; + + static Result from_json_obj(const Reader::YYJSONInputVar& _var) { + if (!_var.val_) { + return error("Cannot construct rfl::json::Raw from null JSON value."); + } + struct FreeDeleter { + void operator()(char* _p) const noexcept { std::free(_p); } + }; + size_t len = 0; + std::unique_ptr buf( + yyjson_val_write(_var.val_, 0, &len)); + if (!buf) { + return error("Could not serialize JSON value into rfl::json::Raw."); + } + return Raw(std::string(buf.get(), len)); + } + + private: + std::string value_{"null"}; +}; + +} // namespace rfl::json + +namespace rfl::parsing { + +template + requires AreReaderAndWriter +struct Parser { + static_assert(always_false_v, + "rfl::json::Raw is only supported with rfl::json."); +}; + +template + requires AreReaderAndWriter +struct Parser { + public: + using InputVarType = typename json::Reader::InputVarType; + using ParentType = Parent; + + static Result read(const json::Reader& _r, + const InputVarType& _var) noexcept { + return _r.template use_custom_constructor(_var); + } + + template + static void write(const json::Writer& _w, const json::Raw& _raw, + const P& _parent) { + using Type = std::remove_cvref_t

; + if constexpr (std::is_same_v) { + _w.add_raw_to_array(_raw.str(), _parent.arr_); + } else if constexpr (std::is_same_v) { + _w.add_raw_to_object(_parent.name_, _raw.str(), _parent.obj_); + } else if constexpr (std::is_same_v) { + _w.raw_as_root(_raw.str()); + } else { + static_assert(always_false_v, "Unsupported parent type."); + } + } + + static schema::Type to_schema( + std::map* _definitions) { + return Parser::to_schema(_definitions); + } +}; + +} // namespace rfl::parsing + +#endif diff --git a/include/rfl/json/Writer.hpp b/include/rfl/json/Writer.hpp index 7530ea98c..9748279a5 100644 --- a/include/rfl/json/Writer.hpp +++ b/include/rfl/json/Writer.hpp @@ -81,6 +81,12 @@ class RFL_API Writer { /// @return An output variable representing null OutputVarType null_as_root() const noexcept; + /// Creates a raw JSON value as the root element of the output. + /// Emits null if _str is empty. + /// @param _str The raw JSON text to write + /// @return An output variable representing the raw JSON value + OutputVarType raw_as_root(const std::string_view& _str) const noexcept; + /// Creates a value as the root element of the output. /// Supports basic types like strings, numbers, and booleans. /// @tparam T The type of the value to serialize @@ -177,6 +183,26 @@ class RFL_API Writer { OutputVarType add_null_to_object(const std::string_view& _name, OutputObjectType* _parent) const; + /// Adds a raw JSON value to a parent array. + /// Emits null if _str is empty. + /// @param _str The raw JSON text to add + /// @param _parent Pointer to the parent array to add to + /// @return An output variable representing the raw JSON value + /// @throws std::runtime_error if the value cannot be added + OutputVarType add_raw_to_array(const std::string_view& _str, + OutputArrayType* _parent) const; + + /// Adds a raw JSON value to a parent object with the specified field name. + /// Emits null if _str is empty. + /// @param _name The name of the field in the parent object + /// @param _str The raw JSON text to add + /// @param _parent Pointer to the parent object to add to + /// @return An output variable representing the raw JSON value + /// @throws std::runtime_error if the field cannot be added + OutputVarType add_raw_to_object(const std::string_view& _name, + const std::string_view& _str, + OutputObjectType* _parent) const; + /// Finalizes a JSON array after all elements have been added. /// This is a no-op for yyjson as arrays don't need explicit finalization. /// @param Pointer to the array (unused) diff --git a/src/rfl/json/Writer.cpp b/src/rfl/json/Writer.cpp index fbb5e3234..1fa3ebd0d 100644 --- a/src/rfl/json/Writer.cpp +++ b/src/rfl/json/Writer.cpp @@ -50,6 +50,15 @@ Writer::OutputVarType Writer::null_as_root() const noexcept { return OutputVarType(null); } +Writer::OutputVarType Writer::raw_as_root( + const std::string_view& _str) const noexcept { + const auto val = _str.empty() + ? yyjson_mut_null(doc()) + : yyjson_mut_rawncpy(doc(), _str.data(), _str.size()); + yyjson_mut_doc_set_root(doc(), val); + return OutputVarType(val); +} + Writer::OutputArrayType Writer::add_array_to_array( const size_t, OutputArrayType* _parent) const { const auto arr = yyjson_mut_arr(doc()); @@ -118,6 +127,34 @@ Writer::OutputVarType Writer::add_null_to_object( return OutputVarType(null); } +Writer::OutputVarType Writer::add_raw_to_array( + const std::string_view& _str, OutputArrayType* _parent) const { + const auto val = _str.empty() + ? yyjson_mut_null(doc()) + : yyjson_mut_rawncpy(doc(), _str.data(), _str.size()); + const bool ok = yyjson_mut_arr_add_val(_parent->val_, val); + if (!ok) { + throw std::runtime_error("Adding raw JSON to an array failed."); + } + return OutputVarType(val); +} + +Writer::OutputVarType Writer::add_raw_to_object( + const std::string_view& _name, const std::string_view& _str, + OutputObjectType* _parent) const { + const auto val = _str.empty() + ? yyjson_mut_null(doc()) + : yyjson_mut_rawncpy(doc(), _str.data(), _str.size()); + const bool ok = yyjson_mut_obj_add( + _parent->val_, yyjson_mut_strncpy(doc(), _name.data(), _name.size()), + val); + if (!ok) { + throw std::runtime_error("Could not add field '" + std::string(_name) + + "' to object."); + } + return OutputVarType(val); +} + void Writer::end_array(OutputArrayType*) const noexcept {} void Writer::end_object(OutputObjectType*) const noexcept {} diff --git a/tests/json/test_raw.cpp b/tests/json/test_raw.cpp new file mode 100644 index 000000000..bdff8d7aa --- /dev/null +++ b/tests/json/test_raw.cpp @@ -0,0 +1,177 @@ +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace test_raw { + +struct Envelope { + std::string type; + rfl::json::Raw payload; +}; + +struct OptionalEnvelope { + int id; + std::optional payload; +}; + +TEST(json, test_raw_constructors_and_accessors) { + const rfl::json::Raw def; + EXPECT_EQ(def.str(), "null"); + EXPECT_EQ(def.value(), "null"); + EXPECT_STREQ(def.c_str(), "null"); + + static_assert(!std::is_convertible_v); + static_assert(!std::is_convertible_v); + static_assert(!std::is_convertible_v); + + const rfl::json::Raw from_cstr(R"({"a":1})"); + const rfl::json::Raw from_sv(std::string_view{R"({"a":1})"}); + const rfl::json::Raw from_str(std::string{R"({"a":1})"}); + EXPECT_EQ(from_cstr, from_sv); + EXPECT_EQ(from_sv, from_str); + EXPECT_NE(from_cstr, def); + + const rfl::json::Raw from_null(static_cast(nullptr)); + EXPECT_EQ(from_null, def); + + const rfl::json::Raw empty_raw(""); + EXPECT_EQ(empty_raw.str(), "null"); + EXPECT_EQ(empty_raw, def); + EXPECT_EQ(rfl::json::write(empty_raw), "null"); + EXPECT_EQ(rfl::json::write(def), "null"); + EXPECT_EQ(rfl::json::write(std::vector{empty_raw, def}), + "[null,null]"); + EXPECT_EQ(rfl::json::write(Envelope{.type = "empty", .payload = empty_raw}), + R"({"type":"empty","payload":null})"); + + // Validating factory rejects malformed JSON and preserves valid JSON verbatim. + const auto valid = rfl::json::Raw::from_string(R"({ "k" : [1, 2] })"); + ASSERT_TRUE(valid.has_value()); + EXPECT_EQ(valid->str(), R"({ "k" : [1, 2] })"); + EXPECT_FALSE(rfl::json::Raw::from_string("").has_value()); + EXPECT_FALSE(rfl::json::Raw::from_string("{not json").has_value()); + EXPECT_FALSE(rfl::json::Raw::from_string("1 2").has_value()); +} + +TEST(json, test_raw_root_values) { + for (const char* sample : + {R"({"a":1,"b":[true,false,null,"hi"]})", R"([1,2,3])", R"("hello")", + "42", "3.5", "true", "false", "null"}) { + write_and_read(rfl::json::Raw(sample), sample); + } + const auto bad = rfl::json::Raw::from_json_obj(rfl::json::Reader::YYJSONInputVar{}); + EXPECT_FALSE(bad.has_value()); +} + +TEST(json, test_raw_struct_field) { + const Envelope env{ + .type = "event", + .payload = rfl::json::Raw(R"({"nested":{"k":[1,"two",true,null]}})")}; + write_and_read( + env, + R"({"type":"event","payload":{"nested":{"k":[1,"two",true,null]}}})"); + + const auto null_field = + rfl::json::read(R"({"type":"nil","payload":null})"); + ASSERT_TRUE(null_field.has_value()); + EXPECT_EQ(null_field->payload, rfl::json::Raw("null")); + + const auto missing = rfl::json::read(R"({"type":"missing"})"); + EXPECT_FALSE(missing.has_value()); +} + +TEST(json, test_raw_optional_field) { + const auto missing = rfl::json::read(R"({"id":1})"); + ASSERT_TRUE(missing.has_value()); + EXPECT_FALSE(missing->payload.has_value()); + EXPECT_EQ(rfl::json::write(*missing), R"({"id":1})"); + + const auto explicit_null = + rfl::json::read(R"({"id":2,"payload":null})"); + ASSERT_TRUE(explicit_null.has_value()); + EXPECT_FALSE(explicit_null->payload.has_value()); + + const auto present = + rfl::json::read(R"({"id":3,"payload":{"x":[1,2]}})"); + ASSERT_TRUE(present.has_value()); + ASSERT_TRUE(present->payload.has_value()); + EXPECT_EQ(*present->payload, rfl::json::Raw(R"({"x":[1,2]})")); + EXPECT_EQ(rfl::json::write(*present), R"({"id":3,"payload":{"x":[1,2]}})"); +} + +TEST(json, test_raw_containers) { + const std::vector vec{ + rfl::json::Raw("1"), + rfl::json::Raw(R"("two")"), + rfl::json::Raw(R"({"three":3})"), + rfl::json::Raw("[4,5]"), + rfl::json::Raw("true"), + rfl::json::Raw("null"), + }; + write_and_read(vec, R"([1,"two",{"three":3},[4,5],true,null])"); + + const std::map mp{ + {"a", rfl::json::Raw("123")}, + {"b", rfl::json::Raw(R"({"nested":true})")}, + {"c", rfl::json::Raw(R"(["x","y"])")}, + }; + write_and_read(mp, R"({"a":123,"b":{"nested":true},"c":["x","y"]})"); +} + +TEST(json, test_raw_passthrough_and_pretty) { + // Non-canonical whitespace and key order must pass through untouched on write. + const std::string unformatted = R"({ "z" : 2, "a" : [ 1, 2 ] })"; + const Envelope env{.type = "pass", .payload = rfl::json::Raw(unformatted)}; + EXPECT_EQ(rfl::json::write(env), + R"({"type":"pass","payload":)" + unformatted + "}"); + EXPECT_EQ(rfl::json::write(rfl::json::Raw(unformatted)), unformatted); + + const auto pretty_out = rfl::json::write(env, rfl::json::pretty); + EXPECT_NE(pretty_out.find('\n'), std::string::npos); + EXPECT_NE(pretty_out.find(unformatted), std::string::npos); + + const auto reparsed = rfl::json::read(pretty_out); + ASSERT_TRUE(reparsed.has_value()); + EXPECT_EQ(reparsed->type, "pass"); + EXPECT_EQ(reparsed->payload, rfl::json::Raw(R"({"z":2,"a":[1,2]})")); +} + +TEST(json, test_raw_to_schema) { + const auto schema = rfl::json::to_schema(); + EXPECT_NE(schema.find("rfl__Generic"), std::string::npos); + EXPECT_NE(schema.find(R"("required":["id"])"), std::string::npos); + + const auto req_schema = rfl::json::to_schema(); + EXPECT_NE(req_schema.find("rfl__Generic"), std::string::npos); + EXPECT_NE(req_schema.find(R"("required":["type","payload"])"), + std::string::npos); +} + +TEST(json, test_raw_bignum_and_nested_reparse) { + // With YYJSON_READ_BIGNUM_AS_RAW, integers wider than 64 bits survive verbatim. + const std::string big = "1234567890123456789012345678901234567890"; + const auto big_env = rfl::json::read( + R"({"type":"bignum","payload":{"amount":)" + big + "}}", + YYJSON_READ_BIGNUM_AS_RAW); + ASSERT_TRUE(big_env.has_value()); + EXPECT_EQ(big_env->payload.str(), R"({"amount":)" + big + "}"); + + // Nested Raw inside a Raw payload can be re-parsed into a typed struct. + const auto outer = rfl::json::read( + R"({"type":"outer","payload":{"type":"inner","payload":[1,2,3]}})"); + ASSERT_TRUE(outer.has_value()); + const auto inner = rfl::json::read(outer->payload.str()); + ASSERT_TRUE(inner.has_value()); + EXPECT_EQ(inner->type, "inner"); + EXPECT_EQ(inner->payload.str(), "[1,2,3]"); +} + +} // namespace test_raw