Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions docs/content/supported_formats/json.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,3 +118,29 @@ rfl::Result<Person> 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<Envelope>(
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<rfl::json::Raw>`)
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.

1 change: 1 addition & 0 deletions include/rfl/json.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
149 changes: 149 additions & 0 deletions include/rfl/json/Raw.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
#ifndef RFL_JSON_RAW_HPP_
#define RFL_JSON_RAW_HPP_

#if __has_include(<yyjson.h>)
#include <yyjson.h>
#else
#include "../thirdparty/yyjson.h"
#endif

#include <cstddef>
#include <cstdlib>
#include <map>
#include <memory>
#include <string>
#include <string_view>
#include <type_traits>
#include <utility>

#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<Raw> 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<char*>(_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<Raw> 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<char, FreeDeleter> 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 <class R, class W, class ProcessorsType>
requires AreReaderAndWriter<R, W, json::Raw>
struct Parser<R, W, json::Raw, ProcessorsType> {
static_assert(always_false_v<R>,
"rfl::json::Raw is only supported with rfl::json.");
};

template <class ProcessorsType>
requires AreReaderAndWriter<json::Reader, json::Writer, json::Raw>
struct Parser<json::Reader, json::Writer, json::Raw, ProcessorsType> {
public:
using InputVarType = typename json::Reader::InputVarType;
using ParentType = Parent<json::Writer>;

static Result<json::Raw> read(const json::Reader& _r,
const InputVarType& _var) noexcept {
return _r.template use_custom_constructor<json::Raw>(_var);
}

template <class P>
static void write(const json::Writer& _w, const json::Raw& _raw,
const P& _parent) {
using Type = std::remove_cvref_t<P>;
if constexpr (std::is_same_v<Type, typename ParentType::Array>) {
_w.add_raw_to_array(_raw.str(), _parent.arr_);
} else if constexpr (std::is_same_v<Type, typename ParentType::Object>) {
_w.add_raw_to_object(_parent.name_, _raw.str(), _parent.obj_);
} else if constexpr (std::is_same_v<Type, typename ParentType::Root>) {
_w.raw_as_root(_raw.str());
} else {
static_assert(always_false_v<Type>, "Unsupported parent type.");
}
}

static schema::Type to_schema(
std::map<std::string, schema::Type>* _definitions) {
return Parser<json::Reader, json::Writer, Generic,
ProcessorsType>::to_schema(_definitions);
}
};

} // namespace rfl::parsing

#endif
26 changes: 26 additions & 0 deletions include/rfl/json/Writer.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
37 changes: 37 additions & 0 deletions src/rfl/json/Writer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down Expand Up @@ -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 {}
Expand Down
Loading