Added support for Apache Avro, and thus for schemaful formats (#303)

This commit is contained in:
Dr. Patrick Urbanke (劉自成)
2024-12-22 14:53:25 +01:00
committed by GitHub
parent a1920a1e30
commit e46835287f
114 changed files with 4750 additions and 261 deletions
+15
View File
@@ -0,0 +1,15 @@
#ifndef RFL_AVRO_HPP_
#define RFL_AVRO_HPP_
#include "../rfl.hpp"
#include "avro/Parser.hpp"
#include "avro/Reader.hpp"
#include "avro/Schema.hpp"
#include "avro/Writer.hpp"
#include "avro/load.hpp"
#include "avro/read.hpp"
#include "avro/save.hpp"
#include "avro/to_schema.hpp"
#include "avro/write.hpp"
#endif
+111
View File
@@ -0,0 +1,111 @@
#ifndef RFL_AVRO_PARSER_HPP_
#define RFL_AVRO_PARSER_HPP_
#include "../Generic.hpp"
#include "../Tuple.hpp"
#include "../always_false.hpp"
#include "../parsing/Parser.hpp"
#include "Reader.hpp"
#include "Writer.hpp"
namespace rfl {
namespace parsing {
/// AVRO requires us to explicitly set all fields. Because
/// of that, we require all of the fields and then set them to nullptr, if
/// necessary.
template <class ProcessorsType, class... FieldTypes>
requires AreReaderAndWriter<avro::Reader, avro::Writer,
NamedTuple<FieldTypes...>>
struct Parser<avro::Reader, avro::Writer, NamedTuple<FieldTypes...>,
ProcessorsType>
: public NamedTupleParser<
avro::Reader, avro::Writer,
/*_ignore_empty_containers=*/false,
/*_all_required=*/true,
/*_no_field_names=*/ProcessorsType::no_field_names_, ProcessorsType,
FieldTypes...> {};
template <class ProcessorsType, class... Ts>
requires AreReaderAndWriter<avro::Reader, avro::Writer, rfl::Tuple<Ts...>>
struct Parser<avro::Reader, avro::Writer, rfl::Tuple<Ts...>, ProcessorsType>
: public TupleParser<avro::Reader, avro::Writer,
/*_ignore_empty_containers=*/false,
/*_all_required=*/true, ProcessorsType,
rfl::Tuple<Ts...>> {};
template <class ProcessorsType, class... Ts>
requires AreReaderAndWriter<avro::Reader, avro::Writer, std::tuple<Ts...>>
struct Parser<avro::Reader, avro::Writer, std::tuple<Ts...>, ProcessorsType>
: public TupleParser<avro::Reader, avro::Writer,
/*_ignore_empty_containers=*/false,
/*_all_required=*/true, ProcessorsType,
std::tuple<Ts...>> {};
template <class ProcessorsType>
requires AreReaderAndWriter<avro::Reader, avro::Writer, Generic>
struct Parser<avro::Reader, avro::Writer, Generic, ProcessorsType> {
template <class T>
static Result<Generic> read(const avro::Reader&, const T&) noexcept {
static_assert(always_false_v<T>, "Generics are unsupported in Avro.");
return Error("Unsupported");
}
template <class P>
static void write(const avro::Writer&, const Generic&, const P&) noexcept {
static_assert(always_false_v<P>, "Generics are unsupported in Avro.");
}
template <class T>
static schema::Type to_schema(T*) {
static_assert(always_false_v<T>, "Generics are unsupported in Avro.");
return schema::Type{};
}
};
template <class T, bool _skip_serialization, bool _skip_deserialization,
class ProcessorsType>
requires AreReaderAndWriter<
avro::Reader, avro::Writer,
internal::Skip<T, _skip_serialization, _skip_deserialization>>
struct Parser<avro::Reader, avro::Writer,
internal::Skip<T, _skip_serialization, _skip_deserialization>,
ProcessorsType> {
using R = avro::Reader;
using W = avro::Writer;
template <class U>
static Result<internal::Skip<T, _skip_serialization, _skip_deserialization>>
read(const R&, const U&) noexcept {
static_assert(always_false_v<T>, "rfl::Skip is unsupported in Avro.");
return Error("Unsupported");
}
template <class P>
static void write(const W& _w,
const internal::Skip<T, _skip_serialization,
_skip_deserialization>& _skip,
const P& _parent) noexcept {
static_assert(always_false_v<P>, "rfl::Skip is unsupported in Avro.");
}
template <class U>
static schema::Type to_schema(U* _definitions) {
static_assert(always_false_v<U>, "rfl::Skip is unsupported in Avro.");
return schema::Type{};
}
};
} // namespace parsing
} // namespace rfl
namespace rfl {
namespace avro {
template <class T, class ProcessorsType>
using Parser = parsing::Parser<Reader, Writer, T, ProcessorsType>;
}
} // namespace rfl
#endif
+215
View File
@@ -0,0 +1,215 @@
#ifndef RFL_AVRO_READER_HPP_
#define RFL_AVRO_READER_HPP_
#include <avro.h>
#include <cstddef>
#include <exception>
#include <string>
#include <string_view>
#include <type_traits>
#include <vector>
#include "../Bytestring.hpp"
#include "../Result.hpp"
#include "../always_false.hpp"
#include "../internal/is_literal.hpp"
namespace rfl::avro {
struct Reader {
struct AVROInputArray {
const avro_value_t* val_;
};
struct AVROInputObject {
const avro_value_t* val_;
};
struct AVROInputMap {
const avro_value_t* val_;
};
struct AVROInputUnion {
const avro_value_t* val_;
};
struct AVROInputVar {
const avro_value_t* val_;
};
using InputArrayType = AVROInputArray;
using InputObjectType = AVROInputObject;
using InputMapType = AVROInputMap;
using InputUnionType = AVROInputUnion;
using InputVarType = AVROInputVar;
template <class T>
static constexpr bool has_custom_constructor =
(requires(InputVarType var) { T::from_avro_obj(var); });
bool is_empty(const InputVarType& _var) const noexcept;
template <class T>
rfl::Result<T> to_basic_type(const InputVarType& _var) const noexcept {
const auto type = avro_value_get_type(_var.val_);
if constexpr (std::is_same<std::remove_cvref_t<T>, std::string>()) {
const char* c_str = nullptr;
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.");
}
if (size == 0) {
return std::string("");
}
return std::string(c_str, size - 1);
} else if constexpr (std::is_same<std::remove_cvref_t<T>,
rfl::Bytestring>()) {
const void* ptr = nullptr;
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 rfl::Bytestring(static_cast<const std::byte*>(ptr), size - 1);
} else if constexpr (std::is_same<std::remove_cvref_t<T>, bool>()) {
if (type != AVRO_BOOLEAN) {
return rfl::Error("Could not cast to boolean.");
}
int result = 0;
avro_value_get_boolean(_var.val_, &result);
return (result != 0);
} else if constexpr (std::is_floating_point<std::remove_cvref_t<T>>() ||
std::is_integral<std::remove_cvref_t<T>>()) {
if (type == AVRO_DOUBLE) {
double result = 0.0;
const auto err = avro_value_get_double(_var.val_, &result);
if (err) {
return Error("Could not cast to double.");
}
return static_cast<T>(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 static_cast<T>(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 static_cast<T>(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 static_cast<T>(result);
}
return rfl::Error(
"Could not cast to numeric value. The type must be integral, float "
"or double.");
} else if constexpr (internal::is_literal_v<T>) {
int value = 0;
const auto err = avro_value_get_enum(_var.val_, &value);
if (err) {
return Error("Could not cast to enum.");
}
return std::remove_cvref_t<T>::from_value(
static_cast<typename std::remove_cvref_t<T>::ValueType>(value));
} else {
static_assert(rfl::always_false_v<T>, "Unsupported type.");
}
}
rfl::Result<InputArrayType> to_array(const InputVarType& _var) const noexcept;
rfl::Result<InputObjectType> to_object(
const InputVarType& _var) const noexcept;
rfl::Result<InputMapType> to_map(const InputVarType& _var) const noexcept;
rfl::Result<InputUnionType> to_union(const InputVarType& _var) const noexcept;
template <class ArrayReader>
std::optional<Error> read_array(const ArrayReader& _array_reader,
const InputArrayType& _arr) const noexcept {
size_t size = 0;
avro_value_get_size(_arr.val_, &size);
for (size_t ix = 0; ix < size; ++ix) {
avro_value_t element;
avro_value_get_by_index(_arr.val_, ix, &element, nullptr);
const auto err = _array_reader.read(InputVarType{&element});
if (err) {
return err;
}
}
return std::nullopt;
}
template <class MapReader>
std::optional<Error> read_map(const MapReader& _map_reader,
const InputMapType& _map) const noexcept {
size_t size = 0;
avro_value_get_size(_map.val_, &size);
for (size_t ix = 0; ix < size; ++ix) {
avro_value_t element;
const char* key = nullptr;
avro_value_get_by_index(_map.val_, ix, &element, &key);
_map_reader.read(std::string_view(key), InputVarType{&element});
}
return std::nullopt;
}
template <class ObjectReader>
std::optional<Error> read_object(const ObjectReader& _object_reader,
const InputObjectType& _obj) const noexcept {
size_t size = 0;
avro_value_get_size(_obj.val_, &size);
for (size_t ix = 0; ix < size; ++ix) {
avro_value_t element;
avro_value_get_by_index(_obj.val_, ix, &element, nullptr);
_object_reader.read(static_cast<int>(ix), InputVarType{&element});
}
return std::nullopt;
}
template <class VariantType, class UnionReaderType>
rfl::Result<VariantType> read_union(
const InputUnionType& _union) const noexcept {
int disc = 0;
auto err = avro_value_get_discriminant(_union.val_, &disc);
if (err) {
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 UnionReaderType::read(*this, static_cast<size_t>(disc),
InputVarType{&value});
}
template <class T>
rfl::Result<T> use_custom_constructor(
const InputVarType& _var) const noexcept {
try {
return T::from_avro_obj(_var);
} catch (std::exception& e) {
return rfl::Error(e.what());
}
}
};
} // namespace rfl::avro
#endif
+43
View File
@@ -0,0 +1,43 @@
#ifndef RFL_AVRO_SCHEMA_HPP_
#define RFL_AVRO_SCHEMA_HPP_
#include <type_traits>
#include "../Ref.hpp"
#include "SchemaImpl.hpp"
namespace rfl::avro {
template <class T>
class Schema {
public:
using Type = std::remove_cvref_t<T>;
Schema(const std::string& _json_str)
: impl_(Ref<SchemaImpl>::make(_json_str)) {}
static Result<Schema<T>> from_json(const std::string& _json_str) noexcept {
try {
return Schema<T>(_json_str);
} catch (std::exception& e) {
return Error(e.what());
}
}
/// The JSON string used to create this schema.
const std::string& json_str() const { return impl_->json_str(); }
/// The JSON string used to create this schema.
const std::string& str() const { return impl_->json_str(); }
/// The interface used to create new values.
avro_value_iface_t* iface() const { return impl_->iface(); };
private:
/// We are using the "pimpl"-pattern
Ref<SchemaImpl> impl_;
};
} // namespace rfl::avro
#endif
+46
View File
@@ -0,0 +1,46 @@
#ifndef RFL_AVRO_SCHEMAIMPL_HPP_
#define RFL_AVRO_SCHEMAIMPL_HPP_
#include <avro.h>
#include <string>
#include "../Box.hpp"
#include "../Result.hpp"
namespace rfl::avro {
class SchemaImpl {
public:
SchemaImpl(const std::string& _json_str);
~SchemaImpl();
SchemaImpl(const SchemaImpl& _other) = delete;
SchemaImpl(SchemaImpl&& _other) noexcept;
SchemaImpl& operator=(const SchemaImpl& _other) = delete;
SchemaImpl& operator=(SchemaImpl&& _other) noexcept;
/// The JSON string used to create this schema.
const std::string& json_str() const { return json_str_; }
/// The interface used to create new values.
avro_value_iface_t* iface() const { return iface_; };
private:
/// The JSON string used to create the schema.
std::string json_str_;
/// The actual schema
Box<avro_schema_t> schema_;
/// The interface used to create new, generic classes.
avro_value_iface_t* iface_;
};
} // namespace rfl::avro
#endif
+216
View File
@@ -0,0 +1,216 @@
#ifndef RFL_AVRO_WRITER_HPP_
#define RFL_AVRO_WRITER_HPP_
#include <avro.h>
#include <bit>
#include <cstdint>
#include <exception>
#include <map>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <type_traits>
#include <variant>
#include <vector>
#include "../Box.hpp"
#include "../Bytestring.hpp"
#include "../Ref.hpp"
#include "../Result.hpp"
#include "../always_false.hpp"
#include "../internal/is_literal.hpp"
namespace rfl::avro {
class Writer {
public:
struct AVROOutputArray {
avro_value_t val_;
};
struct AVROOutputMap {
avro_value_t val_;
};
struct AVROOutputObject {
avro_value_t val_;
};
struct AVROOutputUnion {
avro_value_t val_;
};
struct AVROOutputVar {
avro_value_t val_;
};
using OutputArrayType = AVROOutputArray;
using OutputMapType = AVROOutputMap;
using OutputObjectType = AVROOutputObject;
using OutputUnionType = AVROOutputUnion;
using OutputVarType = AVROOutputVar;
Writer(avro_value_t* _root);
~Writer();
OutputArrayType array_as_root(const size_t _size) const noexcept;
OutputMapType map_as_root(const size_t _size) const noexcept;
OutputObjectType object_as_root(const size_t _size) const noexcept;
OutputVarType null_as_root() const noexcept;
OutputUnionType union_as_root() const noexcept;
template <class T>
OutputVarType value_as_root(const T& _var) const noexcept {
set_value(_var, root_);
return OutputVarType{*root_};
}
OutputArrayType add_array_to_array(const size_t _size,
OutputArrayType* _parent) const noexcept;
OutputArrayType add_array_to_map(const std::string_view& _name,
const size_t _size,
OutputMapType* _parent) const noexcept;
OutputArrayType add_array_to_object(const std::string_view& _name,
const size_t _size,
OutputObjectType* _parent) const noexcept;
OutputArrayType add_array_to_union(const size_t _index, const size_t _size,
OutputUnionType* _parent) const noexcept;
OutputMapType add_map_to_array(const size_t _size,
OutputArrayType* _parent) const noexcept;
OutputMapType add_map_to_map(const std::string_view& _name,
const size_t _size,
OutputMapType* _parent) const noexcept;
OutputMapType add_map_to_object(const std::string_view& _name,
const size_t _size,
OutputObjectType* _parent) const noexcept;
OutputMapType add_map_to_union(const size_t _index, const size_t _size,
OutputUnionType* _parent) const noexcept;
OutputObjectType add_object_to_array(const size_t _size,
OutputArrayType* _parent) const noexcept;
OutputObjectType add_object_to_map(const std::string_view& _name,
const size_t _size,
OutputMapType* _parent) const noexcept;
OutputObjectType add_object_to_object(
const std::string_view& _name, const size_t _size,
OutputObjectType* _parent) const noexcept;
OutputObjectType add_object_to_union(const size_t _index, const size_t _size,
OutputUnionType* _parent) const noexcept;
OutputUnionType add_union_to_array(OutputArrayType* _parent) const noexcept;
OutputUnionType add_union_to_map(const std::string_view& _name,
OutputMapType* _parent) const noexcept;
OutputUnionType add_union_to_object(const std::string_view& _name,
OutputObjectType* _parent) const noexcept;
OutputUnionType add_union_to_union(const size_t _index,
OutputUnionType* _parent) const noexcept;
OutputVarType add_null_to_array(OutputArrayType* _parent) const noexcept;
OutputVarType add_null_to_map(const std::string_view& _name,
OutputMapType* _parent) const noexcept;
OutputVarType add_null_to_object(const std::string_view& _name,
OutputObjectType* _parent) const noexcept;
OutputVarType add_null_to_union(const size_t _index,
OutputUnionType* _parent) const noexcept;
template <class T>
OutputVarType add_value_to_array(const T& _var,
OutputArrayType* _parent) const noexcept {
avro_value_t new_value;
avro_value_append(&_parent->val_, &new_value, nullptr);
set_value(_var, &new_value);
return OutputVarType{new_value};
}
template <class T>
OutputVarType add_value_to_map(const std::string_view& _name, const T& _var,
OutputMapType* _parent) const noexcept {
avro_value_t new_value;
avro_value_add(&_parent->val_, _name.data(), &new_value, nullptr, nullptr);
set_value(_var, &new_value);
return OutputVarType{new_value};
}
template <class T>
OutputVarType add_value_to_object(const std::string_view& _name,
const T& _var,
OutputObjectType* _parent) const noexcept {
avro_value_t new_value;
avro_value_get_by_name(&_parent->val_, _name.data(), &new_value, nullptr);
set_value(_var, &new_value);
return OutputVarType{new_value};
}
template <class T>
OutputVarType add_value_to_union(const size_t _index, const T& _var,
OutputUnionType* _parent) const noexcept {
avro_value_t new_value;
avro_value_set_branch(&_parent->val_, static_cast<int>(_index), &new_value);
set_value(_var, &new_value);
return OutputVarType{new_value};
}
void end_array(OutputArrayType* _arr) const noexcept {}
void end_map(OutputMapType* _obj) const noexcept {}
void end_object(OutputObjectType* _obj) const noexcept {}
private:
template <class T>
void set_value(const T& _var, avro_value_t* _val) const noexcept {
if constexpr (std::is_same<std::remove_cvref_t<T>, std::string>()) {
avro_value_set_string_len(_val, _var.c_str(), _var.size() + 1);
} else if constexpr (std::is_same<std::remove_cvref_t<T>,
rfl::Bytestring>()) {
auto var = _var;
avro_value_set_bytes(_val, var.data(), var.size() + 1);
} else if constexpr (std::is_same<std::remove_cvref_t<T>, bool>()) {
avro_value_set_boolean(_val, _var);
} else if constexpr (std::is_floating_point<std::remove_cvref_t<T>>()) {
avro_value_set_double(_val, static_cast<double>(_var));
} else if constexpr (std::is_integral<std::remove_cvref_t<T>>()) {
avro_value_set_long(_val, static_cast<std::int64_t>(_var));
} else if constexpr (internal::is_literal_v<T>) {
avro_value_set_enum(_val, static_cast<int>(_var.value()));
} else {
static_assert(rfl::always_false_v<T>, "Unsupported type.");
}
}
private:
avro_value_t* root_;
};
} // namespace rfl::avro
#endif
+23
View File
@@ -0,0 +1,23 @@
#ifndef RFL_AVRO_LOAD_HPP_
#define RFL_AVRO_LOAD_HPP_
#include "../Processors.hpp"
#include "../Result.hpp"
#include "../io/load_bytes.hpp"
#include "read.hpp"
namespace rfl {
namespace avro {
template <class T, class... Ps>
Result<T> load(const std::string& _fname) {
const auto read_bytes = [](const auto& _bytes) {
return read<T, Ps...>(_bytes);
};
return rfl::io::load_bytes(_fname).and_then(read_bytes);
}
} // namespace avro
} // namespace rfl
#endif
+78
View File
@@ -0,0 +1,78 @@
#ifndef RFL_AVRO_READ_HPP_
#define RFL_AVRO_READ_HPP_
#include <avro.h>
#include <bit>
#include <istream>
#include <string>
#include <type_traits>
#include "../Processors.hpp"
#include "../internal/wrap_in_rfl_array_t.hpp"
#include "Parser.hpp"
#include "Reader.hpp"
#include "Schema.hpp"
#include "to_schema.hpp"
namespace rfl::avro {
using InputObjectType = typename Reader::InputObjectType;
using InputVarType = typename Reader::InputVarType;
/// Parses an object from a AVRO var.
template <class T, class... Ps>
auto read(const InputVarType& _obj) {
const auto r = Reader();
return Parser<T, Processors<Ps...>>::read(r, _obj);
}
/// Parses an object from AVRO using reflection.
template <class T, class... Ps>
Result<internal::wrap_in_rfl_array_t<T>> read(
const char* _bytes, const size_t _size, const Schema<T>& _schema) noexcept {
avro_reader_t avro_reader = avro_reader_memory(_bytes, _size);
avro_value_t root;
avro_generic_value_new(_schema.iface(), &root);
auto err = avro_value_read(avro_reader, &root);
if (err) {
avro_value_decref(&root);
avro_reader_free(avro_reader);
return Error(std::string("Could not read root value: ") + avro_strerror());
}
auto result = read<T, Ps...>(InputVarType{&root});
avro_value_decref(&root);
avro_reader_free(avro_reader);
return result;
}
/// Parses an object from AVRO using reflection.
template <class T, class... Ps>
auto read(const char* _bytes, const size_t _size) noexcept {
const auto schema = to_schema<std::remove_cvref_t<T>, Ps...>();
return read<T, Ps...>(_bytes, _size, schema);
}
/// Parses an object from AVRO using reflection.
template <class T, class... Ps>
auto read(const std::vector<char>& _bytes, const Schema<T>& _schema) {
return read<T, Ps...>(_bytes.data(), _bytes.size(), _schema);
}
/// Parses an object from AVRO using reflection.
template <class T, class... Ps>
auto read(const std::vector<char>& _bytes) {
return read<T, Ps...>(_bytes.data(), _bytes.size());
}
/// Parses an object from a stream.
template <class T, class... Ps>
auto read(std::istream& _stream) {
std::istreambuf_iterator<char> begin(_stream), end;
auto bytes = std::vector<char>(begin, end);
return read<T, Ps...>(bytes.data(), bytes.size());
}
} // namespace rfl::avro
#endif
+25
View File
@@ -0,0 +1,25 @@
#ifndef RFL_AVRO_SAVE_HPP_
#define RFL_AVRO_SAVE_HPP_
#include <fstream>
#include <iostream>
#include <string>
#include "../Result.hpp"
#include "../io/save_bytes.hpp"
#include "write.hpp"
namespace rfl::avro {
template <class... Ps>
Result<Nothing> save(const std::string& _fname, const auto& _obj) {
const auto write_func = [](const auto& _obj,
std::ostream& _stream) -> std::ostream& {
return write<Ps...>(_obj, _stream);
};
return rfl::io::save_bytes(_fname, _obj, write_func);
}
} // namespace rfl::avro
#endif
+96
View File
@@ -0,0 +1,96 @@
#ifndef RFL_AVRO_SCHEMA_TYPE_HPP_
#define RFL_AVRO_SCHEMA_TYPE_HPP_
#include <map>
#include <memory>
#include <optional>
#include <string>
#include "../../Literal.hpp"
#include "../../Object.hpp"
#include "../../Rename.hpp"
#include "../../Variant.hpp"
namespace rfl::avro::schema {
struct Type {
struct Null {
Literal<"null"> type;
};
struct Boolean {
Literal<"boolean"> type;
};
struct Int {
Literal<"int"> type;
};
struct Long {
Literal<"long"> type;
};
struct Float {
Literal<"float"> type;
};
struct Double {
Literal<"float"> type;
};
struct Bytes {
Literal<"bytes"> type;
};
struct String {
Literal<"string"> type;
};
struct RecordField {
std::string name;
rfl::Ref<Type> type;
};
struct Record {
Literal<"record"> type;
std::string name;
std::vector<RecordField> fields;
std::optional<std::string> doc;
};
struct Enum {
Literal<"enum"> type;
std::string name;
std::vector<std::string> symbols;
};
struct Array {
Literal<"array"> type;
rfl::Ref<Type> items;
Rename<"default", std::vector<std::string>> default_;
};
struct Map {
Literal<"map"> type;
rfl::Ref<Type> values;
Rename<"default", std::map<std::string, std::string>> default_;
};
struct Reference {
std::string type;
};
using ReflectionType =
rfl::Variant<Null, Boolean, Int, Long, Float, Double, Bytes, String,
Record, Enum, Array, Map, Reference, std::vector<Type>>;
const auto& reflection() const { return value; }
Type with_name(const std::string& _name) const;
ReflectionType value;
};
} // namespace rfl::avro::schema
#endif
+35
View File
@@ -0,0 +1,35 @@
#ifndef RFL_AVRO_TOSCHEMA_HPP_
#define RFL_AVRO_TOSCHEMA_HPP_
#include <map>
#include <string>
#include <type_traits>
#include "../Literal.hpp"
#include "../Processors.hpp"
#include "../Variant.hpp"
#include "../json.hpp"
#include "../parsing/schema/Type.hpp"
#include "../parsing/schema/ValidationType.hpp"
#include "../parsing/schema/make.hpp"
#include "Reader.hpp"
#include "Schema.hpp"
#include "Writer.hpp"
#include "schema/Type.hpp"
namespace rfl::avro {
std::string to_json_representation(
const parsing::schema::Definition& internal_schema);
/// Returns the Avro schema for a class.
template <class T, class... Ps>
Schema<T> to_schema() noexcept {
const auto internal_schema =
parsing::schema::make<Reader, Writer, T, Processors<Ps...>>();
const auto json_str = to_json_representation(internal_schema);
return std::move(Schema<T>::from_json(json_str).value());
}
} // namespace rfl::avro
#endif
+63
View File
@@ -0,0 +1,63 @@
#ifndef RFL_AVRO_WRITE_HPP_
#define RFL_AVRO_WRITE_HPP_
#include <avro.h>
#include <bit>
#include <cstdint>
#include <ostream>
#include <sstream>
#include <string>
#include <type_traits>
#include <utility>
#include "../parsing/Parent.hpp"
#include "Parser.hpp"
#include "Schema.hpp"
#include "Writer.hpp"
#include "to_schema.hpp"
namespace rfl::avro {
/// Returns AVRO bytes.
template <class... Ps>
std::vector<char> write(const auto& _obj, const auto& _schema) noexcept {
using T = std::remove_cvref_t<decltype(_obj)>;
using U = typename std::remove_cvref_t<decltype(_schema)>::Type;
using ParentType = parsing::Parent<Writer>;
static_assert(std::is_same<T, U>(),
"The schema must be compatible with the type to write.");
avro_value_t root;
avro_generic_value_new(_schema.iface(), &root);
const auto writer = Writer(&root);
Parser<T, Processors<Ps...>>::write(writer, _obj,
typename ParentType::Root{});
size_t size = 0;
avro_value_sizeof(&root, &size);
std::vector<char> buffer(size);
avro_writer_t avro_writer = avro_writer_memory(buffer.data(), buffer.size());
avro_value_write(avro_writer, &root);
avro_value_decref(&root);
avro_writer_free(avro_writer);
return buffer;
}
/// Returns AVRO bytes.
template <class... Ps>
std::vector<char> write(const auto& _obj) noexcept {
using T = std::remove_cvref_t<decltype(_obj)>;
const auto schema = to_schema<T, Ps...>();
return write<Ps...>(_obj, schema);
}
/// Writes a AVRO into an ostream.
template <class... Ps>
std::ostream& write(const auto& _obj, std::ostream& _stream) noexcept {
auto buffer = write<Ps...>(_obj);
_stream.write(buffer.data(), buffer.size());
return _stream;
}
} // namespace rfl::avro
#endif
@@ -14,9 +14,7 @@
#include "get_enum_names.hpp"
#include "is_flag_enum.hpp"
namespace rfl {
namespace internal {
namespace enums {
namespace rfl ::internal ::enums {
template <class EnumType>
class StringConverter {
@@ -125,8 +123,6 @@ class StringConverter {
}
};
} // namespace enums
} // namespace internal
} // namespace rfl
} // namespace rfl::internal::enums
#endif
+2 -1
View File
@@ -7,6 +7,7 @@
#include <string>
#include "../../Literal.hpp"
#include "../../Object.hpp"
#include "../../Rename.hpp"
#include "../../Variant.hpp"
@@ -88,7 +89,7 @@ struct Type {
struct Object {
Literal<"object"> type;
std::optional<std::string> description;
std::map<std::string, Type> properties;
rfl::Object<Type> properties;
std::vector<std::string> required;
std::shared_ptr<Type> additionalProperties;
};
+50 -55
View File
@@ -12,6 +12,8 @@
#include "../Result.hpp"
#include "../internal/is_basic_type.hpp"
#include "../internal/wrap_in_rfl_array_t.hpp"
#include "SupportsTaggedUnions.hpp"
#include "schemaful/IsSchemafulReader.hpp"
namespace rfl {
namespace parsing {
@@ -25,71 +27,64 @@ struct MockArrayReader {
template <class R>
struct MockObjectReader {
void read(const std::string_view&,
typename R::InputVarType&) const {}
void read(const std::string_view&, typename R::InputVarType&) const {}
};
template <class R, class T>
concept IsReader = requires(R r, std::string name,
std::function<std::int16_t(std::string_view)> fct,
MockArrayReader<R> array_reader,
MockObjectReader<R> object_reader,
typename R::InputArrayType arr,
typename R::InputObjectType obj,
typename R::InputVarType var, size_t idx) {
/// Any Reader needs to define the following:
///
/// 1) An InputArrayType, which must be an array-like data structure.
/// 2) An InputObjectType, which must contain key-value pairs.
/// 3) An InputVarType, which must be able to represent either
/// InputArrayType, InputObjectType or a basic type (bool, integral,
/// floating point, std::string).
/// 4) A static constexpr bool has_custom_constructor, that determines
/// whether the class in question as a custom constructor, which might
/// be called something like from_json_obj(...).
concept IsReader =
(SupportsTaggedUnions<R> || schemaful::IsSchemafulReader<R>) &&
requires(R r, std::string name,
std::function<std::int16_t(std::string_view)> fct,
MockArrayReader<R> array_reader, MockObjectReader<R> object_reader,
typename R::InputArrayType arr, typename R::InputObjectType obj,
typename R::InputVarType var, size_t idx) {
/// Any Reader needs to define the following:
///
/// 1) An InputArrayType, which must be an array-like data structure.
/// 2) An InputObjectType, which must contain key-value pairs.
/// 3) An InputVarType, which must be able to represent either
/// InputArrayType, InputObjectType or a basic type (bool, integral,
/// floating point, std::string).
/// 4) A static constexpr bool has_custom_constructor, that determines
/// whether the class in question as a custom constructor, which might
/// be called something like from_json_obj(...).
/// Retrieves a particular field from an array.
{
r.get_field_from_array(idx, arr)
} -> std::same_as<rfl::Result<typename R::InputVarType>>;
/// Determines whether a variable is empty (the NULL type).
{ r.is_empty(var) } -> std::same_as<bool>;
/// Retrieves a particular field from an object.
{
r.get_field_from_object(name, obj)
} -> std::same_as<rfl::Result<typename R::InputVarType>>;
/// Iterates through an array and writes the contained vars into
/// an array reader.
{ r.read_array(array_reader, arr) } -> std::same_as<std::optional<Error>>;
/// Determines whether a variable is empty (the NULL type).
{ r.is_empty(var) } -> std::same_as<bool>;
/// Iterates through an object and writes the key-value pairs into an
/// object reader. This is what we use to handle structs and named tuples,
/// making it a very important function.
{
r.read_object(object_reader, obj)
} -> std::same_as<std::optional<Error>>;
/// Iterates through an array and writes the contained vars into
/// an array reader.
{ r.read_array(array_reader, arr) } -> std::same_as<std::optional<Error>>;
/// Transforms var to a basic type (bool, integral,
/// floating point, std::string)
{
r.template to_basic_type<internal::wrap_in_rfl_array_t<T>>(var)
} -> std::same_as<rfl::Result<internal::wrap_in_rfl_array_t<T>>>;
/// Iterates through an object and writes the key-value pairs into an object
/// reader. This is what we use to handle structs and named tuples, making it
/// a very important function.
{ r.read_object(object_reader, obj) } -> std::same_as<std::optional<Error>>;
/// Casts var as an InputArrayType.
{
r.to_array(var)
} -> std::same_as<rfl::Result<typename R::InputArrayType>>;
/// Transforms var to a basic type (bool, integral,
/// floating point, std::string)
{
r.template to_basic_type<internal::wrap_in_rfl_array_t<T>>(var)
} -> std::same_as<rfl::Result<internal::wrap_in_rfl_array_t<T>>>;
/// Casts var as an InputObjectType.
{
r.to_object(var)
} -> std::same_as<rfl::Result<typename R::InputObjectType>>;
/// Casts var as an InputArrayType.
{ r.to_array(var) } -> std::same_as<rfl::Result<typename R::InputArrayType>>;
/// Casts var as an InputObjectType.
{
r.to_object(var)
} -> std::same_as<rfl::Result<typename R::InputObjectType>>;
/// Uses the custom constructor, if it has been determined that T has one
/// (see above).
{
r.template use_custom_constructor<internal::wrap_in_rfl_array_t<T>>(var)
} -> std::same_as<rfl::Result<internal::wrap_in_rfl_array_t<T>>>;
};
/// Uses the custom constructor, if it has been determined that T has one
/// (see above).
{
r.template use_custom_constructor<internal::wrap_in_rfl_array_t<T>>(var)
} -> std::same_as<rfl::Result<internal::wrap_in_rfl_array_t<T>>>;
};
} // namespace parsing
} // namespace rfl
+87 -24
View File
@@ -13,13 +13,15 @@
#include "Parent.hpp"
#include "Parser_base.hpp"
#include "schema/Type.hpp"
#include "schemaful/IsSchemafulReader.hpp"
#include "schemaful/IsSchemafulWriter.hpp"
#include "to_single_error_message.hpp"
namespace rfl {
namespace parsing {
template <class R, class W, class MapType, class ProcessorsType>
requires AreReaderAndWriter<R, W, MapType>
requires AreReaderAndWriter<R, W, MapType>
struct MapParser {
public:
using InputObjectType = typename R::InputObjectType;
@@ -35,11 +37,94 @@ struct MapParser {
const auto to_map = [&](auto obj) -> Result<MapType> {
return make_map(_r, obj);
};
return _r.to_object(_var).and_then(to_map);
if constexpr (schemaful::IsSchemafulReader<R>) {
return _r.to_map(_var).and_then(to_map);
} else {
return _r.to_object(_var).and_then(to_map);
}
}
template <class P>
static void write(const W& _w, const MapType& _m, const P& _parent) noexcept {
if constexpr (schemaful::IsSchemafulWriter<W>) {
write_map(_w, _m, _parent);
} else {
write_object(_w, _m, _parent);
}
}
static schema::Type to_schema(
std::map<std::string, schema::Type>* _definitions) {
return schema::Type{schema::Type::StringMap{Ref<schema::Type>::make(
Parser<R, W, ValueType, ProcessorsType>::to_schema(_definitions))}};
}
private:
static Result<MapType> make_map(const R& _r, const auto& _obj_or_map) {
MapType map;
std::vector<Error> errors;
const auto map_reader =
MapReader<R, W, MapType, ProcessorsType>(&_r, &map, &errors);
if constexpr (schemaful::IsSchemafulReader<R>) {
const auto err = _r.read_map(map_reader, _obj_or_map);
if (err) {
return *err;
}
} else {
const auto err = _r.read_object(map_reader, _obj_or_map);
if (err) {
return *err;
}
}
if (errors.size() != 0) {
return to_single_error_message(errors);
}
return map;
}
template <class P>
static void write_map(const W& _w, const MapType& _m,
const P& _parent) noexcept {
auto m = ParentType::add_map(_w, _m.size(), _parent);
using ParentMapType =
typename ParentType::template Map<typename W::OutputMapType>;
for (const auto& [k, v] : _m) {
if constexpr (internal::has_reflection_type_v<KeyType>) {
using ReflT = typename KeyType::ReflectionType;
if constexpr (std::is_integral_v<ReflT> ||
std::is_floating_point_v<ReflT>) {
const auto name = std::to_string(k.reflection());
const auto new_parent = ParentMapType{name, &m};
Parser<R, W, std::remove_cvref_t<ValueType>, ProcessorsType>::write(
_w, v, new_parent);
} else {
const auto name = k.reflection();
const auto new_parent = ParentMapType{name, &m};
Parser<R, W, std::remove_cvref_t<ValueType>, ProcessorsType>::write(
_w, v, new_parent);
}
} else if constexpr (std::is_integral_v<KeyType> ||
std::is_floating_point_v<KeyType>) {
const auto name = std::to_string(k);
const auto new_parent = ParentMapType{name, &m};
Parser<R, W, std::remove_cvref_t<ValueType>, ProcessorsType>::write(
_w, v, new_parent);
} else {
const auto new_parent = ParentMapType{k, &m};
Parser<R, W, std::remove_cvref_t<ValueType>, ProcessorsType>::write(
_w, v, new_parent);
}
}
_w.end_map(&m);
}
template <class P>
static void write_object(const W& _w, const MapType& _m,
const P& _parent) noexcept {
auto obj = ParentType::add_object(_w, _m.size(), _parent);
for (const auto& [k, v] : _m) {
if constexpr (internal::has_reflection_type_v<KeyType>) {
@@ -72,28 +157,6 @@ struct MapParser {
}
_w.end_object(&obj);
}
static schema::Type to_schema(
std::map<std::string, schema::Type>* _definitions) {
return schema::Type{schema::Type::StringMap{Ref<schema::Type>::make(
Parser<R, W, ValueType, ProcessorsType>::to_schema(_definitions))}};
}
private:
static Result<MapType> make_map(const R& _r, const InputObjectType& _obj) {
MapType map;
std::vector<Error> errors;
const auto map_reader =
MapReader<R, W, MapType, ProcessorsType>(&_r, &map, &errors);
const auto err = _r.read_object(map_reader, _obj);
if (err) {
return *err;
}
if (errors.size() != 0) {
return to_single_error_message(errors);
}
return map;
}
};
} // namespace parsing
+120 -4
View File
@@ -6,10 +6,10 @@
#include <type_traits>
#include "../always_false.hpp"
#include "schemaful/IsSchemafulWriter.hpp"
#include "supports_attributes.hpp"
namespace rfl {
namespace parsing {
namespace rfl::parsing {
template <class W>
struct Parent {
@@ -21,6 +21,13 @@ struct Parent {
OutputArrayType* arr_;
};
// For schemaful formats only.
template <class T>
struct Map {
std::string_view name_;
T* map_;
};
struct Object {
std::string_view name_;
OutputObjectType* obj_;
@@ -28,6 +35,13 @@ struct Parent {
Object as_attribute() const { return Object{name_, obj_, true}; }
};
// For schemaful formats only.
template <class T>
struct Union {
size_t index_;
T* union_;
};
struct Root {};
template <class ParentType>
@@ -36,10 +50,49 @@ struct Parent {
using Type = std::remove_cvref_t<ParentType>;
if constexpr (std::is_same<Type, Array>()) {
return _w.add_array_to_array(_size, _parent.arr_);
} else if constexpr (std::is_same<Type, Object>()) {
return _w.add_array_to_object(_parent.name_, _size, _parent.obj_);
} else if constexpr (std::is_same<Type, Root>()) {
return _w.array_as_root(_size);
} else if constexpr (schemaful::IsSchemafulWriter<W>) {
if constexpr (std::is_same<Type, Map<typename W::OutputMapType>>()) {
return _w.add_array_to_map(_parent.name_, _size, _parent.map_);
} else if constexpr (std::is_same<Type,
Union<typename W::OutputUnionType>>()) {
return _w.add_array_to_union(_parent.index_, _size, _parent.union_);
} else {
static_assert(always_false_v<Type>, "Unsupported option.");
}
} else {
static_assert(always_false_v<Type>, "Unsupported option.");
}
}
// For schemaful formats only.
template <class ParentType>
static auto add_map(const W& _w, const size_t _size,
const ParentType& _parent) {
using Type = std::remove_cvref_t<ParentType>;
if constexpr (std::is_same<Type, Array>()) {
return _w.add_map_to_array(_size, _parent.arr_);
} else if constexpr (std::is_same<Type, Map<typename W::OutputMapType>>()) {
return _w.add_map_to_map(_parent.name_, _size, _parent.map_);
} else if constexpr (std::is_same<Type, Object>()) {
return _w.add_map_to_object(_parent.name_, _size, _parent.obj_);
} else if constexpr (std::is_same<Type,
Union<typename W::OutputUnionType>>()) {
return _w.add_map_to_union(_parent.index_, _size, _parent.union_);
} else if constexpr (std::is_same<Type, Root>()) {
return _w.map_as_root(_size);
} else {
static_assert(always_false_v<Type>, "Unsupported option.");
}
@@ -51,10 +104,23 @@ struct Parent {
using Type = std::remove_cvref_t<ParentType>;
if constexpr (std::is_same<Type, Array>()) {
return _w.add_object_to_array(_size, _parent.arr_);
} else if constexpr (std::is_same<Type, Object>()) {
return _w.add_object_to_object(_parent.name_, _size, _parent.obj_);
} else if constexpr (std::is_same<Type, Root>()) {
return _w.object_as_root(_size);
} else if constexpr (schemaful::IsSchemafulWriter<W>) {
if constexpr (std::is_same<Type, Map<typename W::OutputMapType>>()) {
return _w.add_object_to_map(_parent.name_, _size, _parent.map_);
} else if constexpr (std::is_same<Type,
Union<typename W::OutputUnionType>>()) {
return _w.add_object_to_union(_parent.index_, _size, _parent.union_);
} else {
static_assert(always_false_v<Type>, "Unsupported option.");
}
} else {
static_assert(always_false_v<Type>, "Unsupported option.");
}
@@ -65,6 +131,7 @@ struct Parent {
using Type = std::remove_cvref_t<ParentType>;
if constexpr (std::is_same<Type, Array>()) {
return _w.add_null_to_array(_parent.arr_);
} else if constexpr (std::is_same<Type, Object>()) {
if constexpr (supports_attributes<std::remove_cvref_t<W>>) {
return _w.add_null_to_object(_parent.name_, _parent.obj_,
@@ -72,8 +139,45 @@ struct Parent {
} else {
return _w.add_null_to_object(_parent.name_, _parent.obj_);
}
} else if constexpr (std::is_same<Type, Root>()) {
return _w.null_as_root();
} else if constexpr (schemaful::IsSchemafulWriter<W>) {
if constexpr (std::is_same<Type, Map<typename W::OutputMapType>>()) {
return _w.add_null_to_map(_parent.name_, _parent.map_);
} else if constexpr (std::is_same<Type,
Union<typename W::OutputUnionType>>()) {
return _w.add_null_to_union(_parent.index_, _parent.union_);
} else {
static_assert(always_false_v<Type>, "Unsupported option.");
}
} else {
static_assert(always_false_v<Type>, "Unsupported option.");
}
}
// For schemaful formats only.
template <class ParentType>
static auto add_union(const W& _w, const ParentType& _parent) {
using Type = std::remove_cvref_t<ParentType>;
if constexpr (std::is_same<Type, Array>()) {
return _w.add_union_to_array(_parent.arr_);
} else if constexpr (std::is_same<Type, Map<typename W::OutputMapType>>()) {
return _w.add_union_to_map(_parent.name_, _parent.map_);
} else if constexpr (std::is_same<Type, Object>()) {
return _w.add_union_to_object(_parent.name_, _parent.obj_);
} else if constexpr (std::is_same<Type,
Union<typename W::OutputUnionType>>()) {
return _w.add_union_to_union(_parent.index_, _parent.union_);
} else if constexpr (std::is_same<Type, Root>()) {
return _w.union_as_root();
} else {
static_assert(always_false_v<Type>, "Unsupported option.");
}
@@ -85,6 +189,7 @@ struct Parent {
using Type = std::remove_cvref_t<ParentType>;
if constexpr (std::is_same<Type, Array>()) {
return _w.add_value_to_array(_var, _parent.arr_);
} else if constexpr (std::is_same<Type, Object>()) {
if constexpr (supports_attributes<std::remove_cvref_t<W>>) {
return _w.add_value_to_object(_parent.name_, _var, _parent.obj_,
@@ -92,15 +197,26 @@ struct Parent {
} else {
return _w.add_value_to_object(_parent.name_, _var, _parent.obj_);
}
} else if constexpr (std::is_same<Type, Root>()) {
return _w.value_as_root(_var);
} else if constexpr (schemaful::IsSchemafulWriter<W>) {
if constexpr (std::is_same<Type, Map<typename W::OutputMapType>>()) {
return _w.add_value_to_map(_parent.name_, _var, _parent.map_);
} else if constexpr (std::is_same<Type,
Union<typename W::OutputUnionType>>()) {
return _w.add_value_to_union(_parent.index_, _var, _parent.union_);
} else {
static_assert(always_false_v<Type>, "Unsupported option.");
}
} else {
static_assert(always_false_v<Type>, "Unsupported option.");
}
}
};
} // namespace parsing
} // namespace rfl
} // namespace rfl::parsing
#endif
+31 -7
View File
@@ -5,6 +5,7 @@
#include <stdexcept>
#include <type_traits>
#include "../Bytestring.hpp"
#include "../Result.hpp"
#include "../always_false.hpp"
#include "../from_named_tuple.hpp"
@@ -28,9 +29,10 @@
#include "call_destructors_where_necessary.hpp"
#include "is_tagged_union_wrapper.hpp"
#include "schema/Type.hpp"
#include "schemaful/IsSchemafulReader.hpp"
#include "schemaful/IsSchemafulWriter.hpp"
namespace rfl {
namespace parsing {
namespace rfl ::parsing {
/// Default case - anything that cannot be explicitly matched.
template <class R, class W, class T, class ProcessorsType>
@@ -54,8 +56,14 @@ struct Parser {
return Parser<R, W, typename Reflector<T>::ReflType,
ProcessorsType>::read(_r, _var)
.and_then(wrap_in_t);
} else if constexpr (schemaful::IsSchemafulReader<R> &&
internal::is_literal_v<T>) {
return _r.template to_basic_type<T>(_var);
} else if constexpr (R::template has_custom_constructor<T>) {
return _r.template use_custom_constructor<T>(_var);
} else {
if constexpr (internal::has_reflection_type_v<T>) {
using ReflectionType = std::remove_cvref_t<typename T::ReflectionType>;
@@ -68,14 +76,17 @@ struct Parser {
};
return Parser<R, W, ReflectionType, ProcessorsType>::read(_r, _var)
.and_then(wrap_in_t);
} else if constexpr (std::is_class_v<T> && std::is_aggregate_v<T>) {
if constexpr (ProcessorsType::default_if_missing_) {
return read_struct_with_default(_r, _var);
} else {
return read_struct(_r, _var);
}
} else if constexpr (std::is_enum_v<T>) {
if constexpr (ProcessorsType::underlying_enums_) {
if constexpr (ProcessorsType::underlying_enums_ ||
schemaful::IsSchemafulReader<R>) {
return static_cast<T>(
*_r.template to_basic_type<std::underlying_type_t<T>>(_var));
} else {
@@ -83,6 +94,7 @@ struct Parser {
return _r.template to_basic_type<std::string>(_var).and_then(
StringConverter::string_to_enum);
}
} else {
return _r.template to_basic_type<std::remove_cvref_t<T>>(_var);
}
@@ -94,6 +106,11 @@ struct Parser {
if constexpr (internal::has_write_reflector<T>) {
Parser<R, W, typename Reflector<T>::ReflType, ProcessorsType>::write(
_w, Reflector<T>::from(_var), _parent);
} else if constexpr (schemaful::IsSchemafulWriter<W> &&
internal::is_literal_v<T>) {
ParentType::add_value(_w, _var, _parent);
} else if constexpr (internal::has_reflection_type_v<T>) {
using ReflectionType = std::remove_cvref_t<typename T::ReflectionType>;
if constexpr (internal::has_reflection_method_v<T>) {
@@ -103,14 +120,17 @@ struct Parser {
const auto& [r] = _var;
Parser<R, W, ReflectionType, ProcessorsType>::write(_w, r, _parent);
}
} else if constexpr (std::is_class_v<T> && std::is_aggregate_v<T>) {
const auto ptr_named_tuple = ProcessorsType::template process<T>(
internal::to_ptr_named_tuple(_var));
using PtrNamedTupleType = std::remove_cvref_t<decltype(ptr_named_tuple)>;
Parser<R, W, PtrNamedTupleType, ProcessorsType>::write(
_w, ptr_named_tuple, _parent);
} else if constexpr (std::is_enum_v<T>) {
if constexpr (ProcessorsType::underlying_enums_) {
if constexpr (ProcessorsType::underlying_enums_ ||
schemaful::IsSchemafulWriter<W>) {
const auto val = static_cast<std::underlying_type_t<T>>(_var);
ParentType::add_value(_w, val, _parent);
} else {
@@ -118,6 +138,7 @@ struct Parser {
const auto str = StringConverter::enum_to_string(_var);
ParentType::add_value(_w, str, _parent);
}
} else {
ParentType::add_value(_w, _var, _parent);
}
@@ -131,6 +152,9 @@ struct Parser {
if constexpr (std::is_same<U, bool>()) {
return Type{Type::Boolean{}};
} else if constexpr (std::is_same<U, rfl::Bytestring>()) {
return Type{Type::Bytestring{}};
} else if constexpr (std::is_same<U, std::int32_t>()) {
return Type{Type::Int32{}};
@@ -195,7 +219,8 @@ struct Parser {
std::map<std::string, schema::Type>* _definitions) {
using Type = schema::Type;
using S = internal::enums::StringConverter<U>;
if constexpr (ProcessorsType::underlying_enums_) {
if constexpr (ProcessorsType::underlying_enums_ ||
schemaful::IsSchemafulReader<R>) {
return Type{Type::Integer{}};
} else if constexpr (S::is_flag_enum_) {
return Type{Type::String{}};
@@ -296,7 +321,6 @@ struct Parser {
}
};
} // namespace parsing
} // namespace rfl
} // namespace rfl::parsing
#endif
+36 -11
View File
@@ -11,12 +11,15 @@
#include "Parent.hpp"
#include "Parser_base.hpp"
#include "schema/Type.hpp"
#include "schemaful/IsSchemafulReader.hpp"
#include "schemaful/IsSchemafulWriter.hpp"
#include "schemaful/OptionalReader.hpp"
namespace rfl {
namespace parsing {
template <class R, class W, class T, class ProcessorsType>
requires AreReaderAndWriter<R, W, std::optional<T>>
requires AreReaderAndWriter<R, W, std::optional<T>>
struct Parser<R, W, std::optional<T>, ProcessorsType> {
using InputVarType = typename R::InputVarType;
@@ -24,23 +27,45 @@ struct Parser<R, W, std::optional<T>, ProcessorsType> {
static Result<std::optional<T>> read(const R& _r,
const InputVarType& _var) noexcept {
if (_r.is_empty(_var)) {
return std::optional<T>();
if constexpr (schemaful::IsSchemafulReader<R>) {
using O = schemaful::OptionalReader<R, W, std::remove_cvref_t<T>,
ProcessorsType>;
const auto to_optional = [&](const auto& _u) -> Result<std::optional<T>> {
return _r.template read_union<std::optional<T>, O>(_u);
};
return _r.to_union(_var).and_then(to_optional);
} else {
if (_r.is_empty(_var)) {
return std::optional<T>();
}
const auto to_opt = [](auto&& _t) { return std::make_optional<T>(_t); };
return Parser<R, W, std::remove_cvref_t<T>, ProcessorsType>::read(_r,
_var)
.transform(to_opt);
}
const auto to_opt = [](auto&& _t) { return std::make_optional<T>(_t); };
return Parser<R, W, std::remove_cvref_t<T>, ProcessorsType>::read(_r, _var)
.transform(to_opt);
}
template <class P>
static void write(const W& _w, const std::optional<T>& _o,
const P& _parent) noexcept {
if (!_o) {
ParentType::add_null(_w, _parent);
return;
if constexpr (schemaful::IsSchemafulWriter<W>) {
auto u = ParentType::add_union(_w, _parent);
using UnionType = typename ParentType::template Union<decltype(u)>;
auto p =
UnionType{.index_ = static_cast<size_t>(_o ? 0 : 1), .union_ = &u};
if (_o) {
Parser<R, W, std::remove_cvref_t<T>, ProcessorsType>::write(_w, *_o, p);
} else {
ParentType::add_null(_w, p);
}
} else {
if (_o) {
Parser<R, W, std::remove_cvref_t<T>, ProcessorsType>::write(_w, *_o,
_parent);
} else {
ParentType::add_null(_w, _parent);
}
}
Parser<R, W, std::remove_cvref_t<T>, ProcessorsType>::write(_w, *_o,
_parent);
}
static schema::Type to_schema(
+56 -5
View File
@@ -13,20 +13,45 @@
#include "Parser_base.hpp"
#include "VariantAlternativeWrapper.hpp"
#include "schema/Type.hpp"
#include "schemaful/IsSchemafulReader.hpp"
#include "schemaful/IsSchemafulWriter.hpp"
#include "schemaful/VariantReader.hpp"
namespace rfl::parsing {
template <class R, class W, class... AlternativeTypes, class ProcessorsType>
requires AreReaderAndWriter<R, W, rfl::Variant<AlternativeTypes...>>
requires AreReaderAndWriter<R, W, rfl::Variant<AlternativeTypes...>>
class Parser<R, W, rfl::Variant<AlternativeTypes...>, ProcessorsType> {
using ParentType = Parent<W>;
public:
using InputVarType = typename R::InputVarType;
static Result<rfl::Variant<AlternativeTypes...>> read(
const R& _r, const InputVarType& _var) noexcept {
if constexpr (internal::all_fields<std::tuple<AlternativeTypes...>>()) {
return FieldVariantParser<R, W, ProcessorsType,
AlternativeTypes...>::read(_r, _var);
if constexpr (schemaful::IsSchemafulReader<R>) {
using WrappedType = rfl::Variant<NamedTuple<AlternativeTypes>...>;
return Parser<R, W, WrappedType, ProcessorsType>::read(_r, _var)
.transform(
[](auto&& _variant) -> rfl::Variant<AlternativeTypes...> {
return std::move(_variant).visit([](auto&& _named_tuple) {
return rfl::Variant<AlternativeTypes...>(std::move(
std::move(_named_tuple).fields().template get<0>()));
});
});
} else {
return FieldVariantParser<R, W, ProcessorsType,
AlternativeTypes...>::read(_r, _var);
}
} else if constexpr (schemaful::IsSchemafulReader<R>) {
using V = schemaful::VariantReader<R, W, Variant<AlternativeTypes...>,
ProcessorsType, AlternativeTypes...>;
return _r.to_union(_var).and_then([&](const auto& _u) {
return _r.template read_union<Variant<AlternativeTypes...>, V>(_u);
});
} else if constexpr (ProcessorsType::add_tags_to_variants_) {
using FieldVariantType =
@@ -64,8 +89,34 @@ class Parser<R, W, rfl::Variant<AlternativeTypes...>, ProcessorsType> {
const rfl::Variant<AlternativeTypes...>& _variant,
const P& _parent) noexcept {
if constexpr (internal::all_fields<std::tuple<AlternativeTypes...>>()) {
FieldVariantParser<R, W, ProcessorsType, AlternativeTypes...>::write(
_w, _variant, _parent);
if constexpr (schemaful::IsSchemafulWriter<W>) {
using WrappedType = rfl::Variant<
NamedTuple<Field<AlternativeTypes::name_,
const typename AlternativeTypes::Type*>>...>;
const auto to_wrapped = [](const auto& _variant) -> WrappedType {
return _variant.visit([](const auto& _field) -> WrappedType {
return make_named_tuple(internal::to_ptr_field(_field));
});
};
Parser<R, W, WrappedType, ProcessorsType>::write(
_w, to_wrapped(_variant), _parent);
} else {
FieldVariantParser<R, W, ProcessorsType, AlternativeTypes...>::write(
_w, _variant, _parent);
}
} else if constexpr (schemaful::IsSchemafulWriter<W>) {
return rfl::visit(
[&](const auto& _v) {
using Type = std::remove_cvref_t<decltype(_v)>;
auto u = ParentType::add_union(_w, _parent);
using UnionType = typename ParentType::template Union<decltype(u)>;
auto p = UnionType{.index_ = static_cast<size_t>(_variant.index()),
.union_ = &u};
Parser<R, W, Type, ProcessorsType>::write(_w, _v, p);
},
_variant);
} else if constexpr (ProcessorsType::add_tags_to_variants_) {
using FieldVariantType =
+35 -13
View File
@@ -11,11 +11,14 @@
#include "Parent.hpp"
#include "Parser_base.hpp"
#include "schema/Type.hpp"
#include "schemaful/IsSchemafulReader.hpp"
#include "schemaful/IsSchemafulWriter.hpp"
#include "schemaful/SharedPtrReader.hpp"
namespace rfl::parsing {
template <class R, class W, class T, class ProcessorsType>
requires AreReaderAndWriter<R, W, std::shared_ptr<T>>
requires AreReaderAndWriter<R, W, std::shared_ptr<T>>
struct Parser<R, W, std::shared_ptr<T>, ProcessorsType> {
using InputVarType = typename R::InputVarType;
@@ -23,25 +26,44 @@ struct Parser<R, W, std::shared_ptr<T>, ProcessorsType> {
static Result<std::shared_ptr<T>> read(const R& _r,
const InputVarType& _var) noexcept {
if (_r.is_empty(_var)) {
return std::shared_ptr<T>();
if constexpr (schemaful::IsSchemafulReader<R>) {
using S = schemaful::SharedPtrReader<R, W, std::remove_cvref_t<T>,
ProcessorsType>;
const auto to_shared = [&](const auto& _u) -> Result<std::shared_ptr<T>> {
return _r.template read_union<std::shared_ptr<T>, S>(_u);
};
return _r.to_union(_var).and_then(to_shared);
} else {
if (_r.is_empty(_var)) {
return std::shared_ptr<T>();
}
return Parser<R, W, std::remove_cvref_t<T>, ProcessorsType>::read(_r,
_var)
.transform([](T&& _t) { return std::make_shared<T>(std::move(_t)); });
}
const auto to_ptr = [](auto&& _t) {
return std::make_shared<T>(std::move(_t));
};
return Parser<R, W, std::remove_cvref_t<T>, ProcessorsType>::read(_r, _var)
.transform(to_ptr);
}
template <class P>
static void write(const W& _w, const std::shared_ptr<T>& _s,
const P& _parent) noexcept {
if (!_s) {
ParentType::add_null(_w, _parent);
return;
if constexpr (schemaful::IsSchemafulWriter<W>) {
auto u = ParentType::add_union(_w, _parent);
using UnionType = typename ParentType::template Union<decltype(u)>;
auto p =
UnionType{.index_ = static_cast<size_t>(_s ? 0 : 1), .union_ = &u};
if (_s) {
Parser<R, W, std::remove_cvref_t<T>, ProcessorsType>::write(_w, *_s, p);
} else {
ParentType::add_null(_w, p);
}
} else {
if (_s) {
Parser<R, W, std::remove_cvref_t<T>, ProcessorsType>::write(_w, *_s,
_parent);
} else {
ParentType::add_null(_w, _parent);
}
}
Parser<R, W, std::remove_cvref_t<T>, ProcessorsType>::write(_w, *_s,
_parent);
}
static schema::Type to_schema(
+46 -27
View File
@@ -14,15 +14,16 @@
#include "TaggedUnionWrapper.hpp"
#include "is_tagged_union_wrapper.hpp"
#include "schema/Type.hpp"
#include "schemaful/IsSchemafulReader.hpp"
#include "schemaful/IsSchemafulWriter.hpp"
#include "tagged_union_wrapper_no_ptr.hpp"
namespace rfl {
namespace parsing {
namespace rfl::parsing {
template <class R, class W, internal::StringLiteral _discriminator,
class... AlternativeTypes, class ProcessorsType>
requires AreReaderAndWriter<R, W,
TaggedUnion<_discriminator, AlternativeTypes...>>
requires AreReaderAndWriter<R, W,
TaggedUnion<_discriminator, AlternativeTypes...>>
struct Parser<R, W, TaggedUnion<_discriminator, AlternativeTypes...>,
ProcessorsType> {
using ResultType = Result<TaggedUnion<_discriminator, AlternativeTypes...>>;
@@ -38,22 +39,32 @@ struct Parser<R, W, TaggedUnion<_discriminator, AlternativeTypes...>,
typename R::InputObjectType>;
static ResultType read(const R& _r, const InputVarType& _var) noexcept {
const auto get_disc =
[&_r](InputObjectOrArrayType _obj_or_arr) -> Result<std::string> {
return get_discriminator(_r, _obj_or_arr);
};
if constexpr (schemaful::IsSchemafulReader<R>) {
return Parser<R, W, Variant<AlternativeTypes...>, ProcessorsType>::read(
_r, _var)
.transform([](auto&& _variant) {
return TaggedUnion<_discriminator, AlternativeTypes...>(
std::move(_variant));
});
const auto to_result =
[&_r, _var](const std::string& _disc_value) -> ResultType {
return find_matching_alternative(
_r, _disc_value, _var,
std::make_integer_sequence<int, sizeof...(AlternativeTypes)>());
};
if constexpr (no_field_names_) {
return _r.to_array(_var).and_then(get_disc).and_then(to_result);
} else {
return _r.to_object(_var).and_then(get_disc).and_then(to_result);
const auto get_disc =
[&_r](InputObjectOrArrayType _obj_or_arr) -> Result<std::string> {
return get_discriminator(_r, _obj_or_arr);
};
const auto to_result =
[&_r, _var](const std::string& _disc_value) -> ResultType {
return find_matching_alternative(
_r, _disc_value, _var,
std::make_integer_sequence<int, sizeof...(AlternativeTypes)>());
};
if constexpr (no_field_names_) {
return _r.to_array(_var).and_then(get_disc).and_then(to_result);
} else {
return _r.to_object(_var).and_then(get_disc).and_then(to_result);
}
}
}
@@ -62,17 +73,26 @@ struct Parser<R, W, TaggedUnion<_discriminator, AlternativeTypes...>,
const W& _w,
const TaggedUnion<_discriminator, AlternativeTypes...>& _tagged_union,
const P& _parent) noexcept {
const auto handle = [&](const auto& _val) {
write_wrapped(_w, _val, _parent);
};
rfl::visit(handle, _tagged_union.variant_);
if constexpr (schemaful::IsSchemafulWriter<W>) {
Parser<R, W, Variant<AlternativeTypes...>, ProcessorsType>::write(
_w, _tagged_union.variant(), _parent);
} else {
rfl::visit([&](const auto& _val) { write_wrapped(_w, _val, _parent); },
_tagged_union.variant());
}
}
static schema::Type to_schema(
std::map<std::string, schema::Type>* _definitions) noexcept {
using VariantType = std::variant<std::invoke_result_t<
decltype(wrap_if_necessary<AlternativeTypes>), AlternativeTypes>...>;
return Parser<R, W, VariantType, ProcessorsType>::to_schema(_definitions);
if constexpr (schemaful::IsSchemafulReader<R> &&
schemaful::IsSchemafulWriter<W>) {
return Parser<R, W, Variant<AlternativeTypes...>,
ProcessorsType>::to_schema(_definitions);
} else {
using VariantType = std::variant<std::invoke_result_t<
decltype(wrap_if_necessary<AlternativeTypes>), AlternativeTypes>...>;
return Parser<R, W, VariantType, ProcessorsType>::to_schema(_definitions);
}
}
private:
@@ -215,7 +235,6 @@ struct Parser<R, W, TaggedUnion<_discriminator, AlternativeTypes...>,
}
};
} // namespace parsing
} // namespace rfl
} // namespace rfl::parsing
#endif
+35 -13
View File
@@ -11,12 +11,15 @@
#include "Parent.hpp"
#include "Parser_base.hpp"
#include "schema/Type.hpp"
#include "schemaful/IsSchemafulReader.hpp"
#include "schemaful/IsSchemafulWriter.hpp"
#include "schemaful/UniquePtrReader.hpp"
namespace rfl {
namespace parsing {
template <class R, class W, class T, class ProcessorsType>
requires AreReaderAndWriter<R, W, std::unique_ptr<T>>
requires AreReaderAndWriter<R, W, std::unique_ptr<T>>
struct Parser<R, W, std::unique_ptr<T>, ProcessorsType> {
using InputVarType = typename R::InputVarType;
@@ -24,25 +27,44 @@ struct Parser<R, W, std::unique_ptr<T>, ProcessorsType> {
static Result<std::unique_ptr<T>> read(const R& _r,
const InputVarType& _var) noexcept {
if (_r.is_empty(_var)) {
return std::unique_ptr<T>();
if constexpr (schemaful::IsSchemafulReader<R>) {
using S = schemaful::UniquePtrReader<R, W, std::remove_cvref_t<T>,
ProcessorsType>;
const auto to_unique = [&](const auto& _u) -> Result<std::unique_ptr<T>> {
return _r.template read_union<std::unique_ptr<T>, S>(_u);
};
return _r.to_union(_var).and_then(to_unique);
} else {
if (_r.is_empty(_var)) {
return std::unique_ptr<T>();
}
return Parser<R, W, std::remove_cvref_t<T>, ProcessorsType>::read(_r,
_var)
.transform([](T&& _t) { return std::make_unique<T>(std::move(_t)); });
}
const auto to_ptr = [](auto&& _t) {
return std::make_unique<T>(std::move(_t));
};
return Parser<R, W, std::remove_cvref_t<T>, ProcessorsType>::read(_r, _var)
.transform(to_ptr);
}
template <class P>
static void write(const W& _w, const std::unique_ptr<T>& _s,
const P& _parent) noexcept {
if (!_s) {
ParentType::add_null(_w, _parent);
return;
if constexpr (schemaful::IsSchemafulWriter<W>) {
auto u = ParentType::add_union(_w, _parent);
using UnionType = typename ParentType::template Union<decltype(u)>;
auto p =
UnionType{.index_ = static_cast<size_t>(_s ? 0 : 1), .union_ = &u};
if (_s) {
Parser<R, W, std::remove_cvref_t<T>, ProcessorsType>::write(_w, *_s, p);
} else {
ParentType::add_null(_w, p);
}
} else {
if (_s) {
Parser<R, W, std::remove_cvref_t<T>, ProcessorsType>::write(_w, *_s,
_parent);
} else {
ParentType::add_null(_w, _parent);
}
}
Parser<R, W, std::remove_cvref_t<T>, ProcessorsType>::write(_w, *_s,
_parent);
}
static schema::Type to_schema(
+79 -21
View File
@@ -6,41 +6,69 @@
#include <type_traits>
#include <variant>
#include "../NamedTuple.hpp"
#include "../Ref.hpp"
#include "../Result.hpp"
#include "../Variant.hpp"
#include "../always_false.hpp"
#include "../internal/to_ptr_field.hpp"
#include "FieldVariantParser.hpp"
#include "Parent.hpp"
#include "Parser_base.hpp"
#include "VariantAlternativeWrapper.hpp"
#include "schema/Type.hpp"
#include "schemaful/IsSchemafulReader.hpp"
#include "schemaful/IsSchemafulWriter.hpp"
#include "schemaful/VariantReader.hpp"
#include "to_single_error_message.hpp"
namespace rfl::parsing {
template <class R, class W, class... AlternativeTypes, class ProcessorsType>
requires AreReaderAndWriter<R, W, std::variant<AlternativeTypes...>>
requires AreReaderAndWriter<R, W, std::variant<AlternativeTypes...>>
class Parser<R, W, std::variant<AlternativeTypes...>, ProcessorsType> {
template <class T>
using ptr_field_t =
decltype(internal::to_ptr_field(std::declval<const T&>()));
using ParentType = Parent<W>;
public:
using InputVarType = typename R::InputVarType;
static Result<std::variant<AlternativeTypes...>> read(
const R& _r, const InputVarType& _var) noexcept {
if constexpr (internal::all_fields<std::tuple<AlternativeTypes...>>()) {
const auto wrap = [](auto&& _v) {
return std::variant<AlternativeTypes...>(std::move(_v));
};
const auto to_std_variant = [&](auto&& _v) {
return rfl::visit(wrap, std::move(_v));
};
return FieldVariantParser<R, W, ProcessorsType,
AlternativeTypes...>::read(_r, _var)
.transform(to_std_variant);
if constexpr (schemaful::IsSchemafulReader<R>) {
using WrappedType = rfl::Variant<NamedTuple<AlternativeTypes>...>;
return Parser<R, W, WrappedType, ProcessorsType>::read(_r, _var)
.transform(
[](auto&& _variant) -> std::variant<AlternativeTypes...> {
return std::move(_variant).visit([](auto&& _named_tuple) {
return std::variant<AlternativeTypes...>(std::move(
std::move(_named_tuple).fields().template get<0>()));
});
});
} else {
const auto wrap = [](auto&& _v) {
return std::variant<AlternativeTypes...>(std::move(_v));
};
const auto to_std_variant = [&](auto&& _v) {
return rfl::visit(wrap, std::move(_v));
};
return FieldVariantParser<R, W, ProcessorsType,
AlternativeTypes...>::read(_r, _var)
.transform(to_std_variant);
}
} else if constexpr (schemaful::IsSchemafulReader<R>) {
using V =
schemaful::VariantReader<R, W, std::variant<AlternativeTypes...>,
ProcessorsType, AlternativeTypes...>;
return _r.to_union(_var).and_then([&](const auto& _u) {
return _r.template read_union<std::variant<AlternativeTypes...>, V>(_u);
});
} else if constexpr (ProcessorsType::add_tags_to_variants_) {
using FieldVariantType =
@@ -78,17 +106,47 @@ class Parser<R, W, std::variant<AlternativeTypes...>, ProcessorsType> {
const std::variant<AlternativeTypes...>& _variant,
const P& _parent) noexcept {
if constexpr (internal::all_fields<std::tuple<AlternativeTypes...>>()) {
const auto wrap = [](const auto& _v) {
return rfl::Variant<ptr_field_t<AlternativeTypes>...>(
internal::to_ptr_field(_v));
};
const auto to_rfl_variant = [&](const auto& _v) {
return std::visit(wrap, _v);
};
FieldVariantParser<
R, W, ProcessorsType,
ptr_field_t<AlternativeTypes>...>::write(_w, to_rfl_variant(_variant),
_parent);
if constexpr (schemaful::IsSchemafulWriter<W>) {
using WrappedType = rfl::Variant<
NamedTuple<Field<AlternativeTypes::name_,
const typename AlternativeTypes::Type*>>...>;
const auto to_wrapped = [](const auto& _variant) -> WrappedType {
return std::visit(
[](const auto& _field) -> WrappedType {
return make_named_tuple(internal::to_ptr_field(_field));
},
_variant);
};
Parser<R, W, WrappedType, ProcessorsType>::write(
_w, to_wrapped(_variant), _parent);
} else {
const auto wrap = [](const auto& _v) {
return rfl::Variant<ptr_field_t<AlternativeTypes>...>(
internal::to_ptr_field(_v));
};
const auto to_rfl_variant = [&](const auto& _v) {
return std::visit(wrap, _v);
};
FieldVariantParser<
R, W, ProcessorsType,
ptr_field_t<AlternativeTypes>...>::write(_w,
to_rfl_variant(_variant),
_parent);
}
} else if constexpr (schemaful::IsSchemafulWriter<W>) {
return std::visit(
[&](const auto& _v) {
using Type = std::remove_cvref_t<decltype(_v)>;
auto u = ParentType::add_union(_w, _parent);
using UnionType = typename ParentType::template Union<decltype(u)>;
auto p = UnionType{.index_ = static_cast<size_t>(_variant.index()),
.union_ = &u};
Parser<R, W, Type, ProcessorsType>::write(_w, _v, p);
},
_variant);
} else if constexpr (ProcessorsType::add_tags_to_variants_) {
using FieldVariantType =
rfl::Variant<VariantAlternativeWrapper<const AlternativeTypes*>...>;
@@ -0,0 +1,35 @@
#ifndef RFL_PARSING_SUPPORTSTAGGEDUNIONS_HPP_
#define RFL_PARSING_SUPPORTSTAGGEDUNIONS_HPP_
#include <array>
#include <concepts>
#include <cstdint>
#include <functional>
#include <optional>
#include <string>
#include <string_view>
#include "../Result.hpp"
#include "../internal/is_basic_type.hpp"
#include "../internal/wrap_in_rfl_array_t.hpp"
namespace rfl::parsing {
template <class R>
concept SupportsTaggedUnions = requires(
R r, std::string name, typename R::InputArrayType arr,
typename R::InputObjectType obj, typename R::InputVarType var, size_t idx) {
/// Retrieves a particular field from an array.
{
r.get_field_from_array(idx, arr)
} -> std::same_as<rfl::Result<typename R::InputVarType>>;
/// Retrieves a particular field from an object.
{
r.get_field_from_object(name, obj)
} -> std::same_as<rfl::Result<typename R::InputVarType>>;
};
} // namespace rfl::parsing
#endif
+51 -27
View File
@@ -1,7 +1,6 @@
#ifndef RFL_PARSING_TUPLEPARSER_HPP_
#define RFL_PARSING_TUPLEPARSER_HPP_
#include <bit>
#include <cstddef>
#include <map>
#include <type_traits>
@@ -16,6 +15,10 @@
#include "TupleReader.hpp"
#include "call_destructors_on_tuple_where_necessary.hpp"
#include "schema/Type.hpp"
#include "schemaful/IsSchemafulReader.hpp"
#include "schemaful/IsSchemafulWriter.hpp"
#include "schemaful/tuple_to_named_tuple.hpp"
#include "schemaful/tuple_to_named_tuple_t.hpp"
namespace rfl::parsing {
@@ -31,38 +34,59 @@ struct TupleParser {
static Result<TupleType> read(const R& _r,
const InputVarType& _var) noexcept {
const auto parse = [&](const InputArrayType& _arr) -> Result<TupleType> {
alignas(TupleType) unsigned char buf[sizeof(TupleType)]{};
auto ptr = internal::ptr_cast<TupleType*>(&buf);
const auto tuple_reader =
TupleReader<R, W, TupleType, _ignore_empty_containers, _all_required,
ProcessorsType>(&_r, ptr);
auto err = _r.read_array(tuple_reader, _arr);
if (err) {
call_destructors_on_tuple_where_necessary(tuple_reader.num_set(), ptr);
return *err;
}
err = tuple_reader.handle_missing_fields();
if (err) {
call_destructors_on_tuple_where_necessary(tuple_reader.num_set(), ptr);
return *err;
}
auto res = Result<TupleType>(std::move(*ptr));
call_destructors_on_tuple_where_necessary(tuple_reader.num_set(), ptr);
return res;
};
if constexpr (schemaful::IsSchemafulReader<R>) {
using NamedTupleType = schemaful::tuple_to_named_tuple_t<TupleType>;
const auto to_tuple = [](auto&& _named_tuple) {
return [&]<int... _is>(std::integer_sequence<int, _is...>) {
return TupleType(std::move(rfl::get<_is>(_named_tuple))...);
}(std::make_integer_sequence<int, NamedTupleType::size()>());
};
return Parser<R, W, NamedTupleType, ProcessorsType>::read(_r, _var)
.transform(to_tuple);
return _r.to_array(_var).and_then(parse);
} else {
const auto parse = [&](const InputArrayType& _arr) -> Result<TupleType> {
alignas(TupleType) unsigned char buf[sizeof(TupleType)];
auto ptr = internal::ptr_cast<TupleType*>(&buf);
const auto tuple_reader =
TupleReader<R, W, TupleType, _ignore_empty_containers,
_all_required, ProcessorsType>(&_r, ptr);
auto err = _r.read_array(tuple_reader, _arr);
if (err) {
call_destructors_on_tuple_where_necessary(tuple_reader.num_set(),
ptr);
return *err;
}
err = tuple_reader.handle_missing_fields();
if (err) {
call_destructors_on_tuple_where_necessary(tuple_reader.num_set(),
ptr);
return *err;
}
auto res = Result<TupleType>(std::move(*ptr));
call_destructors_on_tuple_where_necessary(tuple_reader.num_set(), ptr);
return res;
};
return _r.to_array(_var).and_then(parse);
}
}
template <class P>
static void write(const W& _w, const TupleType& _tup,
const P& _parent) noexcept {
constexpr auto size = rfl::tuple_size_v<TupleType>;
auto arr = ParentType::add_array(_w, size, _parent);
const auto new_parent = typename ParentType::Array{&arr};
to_array(_w, _tup, new_parent, std::make_integer_sequence<int, size>());
_w.end_array(&arr);
if constexpr (schemaful::IsSchemafulWriter<W>) {
const auto named_tuple = schemaful::tuple_to_named_tuple(_tup);
Parser<R, W, std::remove_cvref_t<decltype(named_tuple)>,
ProcessorsType>::write(_w, named_tuple, _parent);
} else {
constexpr auto size = rfl::tuple_size_v<TupleType>;
auto arr = ParentType::add_array(_w, size, _parent);
const auto new_parent = typename ParentType::Array{&arr};
to_array(_w, _tup, new_parent, std::make_integer_sequence<int, size>());
_w.end_array(&arr);
}
}
static schema::Type to_schema(
+9 -5
View File
@@ -27,7 +27,7 @@ namespace parsing {
/// but also includes map-like types, when the key is not of type
/// std::string.
template <class R, class W, class VecType, class ProcessorsType>
requires AreReaderAndWriter<R, W, VecType>
requires AreReaderAndWriter<R, W, VecType>
struct VectorParser {
public:
using InputArrayType = typename R::InputArrayType;
@@ -85,10 +85,14 @@ struct VectorParser {
/// Generates a schema for the underlying type.
static schema::Type to_schema(
std::map<std::string, schema::Type>* _definitions) {
using Type = schema::Type;
return Type{Type::TypedArray{
.type_ = Ref<Type>::make(
Parser<R, W, T, ProcessorsType>::to_schema(_definitions))}};
if constexpr (treat_as_map()) {
return MapParser<R, W, VecType, ProcessorsType>::to_schema(_definitions);
} else {
using Type = schema::Type;
return Type{Type::TypedArray{
.type_ = Ref<Type>::make(
Parser<R, W, T, ProcessorsType>::to_schema(_definitions))}};
}
}
private:
+34 -8
View File
@@ -12,6 +12,7 @@
#include "../Tuple.hpp"
#include "../internal/is_array.hpp"
#include "Parser_base.hpp"
#include "schemaful/IsSchemafulReader.hpp"
namespace rfl::parsing {
@@ -35,10 +36,28 @@ class ViewReader {
std::make_integer_sequence<int, size_>());
}
/// Assigns the parsed version of _var to the field signified by _index, if
/// such a field exists in the underlying view.
/// Note that schemaful formats can assign by index.
void read(const int _index, const InputVarType& _var) const {
assign_to_matching_field(*r_, _index, _var, view_, errors_, found_, set_,
std::make_integer_sequence<int, size_>());
}
private:
template <int i, class FieldType>
static bool is_matching(const int _current_index) {
return _current_index == i;
}
template <int i, class FieldType>
static bool is_matching(const std::string_view& _current_name) {
return _current_name == FieldType::name();
}
template <int i>
static void assign_if_field_matches(const R& _r,
const std::string_view& _current_name,
const auto _current_name_or_index,
const auto& _var, auto* _view,
auto* _errors, auto* _found, auto* _set,
bool* _already_assigned) {
@@ -48,7 +67,7 @@ class ViewReader {
std::remove_cvref_t<std::remove_pointer_t<typename FieldType::Type>>;
constexpr auto name = FieldType::name();
if (!(*_already_assigned) && !std::get<i>(*_found) &&
_current_name == name) {
is_matching<i, FieldType>(_current_name_or_index)) {
std::get<i>(*_found) = true;
*_already_assigned = true;
auto res = Parser<R, W, T, ProcessorsType>::read(_r, _var);
@@ -96,26 +115,33 @@ class ViewReader {
template <int... is>
static void assign_to_matching_field(const R& _r,
const std::string_view& _current_name,
const auto _current_name_or_index,
const auto& _var, auto* _view,
auto* _errors, auto* _found, auto* _set,
std::integer_sequence<int, is...>) {
bool already_assigned = false;
(assign_if_field_matches<is>(_r, _current_name, _var, _view, _errors,
_found, _set, &already_assigned),
(assign_if_field_matches<is>(_r, _current_name_or_index, _var, _view,
_errors, _found, _set, &already_assigned),
...);
if constexpr (ViewType::pos_extra_fields() != -1) {
static_assert(!schemaful::IsSchemafulReader<R>,
"rfl::ExtraFields are not supported for schemaful formats, "
"because schemaful formats cannot have extra fields.");
constexpr int pos = ViewType::pos_extra_fields();
if (!already_assigned) {
assign_to_extra_fields<pos>(_r, _current_name, _var, _view, _errors,
_found, _set);
assign_to_extra_fields<pos>(_r, _current_name_or_index, _var, _view,
_errors, _found, _set);
}
} else if constexpr (ProcessorsType::no_extra_fields_) {
static_assert(
!schemaful::IsSchemafulReader<R>,
"Passing rfl::NoExtraFields to a schemaful format does not make "
"sense, because schemaful formats cannot have extra fields.");
if (!already_assigned) {
std::stringstream stream;
stream << "Value named '" << _current_name
stream << "Value named '" << _current_name_or_index
<< "' not used. Remove the rfl::NoExtraFields processor or add "
"rfl::ExtraFields to avoid this error message.";
_errors->emplace_back(Error(stream.str()));
+8 -6
View File
@@ -2,11 +2,11 @@
#define RFL_PARSING_SCHEMA_TYPE_HPP_
#include <cstddef>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "../../Object.hpp"
#include "../../Ref.hpp"
#include "../../Variant.hpp"
#include "ValidationType.hpp"
@@ -16,6 +16,8 @@ namespace rfl::parsing::schema {
struct Type {
struct Boolean {};
struct Bytestring {};
struct Int32 {};
struct Int64 {};
@@ -51,7 +53,7 @@ struct Type {
};
struct Object {
std::map<std::string, Type> types_;
rfl::Object<Type> types_;
std::shared_ptr<Type> additional_properties_;
};
@@ -86,10 +88,10 @@ struct Type {
};
using VariantType =
rfl::Variant<Boolean, Int32, Int64, UInt32, UInt64, Integer, Float,
Double, String, AnyOf, Description, FixedSizeTypedArray,
Literal, Object, Optional, Reference, StringMap, Tuple,
TypedArray, Validated>;
rfl::Variant<Boolean, Bytestring, Int32, Int64, UInt32, UInt64, Integer,
Float, Double, String, AnyOf, Description,
FixedSizeTypedArray, Literal, Object, Optional, Reference,
StringMap, Tuple, TypedArray, Validated>;
Type();
@@ -0,0 +1,63 @@
#ifndef RFL_PARSING_SCHEMAFUL_ISSCHEMAFULREADER_HPP_
#define RFL_PARSING_SCHEMAFUL_ISSCHEMAFULREADER_HPP_
#include <concepts>
#include <string>
#include <variant>
namespace rfl::parsing::schemaful {
using MockVariantType = std::variant<std::string, int>;
template <class R>
struct MockMapReader {
void read(const std::string_view&, typename R::InputVarType&) const {}
};
template <class R>
struct MockObjectReader {
void read(const int, typename R::InputVarType&) const {}
};
template <class R>
struct MockUnionReader {
static rfl::Result<MockVariantType> read(const R&, const size_t,
typename R::InputVarType&) {
return Error("This is a mock type.");
}
};
template <class R>
concept IsSchemafulReader =
requires(R r, typename R::InputVarType var, typename R::InputObjectType obj,
typename R::InputMapType m, typename R::InputUnionType u,
MockMapReader<R> map_reader, MockObjectReader<R> object_reader) {
/// A schemaful reader needs to differentiate between objects, for which
/// the field names are known at compile time and maps, for which the
/// field names are not known at compile time.
{ r.read_map(map_reader, m) } -> std::same_as<std::optional<Error>>;
/// A schemaful reader can read fields by order and does not have to
/// compare strings - the correct order of the fields is guaranteed by the
/// schema.
{
r.read_object(object_reader, obj)
} -> std::same_as<std::optional<Error>>;
/// A schemaful reader needs an explicit union type.
{
r.template read_union<MockVariantType, MockUnionReader<R>>(u)
} -> std::same_as<rfl::Result<MockVariantType>>;
/// It needs to be possible to transform variables to maps.
{ r.to_map(var) } -> std::same_as<rfl::Result<typename R::InputMapType>>;
/// It needs to be possible to transform variables to unions.
{
r.to_union(var)
} -> std::same_as<rfl::Result<typename R::InputUnionType>>;
};
} // namespace rfl::parsing::schemaful
#endif
@@ -0,0 +1,130 @@
#ifndef RFL_PARSING_SCHEMAFUL_ISSCHEMAFULWRITER_HPP_
#define RFL_PARSING_SCHEMAFUL_ISSCHEMAFULWRITER_HPP_
#include <concepts>
#include <string>
#include <string_view>
#include <variant>
namespace rfl::parsing::schemaful {
template <class W>
concept IsSchemafulWriter = requires(
W w, typename W::OutputVarType var, typename W::OutputArrayType arr,
typename W::OutputMapType m, typename W::OutputObjectType obj,
typename W::OutputUnionType u, size_t index, size_t size,
std::string_view name, std::string val) {
/// A schemaful writer needs to know two additional types:
/// 1) Maps - unlike objects, their field names are not known at compile time.
/// 2) Unions - schemaful formats need explicit union types.
/// Sets an empty map as the root element of the document.
/// Some serialization formats require you to pass the expected size in
/// advance. If you are not working with such a format, you can ignore the
/// parameter `size`. Returns the new array for further modification.
{ w.map_as_root(size) } -> std::same_as<typename W::OutputMapType>;
/// Sets an empty union as the root element of the document.
{ w.union_as_root() } -> std::same_as<typename W::OutputUnionType>;
/// Adds an empty array to an existing map. Returns the new
/// array for further modification.
{
w.add_array_to_map(name, size, &m)
} -> std::same_as<typename W::OutputArrayType>;
/// Adds an empty array to an existing union.
/// The index refers to the index of the element in the union.
/// Returns the new array for further modification.
{
w.add_array_to_union(index, size, &u)
} -> std::same_as<typename W::OutputArrayType>;
/// Adds an empty map to an existing array. Returns the new
/// map for further modification.
{ w.add_map_to_array(size, &arr) } -> std::same_as<typename W::OutputMapType>;
/// Adds an empty map to an existing map. The key or name of the field
/// is signified by `name`. Returns the new map for further modification.
{
w.add_map_to_map(name, size, &m)
} -> std::same_as<typename W::OutputMapType>;
/// Adds an empty map to an existing object. The key or name of the field
/// is signified by `name`. Returns the new map for further modification.
{
w.add_map_to_object(name, size, &obj)
} -> std::same_as<typename W::OutputMapType>;
/// Adds an empty map to an existing union.
/// The index refers to the index of the element in the union.
/// Returns the new map for further modification.
{
w.add_map_to_union(index, size, &u)
} -> std::same_as<typename W::OutputMapType>;
/// Adds an empty object to an existing map. The key or name of the field
/// is signified by `name`. Returns the new object for further modification.
{
w.add_object_to_map(name, size, &m)
} -> std::same_as<typename W::OutputObjectType>;
/// Adds an empty object to an existing union.
/// The index refers to the index of the element in the union.
/// Returns the new object for further modification.
{
w.add_object_to_union(index, size, &u)
} -> std::same_as<typename W::OutputObjectType>;
/// Adds an empty union to an existing array. Returns the new
/// union for further modification.
{ w.add_union_to_array(&arr) } -> std::same_as<typename W::OutputUnionType>;
/// Adds an empty union to an existing map. The key or name of the field
/// is signified by `name`. Returns the new union for further modification.
{ w.add_union_to_map(name, &m) } -> std::same_as<typename W::OutputUnionType>;
/// Adds an empty union to an existing object. The key or name of the field
/// is signified by `name`. Returns the new union for further modification.
{
w.add_union_to_object(name, &obj)
} -> std::same_as<typename W::OutputUnionType>;
/// Adds an empty union to an existing union.
/// The index refers to the index of the element in the union.
/// Returns the new union for further modification.
{
w.add_union_to_union(index, &u)
} -> std::same_as<typename W::OutputUnionType>;
/// Adds a null value to a map. Returns an
/// OutputVarType containing the null value.
{ w.add_null_to_map(name, &m) } -> std::same_as<typename W::OutputVarType>;
/// Adds a basic value (bool, numeric, string) to an existing map. The key
/// or name of the field is signified by `name`. Returns an
/// OutputVarType containing the new value.
{
w.add_value_to_map(name, val, &m)
} -> std::same_as<typename W::OutputVarType>;
/// Adds a null value to a union. Returns an
/// OutputVarType containing the null value.
{ w.add_null_to_union(index, &u) } -> std::same_as<typename W::OutputVarType>;
/// Adds a basic value (bool, numeric, string) to an existing union. The key
/// or name of the field is signified by `name`. Returns an
/// OutputVarType containing the new value.
{
w.add_value_to_union(index, val, &u)
} -> std::same_as<typename W::OutputVarType>;
/// Signifies to the writer that we do not want to add any further elements to
/// this map. Some serialization formats require this. If you are working
/// with a serialization format that doesn't, just leave the function empty.
{ w.end_map(&m) } -> std::same_as<void>;
};
} // namespace rfl::parsing::schemaful
#endif
@@ -0,0 +1,25 @@
#ifndef RFL_PARSING_SCHEMAFUL_OPTIONALREADER_HPP_
#define RFL_PARSING_SCHEMAFUL_OPTIONALREADER_HPP_
#include <optional>
#include <type_traits>
#include "../../Result.hpp"
namespace rfl::parsing::schemaful {
template <class R, class W, class T, class ProcessorsType>
struct OptionalReader {
static Result<std::optional<T>> read(
const R& _r, const size_t _index,
const typename R::InputVarType& _var) noexcept {
if (_index == 1) {
return std::optional<T>();
}
return Parser<R, W, std::remove_cvref_t<T>, ProcessorsType>::read(_r, _var);
}
};
} // namespace rfl::parsing::schemaful
#endif
@@ -0,0 +1,26 @@
#ifndef RFL_PARSING_SCHEMAFUL_SHAREDPTRREADER_HPP_
#define RFL_PARSING_SCHEMAFUL_SHAREDPTRREADER_HPP_
#include <memory>
#include <type_traits>
#include "../../Result.hpp"
namespace rfl::parsing::schemaful {
template <class R, class W, class T, class ProcessorsType>
struct SharedPtrReader {
static Result<std::shared_ptr<T>> read(
const R& _r, const size_t _index,
const typename R::InputVarType& _var) noexcept {
if (_index == 1) {
return std::shared_ptr<T>();
}
return Parser<R, W, std::remove_cvref_t<T>, ProcessorsType>::read(_r, _var)
.transform([](T&& _t) { return std::make_shared<T>(std::move(_t)); });
}
};
} // namespace rfl::parsing::schemaful
#endif
@@ -0,0 +1,26 @@
#ifndef RFL_PARSING_SCHEMAFUL_UNIQUEPTRREADER_HPP_
#define RFL_PARSING_SCHEMAFUL_UNIQUEPTRREADER_HPP_
#include <memory>
#include <type_traits>
#include "../../Result.hpp"
namespace rfl::parsing::schemaful {
template <class R, class W, class T, class ProcessorsType>
struct UniquePtrReader {
static Result<std::unique_ptr<T>> read(
const R& _r, const size_t _index,
const typename R::InputVarType& _var) noexcept {
if (_index == 1) {
return std::unique_ptr<T>();
}
return Parser<R, W, std::remove_cvref_t<T>, ProcessorsType>::read(_r, _var)
.transform([](T&& _t) { return std::make_unique<T>(std::move(_t)); });
}
};
} // namespace rfl::parsing::schemaful
#endif
@@ -0,0 +1,44 @@
#ifndef RFL_PARSING_SCHEMAFUL_VARIANTREADER_HPP_
#define RFL_PARSING_SCHEMAFUL_VARIANTREADER_HPP_
#include <type_traits>
#include <utility>
#include "../../Result.hpp"
#include "../../internal/nth_element_t.hpp"
namespace rfl::parsing::schemaful {
template <class R, class W, class VariantType, class ProcessorsType,
class... AlternativeTypes>
class VariantReader {
public:
static Result<VariantType> read(
const R& _r, const size_t _index,
const typename R::InputVarType& _var) noexcept {
return [&]<size_t... _is>(std::integer_sequence<size_t, _is...>) {
Result<VariantType> result =
Error("Could not parse union: Index out of bounds.");
(try_one_type<_is>(_r, _index, _var, &result), ...);
return result;
}(std::make_integer_sequence<size_t, sizeof...(AlternativeTypes)>());
}
private:
template <size_t _i>
static void try_one_type(const R& _r, const size_t _index,
const typename R::InputVarType& _var,
Result<VariantType>* _result) noexcept {
if (_index == _i) {
using T = internal::nth_element_t<_i, AlternativeTypes...>;
*_result =
Parser<R, W, std::remove_cvref_t<T>, ProcessorsType>::read(_r, _var)
.transform(
[](auto&& _val) -> VariantType { return std::move(_val); });
}
}
};
} // namespace rfl::parsing::schemaful
#endif
@@ -0,0 +1,53 @@
#ifndef RFL_PARSING_SCHEMAFUL_TUPLETONAMEDTUPLE_HPP_
#define RFL_PARSING_SCHEMAFUL_TUPLETONAMEDTUPLE_HPP_
#include <tuple>
#include <type_traits>
#include <utility>
#include "../../Field.hpp"
#include "../../Tuple.hpp"
#include "../../internal/StringLiteral.hpp"
#include "../../make_named_tuple.hpp"
namespace rfl::parsing::schemaful {
template <int _i>
consteval auto to_field_name() {
return internal::StringLiteral<5>('f',
static_cast<char>('0' + ((_i / 100) % 10)),
static_cast<char>('0' + ((_i / 10) % 10)),
static_cast<char>('0' + (_i % 10)));
}
template <int _i>
auto to_field(const auto& _t) {
using T = std::remove_cvref_t<decltype(_t)>;
return rfl::Field<to_field_name<_i>(), const T*>(&_t);
}
/// Schemaful formats often don't have an explicit tuple representation.
/// This is the required workaround.
template <class... Ts>
auto tuple_to_named_tuple(const Tuple<Ts...>& _tup) {
static_assert(sizeof...(Ts) <= 1000,
"The tuple cannot contain more than 1000 elements.");
return [&]<int... _is>(std::integer_sequence<int, _is...>) {
return rfl::make_named_tuple(to_field<_is>(rfl::get<_is>(_tup))...);
}(std::make_integer_sequence<int, sizeof...(Ts)>());
}
/// Schemaful formats often don't have an explicit tuple representation.
/// This is the required workaround.
template <class... Ts>
auto tuple_to_named_tuple(const std::tuple<Ts...>& _tup) {
static_assert(sizeof...(Ts) <= 1000,
"The tuple cannot contain more than 1000 elements.");
return [&]<int... _is>(std::integer_sequence<int, _is...>) {
return rfl::make_named_tuple(to_field<_is>(std::get<_is>(_tup))...);
}(std::make_integer_sequence<int, sizeof...(Ts)>());
}
} // namespace rfl::parsing::schemaful
#endif
@@ -0,0 +1,48 @@
#ifndef RFL_PARSING_SCHEMAFUL_TUPLETONAMEDTUPLE_T_HPP_
#define RFL_PARSING_SCHEMAFUL_TUPLETONAMEDTUPLE_T_HPP_
#include <tuple>
#include <type_traits>
#include <utility>
#include "../../NamedTuple.hpp"
#include "../../Tuple.hpp"
#include "tuple_to_named_tuple.hpp"
namespace rfl::parsing::schemaful {
template <class IntegerSequence, class... Ts>
struct ToNamedTuple;
template <int... _is, class... Ts>
struct ToNamedTuple<std::integer_sequence<int, _is...>, Ts...> {
using Type = NamedTuple<Field<to_field_name<_is>(), Ts>...>;
};
template <class TupleType>
struct TupleToNamedTuple;
template <class... Ts>
struct TupleToNamedTuple<Tuple<Ts...>> {
using Type =
typename ToNamedTuple<std::make_integer_sequence<int, sizeof...(Ts)>,
Ts...>::Type;
};
template <class... Ts>
struct TupleToNamedTuple<std::tuple<Ts...>> {
using Type =
typename ToNamedTuple<std::make_integer_sequence<int, sizeof...(Ts)>,
Ts...>::Type;
};
/// Given
/// std::tuple<T1, T2, T3, ...> or rfl::Tuple<T1, T2, T3, ...>
/// return
/// NamedTuple<Field<"f000", T1>, Field<"f001", T2>, Field<"f002", T3>, ...>
template <class T>
using tuple_to_named_tuple_t = typename TupleToNamedTuple<T>::Type;
} // namespace rfl::parsing::schemaful
#endif
@@ -0,0 +1,28 @@
#ifndef RFL_PARSING_SCHEMAFUL_TUPLETOOBJECT_HPP_
#define RFL_PARSING_SCHEMAFUL_TUPLETOOBJECT_HPP_
#include <string>
#include "../schema/Type.hpp"
namespace rfl::parsing::schemaful {
std::string to_field_name(const size_t _i) {
return std::string({'f', static_cast<char>('0' + ((_i / 100) % 10)),
static_cast<char>('0' + ((_i / 10) % 10)),
static_cast<char>('0' + (_i % 10))});
}
/// Schemaful formats often don't have an explicit tuple representation.
/// This is the required workaround.
schema::Type::Object tuple_to_object(const schema::Type::Tuple& _tup) {
auto obj = schema::Type::Object{};
for (size_t i = 0; i < _tup.types_.size(); ++i) {
obj.types_[to_field_name(i)] = _tup.types_[i];
}
return obj;
}
} // namespace rfl::parsing::schemaful
#endif