Added generic elements; resolves #96 (#125)

This commit is contained in:
Dr. Patrick Urbanke (劉自成)
2024-06-27 23:05:48 +02:00
committed by GitHub
parent c3db8321b3
commit 28b89ae0df
23 changed files with 1012 additions and 39 deletions
+26
View File
@@ -313,6 +313,30 @@ This results in the following JSON string:
Other forms of tagging are supported as well. Refer to the [documentation](https://github.com/getml/reflect-cpp/tree/main/docs) for details.
## Extra fields
If you don't know all of your fields at compile time, no problem. Just use `rfl::ExtraFields`:
```cpp
struct Person {
std::string first_name;
std::string last_name = "Simpson";
rfl::ExtraFields<rfl::Generic> extra_fields;
};
auto homer = Person{.first_name = "Homer"};
homer.extra_fields["age"] = 45;
homer.extra_fields["email"] = "homer@simpson.com";
homer.extra_fields["town"] = "Springfield";
```
This results in the following JSON string:
```json
{"firstName":"Homer","lastName":"Simpson","age":45,"email":"homer@simpson.com","town":"Springfield"}
```
## Reflective programming
Beyond serialization and deserialization, reflect-cpp also supports reflective programming in general.
@@ -445,8 +469,10 @@ reflect-cpp supports the following containers from the C++ standard library:
In addition, it supports the following custom containers:
- `rfl::Box`: Similar to `std::unique_ptr`, but (almost) guaranteed to never be null.
- `rfl::Generic`: A catch-all type that can represent (almost) anything.
- `rfl::Literal`: An explicitly enumerated string.
- `rfl::NamedTuple`: Similar to `std::tuple`, but with named fields that can be retrieved via their name at compile time.
- `rfl::Object`: A map-like type representing a object with field names that are unknown at compile time.
- `rfl::Ref`: Similar to `std::shared_ptr`, but (almost) guaranteed to never be null.
- `rfl::Result`: Allows for exception-free programming.
- `rfl::TaggedUnion`: Similar to `std::variant`, but with explicit tags that make parsing more efficient.
+28 -20
View File
@@ -44,42 +44,50 @@
2.5) [JSON schema](https://github.com/getml/reflect-cpp/blob/main/docs/json_schema.md) - For validating your schema before you even send it to your C++ backend.
## 3) Custom classes
## 3) Generic elements
3.1) [Custom classes](https://github.com/getml/reflect-cpp/blob/main/docs/custom_classes.md) - For custom classes with private fields.
3.1) [rfl::Object](https://github.com/getml/reflect-cpp/blob/main/docs/object.md) - A map-like type representing a object with field names that are unknown at compile time.
3.2) [Custom parsers for your classes](https://github.com/getml/reflect-cpp/blob/main/docs/custom_parser.md) - For custom classes with private fields that you want to leave absolutely untouched.
3.2) [rfl::Generic](https://github.com/getml/reflect-cpp/blob/main/docs/generic.md) - A catch-all type that can represent (almost) anything.
## 4) Useful helper functions and classes
3.3) [rfl::ExtraFields](https://github.com/getml/reflect-cpp/blob/main/docs/extra_fields.md) - For adding extra fields to your structs, the names of which are unknown at compile time.
4.1) [rfl::replace](https://github.com/getml/reflect-cpp/blob/main/docs/replace.md) - For replacing one or several fields in a struct.
## 4) Custom classes
4.2) [rfl::as](https://github.com/getml/reflect-cpp/blob/main/docs/as.md) - For casting structs as other structs.
4.1) [Custom classes](https://github.com/getml/reflect-cpp/blob/main/docs/custom_classes.md) - For custom classes with private fields.
4.3) [rfl::NamedTuple](https://github.com/getml/reflect-cpp/blob/main/docs/named_tuple.md) - For structural typing.
4.2) [Custom parsers for your classes](https://github.com/getml/reflect-cpp/blob/main/docs/custom_parser.md) - For custom classes with private fields that you want to leave absolutely untouched.
4.4) [rfl::to_view](https://github.com/getml/reflect-cpp/blob/main/docs/to_view.md) - For accessing fields of a struct by index or name.
## 5) Useful helper functions and classes
## 5) Supported formats
5.1) [rfl::replace](https://github.com/getml/reflect-cpp/blob/main/docs/replace.md) - For replacing one or several fields in a struct.
5.1) [JSON](https://github.com/getml/reflect-cpp/blob/main/docs/json.md)
5.2) [rfl::as](https://github.com/getml/reflect-cpp/blob/main/docs/as.md) - For casting structs as other structs.
5.2) [BSON](https://github.com/getml/reflect-cpp/blob/main/docs/bson.md)
5.3) [rfl::NamedTuple](https://github.com/getml/reflect-cpp/blob/main/docs/named_tuple.md) - For structural typing.
5.3) [CBOR](https://github.com/getml/reflect-cpp/blob/main/docs/cbor.md)
5.4) [rfl::to_view](https://github.com/getml/reflect-cpp/blob/main/docs/to_view.md) - For accessing fields of a struct by index or name.
5.4) [flexbuffers](https://github.com/getml/reflect-cpp/blob/main/docs/flexbuffers.md)
## 6) Supported formats
5.5) [msgpack](https://github.com/getml/reflect-cpp/blob/main/docs/msgpack.md)
6.1) [JSON](https://github.com/getml/reflect-cpp/blob/main/docs/json.md)
5.6) [TOML](https://github.com/getml/reflect-cpp/blob/main/docs/toml.md)
6.2) [BSON](https://github.com/getml/reflect-cpp/blob/main/docs/bson.md)
5.7) [XML](https://github.com/getml/reflect-cpp/blob/main/docs/xml.md)
6.3) [CBOR](https://github.com/getml/reflect-cpp/blob/main/docs/cbor.md)
5.8) [YAML](https://github.com/getml/reflect-cpp/blob/main/docs/yaml.md)
6.4) [flexbuffers](https://github.com/getml/reflect-cpp/blob/main/docs/flexbuffers.md)
## 6) Advanced topics
6.5) [msgpack](https://github.com/getml/reflect-cpp/blob/main/docs/msgpack.md)
6.1) [Supporting your own format](https://github.com/getml/reflect-cpp/blob/main/docs/supporting_your_own_format.md) - For supporting your own serialization and deserialization formats.
6.6) [TOML](https://github.com/getml/reflect-cpp/blob/main/docs/toml.md)
6.2) [Maintaining backwards compatability](https://github.com/getml/reflect-cpp/blob/main/docs/backwards_compatability.md) - Instructions on how to ensure that your API is backwards-compatible with older versions.
6.7) [XML](https://github.com/getml/reflect-cpp/blob/main/docs/xml.md)
6.8) [YAML](https://github.com/getml/reflect-cpp/blob/main/docs/yaml.md)
## 7) Advanced topics
7.1) [Supporting your own format](https://github.com/getml/reflect-cpp/blob/main/docs/supporting_your_own_format.md) - For supporting your own serialization and deserialization formats.
7.2) [Maintaining backwards compatability](https://github.com/getml/reflect-cpp/blob/main/docs/backwards_compatability.md) - Instructions on how to ensure that your API is backwards-compatible with older versions.
+58
View File
@@ -0,0 +1,58 @@
# `rfl::ExtraFields`
In some cases, you simply do not know all of the possible field names at compile time. You might know some, but you
do not know all of them.
Note that there are many ways of dealing with these kind of uncertainties, such as optional fields or tagged unions.
But in instance where the field names are absolutely not known in advance, you might want to use `rfl::ExtraFields`:
```cpp
struct Person {
std::string first_name;
std::string last_name = "Simpson";
rfl::ExtraFields<rfl::Generic> extra_fields;
};
auto homer = Person{.first_name = "Homer"};
homer.extra_fields["age"] = 45;
homer.extra_fields["email"] = "homer@simpson.com";
homer.extra_fields["town"] = "Springfield";
```
Note that `rfl::ExtraFields` inherits from `rfl::Object` and therefore behaves exactly like it. Refer
to the relevant section of the documentation on `rfl::Object`.
This will result in the following JSON string:
```json
{"first_name":"Homer","last_name":"Simpson","age":45,"email":"homer@simpson.com","town":"Springfield"}
```
Likewise, when we parse the JSON string, all of the fields that can't be directly matched to
a known field will be parsed into `extra_fields`.
Note that in this particular instance, we have set the type to `rfl::Generic`. But if we know in
advance that all of the extra fields must be strings, we can set it to `std::string` as well:
```cpp
struct Person {
std::string first_name;
std::string last_name = "Simpson";
rfl::ExtraFields<std::string> extra_fields;
};
auto homer = Person{.first_name = "Homer"};
homer.extra_fields["email"] = "homer@simpson.com";
homer.extra_fields["town"] = "Springfield";
```
This will result in the following JSON string:
```json
{"first_name":"Homer","last_name":"Simpson","email":"homer@simpson.com","town":"Springfield"}
```
If we add an extra field that is not a string (like `"age":45`), this will result in a parsing error.
+87
View File
@@ -0,0 +1,87 @@
# `rfl::Generic`
reflect-cpp is intended to be used to directly parse into structs. Doing this is more efficient, more convenient and also safer.
But in some cases, we simply cannot anticipate the complete structure of the data at compile time. For these cases, we
have `rfl::Generic`.
`rfl::Generic` is a convenience wrapper around the following type:
```cpp
std::variant<bool, int, double, std::string, Object, Array>;
```
`Object` and `Array` are defined as follows:
```cpp
using Array = std::vector<Generic>;
using Object = rfl::Object<Generic>;
```
In other words, `rfl::Generic` encompasses all types that can be expressed in JSON.
It can be used as follows:
```cpp
auto bart = rfl::Generic::Object();
bart["first_name"] = "Bart";
bart["last_name"] = "Simpson";
bart["age"] = 10;
auto lisa = rfl::Generic::Object();
lisa["first_name"] = "Lisa";
lisa["last_name"] = "Simpson";
lisa["age"] = 8;
auto maggie = rfl::Generic::Object();
maggie["first_name"] = "Lisa";
maggie["last_name"] = "Simpson";
maggie["age"] = 0;
auto homer = rfl::Generic::Object();
homer["first_name"] = "Homer";
homer["last_name"] = "Simpson";
homer["age"] = 45;
homer["children"] = rfl::Generic::Array({bart, lisa, maggie});
```
The resulting JSON strings looks as follows:
```json
{"first_name":"Homer","last_name":"Simpson","age":45,"children":[{"first_name":"Bart","last_name":"Simpson","age":10},{"first_name":"Lisa","last_name":"Simpson","age":8},{"first_name":"Lisa","last_name":"Simpson","age":0}]}
```
`rfl::Generic` contains some convenience methods that allow you to handle parsed data:
You can retrieve the underlying `std::variant` using `.get()`. This then allows you to handle allow possible six cases using the [visitor pattern](https://en.cppreference.com/w/cpp/utility/variant/visit).
If you have a guess what the types of a particular field might be, you can use any of the six convenience methods `.to_array()`, `.to_bool()`, `.to_double()`, `.to_int()`, `.to_object()`, `.to_string()`. Each
of these methods will return an `rfl::Result<...>` with the corresponding type, if the `rfl::Generic` does indeed contain such a type.
If you prefer, you can also use the following six convenience *functions*:
`rfl::to_array(...)`, `rfl::to_bool(...)`, `rfl::to_double(...)`, `rfl::to_int(...)`, `rfl::to_object(...)`, `rfl::to_string(...)`.
These functions are particularly useful for monadic error handling:
```cpp
auto homer = rfl::Generic::Object();
...
rfl::Result<int> age = homer.get("age").and_then(rfl::to_int);
```
In this particular instance, we know that `homer` is an `rfl::Generic::Object`. We assume that it has a field named `age` which we also assume is an integer.
In the end, we will get an `rfl::Result<int>` which will contain an integer, if both of our assumptions are correct and an error otherwise.
If we want to retrieve the age, we can use the `.value()` method:
```cpp
auto homer = rfl::Generic::Object();
...
int age = homer.get("age").and_then(rfl::to_int).value();
```
This will throw an exception if any of our assumptions are false.
Please refer to the part of the documentation on `rfl::Result` to learn more about monadic error handling.
+65
View File
@@ -0,0 +1,65 @@
# `rfl::Object`
`rfl::Object<...>` behaves similarly to `rfl::map<std::string, ...>` and `rfl::unordered_map<std::string, ...>`.
It will be represented in JSON or other formats as an object:
```cpp
auto bart = rfl::Object<std::string>();
bart["first_name"] = "Bart";
bart["last_name"] = "Simpson";
bart["town"] = "Springfield";
```
This is results in the following JSON string:
```cpp
{"first_name":"Bart","last_name":"Simpson","town":"Springfield"}
```
It supports almost all of the normal features you would expect from such a container. For instance,
you can iterate through it just like any other map:
```cpp
for (const auto& [k, v]: bart) {
std::cout << k << ": " << v << std::endl;
}
```
However, unlike these containers, the order of fields is preserved. It is also possible to have duplicate keys:
```cpp
auto bart = rfl::Object<std::string>();
bart["first_name"] = "Bart";
bart["last_name"] = "Simpson";
bart["town"] = "Springfield";
// Note that you need the .insert(...) method,
// because operator[] would overwrite the
// existing field.
bart.insert("first_name", "Lisa");
```
This results in the following JSON string:
```cpp
{"first_name":"Bart","last_name":"Simpson","town":"Springfield","first_name":"Lisa"}
```
There are three different ways of inserting fields:
- `operator[...]` creates a new field, if a field of this name doesn't already exist, and then assigns it.
- `.insert(...)` inserts a new field at the end, potentially creating duplicate field names. Much like `std::map`, it supports several types of inputs:
- `.insert(std::pair(key, value))`
- `.insert(key, value)`
- `.insert(begin, end)`, where `begin` and `end` are iterators of a container of key-value-pairs
- `.emplace(...)` is an alias for `.insert` that exists primarily for reasons of compatability with standard containers.
There are three different ways of accessing fields:
- `operator[...]` creates a new field, if a field of this name doesn't already exist.
- `.at(...)` throws an exception, if field of this name doesn't exist.
- `.get(...)` returns an `rfl::Result` wrapping the field, or an `rfl::Error` if the field doesn't exist.
Note that it is most efficient, if you access fields in the order that they were placed.
+3
View File
@@ -13,12 +13,15 @@
#include "rfl/Attribute.hpp"
#include "rfl/Box.hpp"
#include "rfl/Description.hpp"
#include "rfl/ExtraFields.hpp"
#include "rfl/Field.hpp"
#include "rfl/Flatten.hpp"
#include "rfl/Generic.hpp"
#include "rfl/Literal.hpp"
#include "rfl/NamedTuple.hpp"
#include "rfl/NoFieldNames.hpp"
#include "rfl/NoOptionals.hpp"
#include "rfl/Object.hpp"
#include "rfl/OneOf.hpp"
#include "rfl/Pattern.hpp"
#include "rfl/PatternValidator.hpp"
+15
View File
@@ -0,0 +1,15 @@
#ifndef RFL_EXTRAFIELDS_HPP_
#define RFL_EXTRAFIELDS_HPP_
#include "Object.hpp"
namespace rfl {
/// Used to embed additional fields for which the names cannot be known in
/// advance and can therefore not be encoded in the struct.
template <class T>
class ExtraFields : public Object<T> {};
} // namespace rfl
#endif
+181
View File
@@ -0,0 +1,181 @@
#ifndef RFL_GENERIC_HPP_
#define RFL_GENERIC_HPP_
#include <string>
#include <variant>
#include <vector>
#include "Object.hpp"
#include "Result.hpp"
namespace rfl {
class Generic {
public:
using Array = std::vector<Generic>;
using Object = rfl::Object<Generic>;
using ReflectionType =
std::variant<bool, int, double, std::string, Object, Array>;
Generic() : value_(false) {}
Generic(Generic&& _other) noexcept = default;
Generic(const Generic& _other) = default;
Generic(const ReflectionType& _value) : value_(_value) {}
Generic(ReflectionType&& _value) noexcept : value_(std::move(_value)) {}
template <class T,
typename std::enable_if<std::is_convertible_v<T, ReflectionType>,
bool>::type = true>
Generic(const T& _value) : value_(_value) {}
template <class T,
typename std::enable_if<std::is_convertible_v<T, ReflectionType>,
bool>::type = true>
Generic(T&& _value) noexcept : value_(std::forward<T>(_value)) {}
~Generic() = default;
/// Returns the underlying object.
const ReflectionType& get() const { return value_; }
/// Assigns the underlying object.
auto& operator=(const ReflectionType& _value) {
value_ = _value;
return *this;
}
/// Assigns the underlying object.
auto& operator=(ReflectionType&& _value) noexcept {
value_ = std::move(_value);
return *this;
}
/// Assigns the underlying object.
template <class T,
typename std::enable_if<std::is_convertible_v<T, ReflectionType>,
bool>::type = true>
auto& operator=(const T& _value) {
value_ = _value;
return *this;
}
/// Assigns the underlying object.
Generic& operator=(const Generic& _other) = default;
/// Assigns the underlying object.
Generic& operator=(Generic&& _other) = default;
/// Returns the underlying object, necessary for the serialization to work.
const ReflectionType& reflection() const { return value_; };
/// Casts the underlying value to an rfl::Generic::Array or returns an
/// rfl::Error, if the underlying value is not an rfl::Generic::Array.
Result<Array> to_array() const noexcept {
if (const auto* ptr = std::get_if<Array>(&value_)) {
return *ptr;
} else {
return Error(
"rfl::Generic: Could not cast the underlying value to an "
"rfl::Generic::Array.");
}
}
/// Casts the underlying value to a boolean or returns an rfl::Error, if the
/// underlying value is not a boolean.
Result<bool> to_bool() const noexcept {
if (const auto* ptr = std::get_if<bool>(&value_)) {
return *ptr;
} else {
return Error(
"rfl::Generic: Could not cast the underlying value to a boolean.");
}
}
/// Casts the underlying value to a double or returns an rfl::Error, if the
/// underlying value is not a double.
Result<double> to_double() const noexcept {
if (const auto* ptr = std::get_if<double>(&value_)) {
return *ptr;
} else {
return Error(
"rfl::Generic: Could not cast the underlying value to a double.");
}
}
/// Casts the underlying value to an integer or returns an rfl::Error, if the
/// underlying value is not an integer.
Result<int> to_int() const noexcept {
if (const auto* ptr = std::get_if<int>(&value_)) {
return *ptr;
} else {
return Error(
"rfl::Generic: Could not cast the underlying value to an integer.");
}
}
/// Casts the underlying value to an rfl::Generic::Object or returns an
/// rfl::Error, if the underlying value is not an rfl::Generic::Object.
Result<Object> to_object() const noexcept {
if (const auto* ptr = std::get_if<Object>(&value_)) {
return *ptr;
} else {
return Error(
"rfl::Generic: Could not cast the underlying value to an "
"rfl::Generic::Object.");
}
}
/// Casts the underlying value to a string or returns an rfl::Error, if the
/// underlying value is not a string.
Result<std::string> to_string() const noexcept {
if (const auto* ptr = std::get_if<std::string>(&value_)) {
return *ptr;
} else {
return Error(
"rfl::Generic: Could not cast the underlying value to a string.");
}
}
private:
ReflectionType value_;
};
/// Casts the underlying value to an rfl::Generic::Array or returns an
/// rfl::Error, if the underlying value is not an rfl::Generic::Array.
inline Result<Generic::Array> to_array(const Generic& _g) noexcept {
return _g.to_array();
}
/// Casts the underlying value to a boolean or returns an rfl::Error, if the
/// underlying value is not a boolean.
inline Result<bool> to_bool(const Generic& _g) noexcept { return _g.to_bool(); }
/// Casts the underlying value to a double or returns an rfl::Error, if the
/// underlying value is not a double.
inline Result<double> to_double(const Generic& _g) noexcept {
return _g.to_double();
}
/// Casts the underlying value to an integer or returns an rfl::Error, if the
/// underlying value is not an integer.
inline Result<int> to_int(const Generic& _g) noexcept { return _g.to_int(); }
/// Casts the underlying value to an rfl::Generic::Object or returns an
/// rfl::Error, if the underlying value is not an rfl::Generic::Object.
inline Result<Generic::Object> to_object(const Generic& _g) noexcept {
return _g.to_object();
}
/// Casts the underlying value to a string or returns an rfl::Error, if the
/// underlying value is not a string.
inline Result<std::string> to_string(const Generic& _g) noexcept {
return _g.to_string();
}
} // namespace rfl
#endif
+59 -1
View File
@@ -12,6 +12,7 @@
#include "get.hpp"
#include "internal/StringLiteral.hpp"
#include "internal/find_index.hpp"
#include "internal/is_extra_fields.hpp"
#include "internal/no_duplicate_field_names.hpp"
namespace rfl {
@@ -282,6 +283,22 @@ class NamedTuple {
inline auto operator!=(const rfl::NamedTuple<FieldTypes...>& _other) const {
return !(*this == _other);
}
/// Returns the number of fields. Note that this is not necessary the same
/// thing as .size(), because there might be rfl::ExtraFields, which are
/// simply counted as one entry by .size(), but are counted by individually by
/// .num_fields().
size_t num_fields() const {
if constexpr (pos_extra_fields() == -1) {
return size();
} else {
return calc_num_fields<pos_extra_fields()>();
}
}
/// The position of the extra fields, or -1 if there aren't any.
constexpr static int pos_extra_fields() { return pos_extra_fields_; }
/// Replaces one or several fields, returning a new version
/// with the non-replaced fields left unchanged.
template <internal::StringLiteral _name, class FType, class... OtherRFields>
@@ -409,6 +426,38 @@ class NamedTuple {
return std::apply(a, std::forward<std::tuple<TupContent...>>(_tuple));
}
/// Unfortunately, MSVC forces us to do this...
template <int _pos>
size_t calc_num_fields() const {
const auto& extra_fields = get<_pos>();
if constexpr (std::is_pointer_v<
std::remove_cvref_t<decltype(extra_fields)>>) {
return size() + extra_fields->size() - 1;
} else {
return size() + extra_fields.size() - 1;
}
}
/// Finds the position of the extra fields, or -1 if there aren't any.
template <int _i = 0, int _idx = -1>
constexpr static int find_extra_fields() {
if constexpr (_i == size()) {
return _idx;
} else {
using FieldType = typename std::tuple_element_t<_i, Fields>;
constexpr bool is_extra_fields =
internal::is_extra_fields_v<typename FieldType::Type>;
static_assert(_idx == -1 || !is_extra_fields,
"There can only be one rfl::ExtraFields in any struct or "
"named tuple.");
if constexpr (is_extra_fields) {
return find_extra_fields<_i + 1, _i>();
} else {
return find_extra_fields<_i + 1, _idx>();
}
}
}
/// Generates the fields.
template <int num_additional_fields = 0, class... Args>
auto make_fields(Args&&... _args) {
@@ -423,7 +472,7 @@ class NamedTuple {
} else {
// When we add additional fields, it is more intuitive to add
// them to the end, that is why we do it like this.
using FieldType = typename std::tuple_element<i, Fields>::type;
using FieldType = typename std::tuple_element_t<i, Fields>;
using T = std::remove_cvref_t<typename FieldType::Type>;
return make_fields<num_additional_fields>(
FieldType(std::forward<T>(std::get<i>(values_))),
@@ -554,6 +603,9 @@ class NamedTuple {
/// everything else is resolved at compile time. It should have no
/// runtime overhead over a normal std::tuple.
Values values_;
/// The position of rfl::ExtraFields, or -1 if there aren't any.
constexpr static int pos_extra_fields_ = find_extra_fields();
};
// ----------------------------------------------------------------------------
@@ -611,6 +663,12 @@ class NamedTuple<> {
/// Returns an empty tuple.
auto fields() const { return std::tuple(); }
/// Must always be 0.
size_t num_fields() const { return 0; }
/// Must always be -1.
constexpr static int pos_extra_fields() { return -1; }
/// Must always be 0.
static constexpr size_t size() { return 0; }
+231
View File
@@ -0,0 +1,231 @@
#ifndef RFL_OBJECT_HPP_
#define RFL_OBJECT_HPP_
#include <algorithm>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
#include "Result.hpp"
namespace rfl {
/// Used to embed additional fields for which the names cannot be known in
/// advance and can therefore not be encoded in the struct.
template <class T>
class Object {
public:
using DataType = std::vector<std::pair<std::string, T>>;
using Type = T;
/// We want this to behave as similarly to C++ standard containers as
/// possible.
using key_type = std::string;
using mapped_type = T;
using value_type = std::pair<std::string, T>;
using size_type = typename DataType::size_type;
using difference_type = typename DataType::size_type;
using reference = value_type&;
using const_reference = const value_type&;
using pointer = typename DataType::pointer;
using const_pointer = typename DataType::const_pointer;
using iterator = typename DataType::iterator;
using const_iterator = typename DataType::const_iterator;
using reverse_iterator = typename DataType::reverse_iterator;
using const_reverse_iterator = typename DataType::const_reverse_iterator;
Object() : data_(), it_(data_.begin()) {}
Object(const Object<T>& _f) = default;
Object(Object<T>&& _f) noexcept = default;
~Object() = default;
/// Iterator to the beginning.
auto begin() { return data_.begin(); }
/// Iterator to the beginning.
auto begin() const { return data_.begin(); }
/// Const iterator to the beginning.
auto cbegin() const { return data_.cbegin(); }
/// Iterator to the end.
auto end() { return data_.end(); }
/// Iterator to the end.
auto end() const { return data_.end(); }
/// Const iterator to the end.
auto cend() const { return data_.cend(); }
/// Reverse iterator.
auto rbegin() { return data_.rbegin(); }
/// Reverse iterator.
auto rbegin() const { return data_.rbegin(); }
/// Const reverse iterator.
auto crbegin() const { return data_.crbegin(); }
/// Reverse iterator.
auto rend() { return data_.rend(); }
/// Reverse iterator.
auto rend() const { return data_.rend(); }
/// Const reverse iterator.
auto crend() const { return data_.crend(); }
Object<T>& operator=(const Object<T>& _f) = default;
Object<T>& operator=(Object<T>&& _f) = default;
/// Whether the object is empty.
auto empty() const { return data_.size() == 0; }
/// The number of elements currently inside the object.
auto size() const { return data_.size(); }
/// The maximum possible size.
auto max_size() const { return data_.max_size(); }
/// Inserts a new element at the end.
void insert(const value_type& _value) {
data_.push_back(_value);
it_ = data_.begin();
}
/// Inserts a new element at the end.
void insert(value_type&& _value) {
data_.emplace_back(std::move(_value));
it_ = data_.begin();
}
/// Inserts several new elements at the end.
template <class InputIt>
void insert(InputIt _first, InputIt _last) {
for (auto it = _first; it != _last; ++it) {
insert(*it);
}
}
/// Inserts a new element at the end.
void insert(const std::string& _k, const T& _v) {
insert(std::make_pair(_k, _v));
}
/// Inserts a new element at the end.
void insert(const std::string& _k, T&& _v) {
insert(std::make_pair(_k, std::move(_v)));
}
/// Inserts a new element at the end.
void insert(std::string&& _k, T&& _v) {
insert(std::make_pair(std::move(_k), std::move(_v)));
}
/// Alias for insert that primarily exists for compatability with standard
/// containers.
template <class... Args>
void emplace(Args&&... _args) {
insert(std::forward<Args>(_args)...);
}
/// Alias for insert that primarily exists for compatability with standard
/// containers.
template <class... Args>
void emplace(const Args&... _args) {
insert(_args...);
}
/// Returns the element signified by the key or creates a new one.
T& operator[](const std::string& _key) {
for (auto it = it_; it != end(); ++it) {
if (it->first == _key) {
it_ = it + 1;
return it->second;
}
}
for (auto it = begin(); it != it_; ++it) {
if (it->first == _key) {
it_ = it + 1;
return it->second;
}
}
data_.emplace_back(std::make_pair(_key, T()));
it_ = data_.begin();
return data_.back().second;
}
/// Returns the element signified by the key or creates a new one.
T& operator[](std::string&& _key) {
for (auto it = it_; it != end(); ++it) {
if (it->first == _key) {
it_ = it + 1;
return it->second;
}
}
for (auto it = begin(); it != it_; ++it) {
if (it->first == _key) {
it_ = it + 1;
return it->second;
}
}
data_.emplace_back(std::make_pair(std::move(_key), T()));
it_ = data_.begin();
return data_.back().second;
}
/// Deletes all elements.
void clear() {
data_.clear();
it_ = data_.begin();
}
/// Returns the element signified by the key or throws an exception.
T& at(const std::string& _key) {
for (auto it = it_; it != end(); ++it) {
if (it->first == _key) {
it_ = it + 1;
return it->second;
}
}
throw std::runtime_error("Key named '" + _key + "' not found.");
}
/// Returns the element signified by the key or throws an exception.
const T& at(const std::string& _key) const {
for (auto it = it_; it != end(); ++it) {
if (it->first == _key) {
it_ = it + 1;
return it->second;
}
}
throw std::runtime_error("Key named '" + _key + "' not found.");
}
/// Returns a result wrapping the element signified by the key.
Result<T> get(const std::string& _key) const noexcept {
for (auto it = it_; it != end(); ++it) {
if (it->first == _key) {
it_ = it + 1;
return it->second;
}
}
return Error("Key named '" + _key + "' not found.");
}
private:
DataType data_;
/// Allows faster access
iterator it_;
};
} // namespace rfl
#endif
+25
View File
@@ -0,0 +1,25 @@
#ifndef RFL_INTERNAL_ISEXTRAFIELDS_HPP_
#define RFL_INTERNAL_ISEXTRAFIELDS_HPP_
#include <type_traits>
#include "../ExtraFields.hpp"
namespace rfl::internal {
template <class T>
class is_extra_fields;
template <class T>
class is_extra_fields : public std::false_type {};
template <class T>
class is_extra_fields<ExtraFields<T>> : public std::true_type {};
template <class T>
constexpr bool is_extra_fields_v =
is_extra_fields<std::remove_cvref_t<std::remove_pointer_t<T>>>::value;
} // namespace rfl::internal
#endif
+1
View File
@@ -88,6 +88,7 @@ struct Type {
std::optional<std::string> description;
std::map<std::string, Type> properties;
std::vector<std::string> required;
std::shared_ptr<Type> additionalProperties;
};
struct OneOf {
+8 -1
View File
@@ -193,8 +193,15 @@ inline schema::Type type_to_json_schema_type(
required.push_back(k);
}
}
auto additional_properties =
_t.additional_properties_
? std::make_shared<schema::Type>(
type_to_json_schema_type(*_t.additional_properties_))
: std::shared_ptr<schema::Type>();
return schema::Type{.value = schema::Type::Object{
.properties = properties, .required = required}};
.properties = properties,
.required = required,
.additionalProperties = additional_properties}};
} else if constexpr (std::is_same<T, Type::Optional>()) {
return schema::Type{.value = schema::Type::AnyOf{
+36 -11
View File
@@ -15,6 +15,7 @@
#include "../internal/is_array.hpp"
#include "../internal/is_attribute.hpp"
#include "../internal/is_basic_type.hpp"
#include "../internal/is_extra_fields.hpp"
#include "../internal/is_skip.hpp"
#include "../internal/strings/replace_all.hpp"
#include "../to_view.hpp"
@@ -59,6 +60,10 @@ struct NamedTupleParser {
static constexpr size_t size_ = NamedTupleType::size();
static_assert(NamedTupleType::pos_extra_fields() == -1 || !_no_field_names,
"You cannot use the rfl::NoFieldNames processor if you are "
"including rfl::ExtraFields.");
public:
/// The way this works is that we allocate space on the stack in this size of
/// the named tuple in which we then write the individual fields using
@@ -102,11 +107,11 @@ struct NamedTupleParser {
static void write(const W& _w, const NamedTuple<FieldTypes...>& _tup,
const P& _parent) noexcept {
if constexpr (_no_field_names) {
auto arr = ParentType::add_array(_w, _tup.size(), _parent);
auto arr = ParentType::add_array(_w, _tup.num_fields(), _parent);
build_object(_w, _tup, &arr, std::make_integer_sequence<int, size_>());
_w.end_array(&arr);
} else {
auto obj = ParentType::add_object(_w, _tup.size(), _parent);
auto obj = ParentType::add_object(_w, _tup.num_fields(), _parent);
build_object(_w, _tup, &obj, std::make_integer_sequence<int, size_>());
_w.end_object(&obj);
}
@@ -128,11 +133,17 @@ struct NamedTupleParser {
using FieldType =
typename std::tuple_element<_i, std::tuple<FieldTypes...>>::type;
using ValueType = std::remove_cvref_t<typename FieldType::Type>;
const auto& value = rfl::get<_i>(_tup);
constexpr auto name = FieldType::name_.string_view();
const auto new_parent = make_parent(name, _ptr);
if constexpr (!_all_required && !_no_field_names &&
!is_required<ValueType, _ignore_empty_containers>()) {
const auto value = rfl::get<_i>(_tup);
if constexpr (internal::is_extra_fields_v<ValueType>) {
for (const auto& [k, v] : *value) {
const auto new_parent = make_parent(k, _ptr);
Parser<R, W, std::remove_cvref_t<decltype(v)>, ProcessorsType>::write(
_w, v, new_parent);
}
} else if constexpr (!_all_required && !_no_field_names &&
!is_required<ValueType, _ignore_empty_containers>()) {
constexpr auto name = FieldType::name_.string_view();
const auto new_parent = make_parent(name, _ptr);
if (!is_empty(value)) {
if constexpr (internal::is_attribute_v<ValueType>) {
Parser<R, W, ValueType, ProcessorsType>::write(
@@ -142,6 +153,8 @@ struct NamedTupleParser {
}
}
} else {
constexpr auto name = FieldType::name_.string_view();
const auto new_parent = make_parent(name, _ptr);
if constexpr (internal::is_attribute_v<ValueType>) {
Parser<R, W, ValueType, ProcessorsType>::write(
_w, value, new_parent.as_attribute());
@@ -157,8 +170,8 @@ struct NamedTupleParser {
SchemaType* _schema) noexcept {
using F =
std::tuple_element_t<_i, typename NamedTuple<FieldTypes...>::Fields>;
using U = typename F::Type;
if constexpr (!internal::is_skip_v<U>) {
using U = std::remove_cvref_t<typename F::Type>;
if constexpr (!internal::is_skip_v<U> && !internal::is_extra_fields_v<U>) {
auto s = Parser<R, W, U, ProcessorsType>::to_schema(_definitions);
if constexpr (_no_field_names) {
_schema->types_.emplace_back(std::move(s));
@@ -180,6 +193,16 @@ struct NamedTupleParser {
SchemaType* _schema,
std::integer_sequence<int, _is...>) noexcept {
(add_field_to_schema<_is>(_definitions, _schema), ...);
if constexpr (NamedTupleType::pos_extra_fields() != -1) {
using F =
std::tuple_element_t<NamedTupleType::pos_extra_fields(),
typename NamedTuple<FieldTypes...>::Fields>;
using ExtraFieldsType = std::remove_cvref_t<typename F::Type>;
using U = std::remove_cvref_t<typename ExtraFieldsType::Type>;
_schema->additional_properties_ = std::make_shared<schema::Type>(
Parser<R, W, U, ProcessorsType>::to_schema(_definitions));
}
}
/// Generates error messages for when fields are missing.
@@ -193,8 +216,10 @@ struct NamedTupleParser {
std::remove_pointer_t<typename FieldType::Type>>;
if (!std::get<_i>(_found)) {
if constexpr (_all_required ||
is_required<ValueType, _ignore_empty_containers>()) {
constexpr bool is_required_field =
!internal::is_extra_fields_v<ValueType> &&
(_all_required || is_required<ValueType, _ignore_empty_containers>());
if constexpr (is_required_field) {
constexpr auto current_name =
std::tuple_element_t<_i, typename NamedTupleType::Fields>::name();
_errors->emplace_back(Error(
+11 -5
View File
@@ -140,8 +140,7 @@ struct Parser {
return make_validated<U>(_definitions);
} else if constexpr (internal::has_reflection_type_v<U>) {
return Parser<R, W, typename U::ReflectionType,
ProcessorsType>::to_schema(_definitions);
return make_reference<U>(_definitions);
} else {
static_assert(rfl::always_false_v<U>, "Unsupported type.");
@@ -181,9 +180,16 @@ struct Parser {
if (_definitions->find(name) == _definitions->end()) {
(*_definitions)[name] =
Type{Type::Integer{}}; // Placeholder to avoid infinite loop.
using NamedTupleType = internal::processed_t<U, ProcessorsType>;
(*_definitions)[name] =
Parser<R, W, NamedTupleType, ProcessorsType>::to_schema(_definitions);
if constexpr (internal::has_reflection_type_v<U>) {
(*_definitions)[name] =
Parser<R, W, typename U::ReflectionType, ProcessorsType>::to_schema(
_definitions);
} else {
using NamedTupleType = internal::processed_t<U, ProcessorsType>;
(*_definitions)[name] =
Parser<R, W, NamedTupleType, ProcessorsType>::to_schema(
_definitions);
}
}
return Type{Type::Reference{name}};
}
+14
View File
@@ -7,6 +7,8 @@
#include <type_traits>
#include <unordered_map>
#include "../ExtraFields.hpp"
#include "../Object.hpp"
#include "../Result.hpp"
#include "../always_false.hpp"
#include "MapParser.hpp"
@@ -28,6 +30,18 @@ struct Parser<R, W, std::unordered_map<std::string, T>, ProcessorsType>
ProcessorsType> {
};
template <class R, class W, class T, class ProcessorsType>
requires AreReaderAndWriter<R, W, Object<T>>
struct Parser<R, W, Object<T>, ProcessorsType>
: public MapParser<R, W, Object<T>, ProcessorsType> {
};
template <class R, class W, class T, class ProcessorsType>
requires AreReaderAndWriter<R, W, ExtraFields<T>>
struct Parser<R, W, ExtraFields<T>, ProcessorsType>
: public MapParser<R, W, ExtraFields<T>, ProcessorsType> {
};
} // namespace parsing
} // namespace rfl
+34
View File
@@ -73,6 +73,31 @@ class ViewReader {
}
}
template <int _pos>
static void assign_to_extra_fields(const R& _r,
const std::string_view& _current_name,
const auto& _var, auto* _view,
auto* _errors, auto* _found, auto* _set) {
auto* extra_fields = _view->template get<_pos>();
using ExtraFieldsType =
std::remove_cvref_t<std::remove_pointer_t<decltype(extra_fields)>>;
using T = std::remove_cvref_t<
std::remove_pointer_t<typename ExtraFieldsType::Type>>;
if (!std::get<_pos>(*_set)) {
::new (extra_fields) ExtraFieldsType();
std::get<_pos>(*_set) = true;
std::get<_pos>(*_found) = true;
}
auto res = Parser<R, W, T, ProcessorsType>::read(_r, _var);
if (!res) {
_errors->emplace_back(Error("Failed to parse field '" +
std::string(_current_name) +
"': " + std::move(res.error()->what())));
return;
}
extra_fields->emplace(std::string(_current_name), std::move(*res));
}
template <int... is>
static void assign_to_matching_field(const R& _r,
const std::string_view& _current_name,
@@ -80,9 +105,18 @@ class ViewReader {
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),
...);
if constexpr (ViewType::pos_extra_fields() != -1) {
constexpr int pos = ViewType::pos_extra_fields();
if (!already_assigned) {
assign_to_extra_fields<pos>(_r, _current_name, _var, _view, _errors,
_found, _set);
}
}
}
template <class T>
+2
View File
@@ -3,6 +3,7 @@
#include <cstddef>
#include <map>
#include <memory>
#include <string>
#include <variant>
#include <vector>
@@ -51,6 +52,7 @@ struct Type {
struct Object {
std::map<std::string, Type> types_;
std::shared_ptr<Type> additional_properties_;
};
/// All values are assumed to be required unless explicitly stated otherwise
+26
View File
@@ -0,0 +1,26 @@
#include <iostream>
#include <rfl.hpp>
#include <source_location>
#include <string>
#include <vector>
#include "write_and_read.hpp"
namespace test_extra_fields {
struct Person {
rfl::Rename<"firstName", std::string> first_name;
rfl::Rename<"lastName", std::string> last_name = "Simpson";
rfl::ExtraFields<rfl::Generic> extra_fields;
};
TEST(cbor, test_extra_fields) {
auto homer = Person{.first_name = "Homer"};
homer.extra_fields["age"] = 45;
homer.extra_fields["email"] = "homer@simpson.com";
homer.extra_fields["town"] = "Springfield";
write_and_read(homer);
}
} // namespace test_extra_fields
+29
View File
@@ -0,0 +1,29 @@
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <source_location>
#include <string>
#include <vector>
#include "write_and_read.hpp"
namespace test_extra_fields {
struct Person {
rfl::Rename<"firstName", std::string> first_name;
rfl::Rename<"lastName", std::string> last_name = "Simpson";
rfl::ExtraFields<rfl::Generic> extra_fields;
};
TEST(json, test_extra_fields) {
auto homer = Person{.first_name = "Homer"};
homer.extra_fields["age"] = 45;
homer.extra_fields["email"] = "homer@simpson.com";
homer.extra_fields["town"] = "Springfield";
write_and_read(
homer,
R"({"firstName":"Homer","lastName":"Simpson","age":45,"email":"homer@simpson.com","town":"Springfield"})");
}
} // namespace test_extra_fields
+38
View File
@@ -0,0 +1,38 @@
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <source_location>
#include <string>
#include <vector>
#include "write_and_read.hpp"
namespace test_generic {
TEST(json, test_generic) {
auto bart = rfl::Generic::Object();
bart["first_name"] = "Bart";
bart["last_name"] = "Simpson";
bart["age"] = 10;
auto lisa = rfl::Generic::Object();
lisa["first_name"] = "Lisa";
lisa["last_name"] = "Simpson";
lisa["age"] = 8;
auto maggie = rfl::Generic::Object();
maggie["first_name"] = "Lisa";
maggie["last_name"] = "Simpson";
maggie["age"] = 0;
auto homer = rfl::Generic::Object();
homer["first_name"] = "Lisa";
homer["last_name"] = "Simpson";
homer["age"] = 45;
homer["children"] = rfl::Generic::Array({bart, lisa, maggie});
write_and_read(
homer,
R"({"first_name":"Lisa","last_name":"Simpson","age":45,"children":[{"first_name":"Bart","last_name":"Simpson","age":10},{"first_name":"Lisa","last_name":"Simpson","age":8},{"first_name":"Lisa","last_name":"Simpson","age":0}]})");
}
} // namespace test_generic
+9 -1
View File
@@ -31,6 +31,12 @@ using FieldVariant =
rfl::Variant<rfl::Field<"rectangle", Rectangle>,
rfl::Field<"square", Square>, rfl::Field<"circle", Circle>>;
struct WithExtraFields {
std::string f1;
std::string f2;
rfl::ExtraFields<std::string> extra_fields;
};
struct Person {
rfl::Rename<"firstName", std::string> first_name;
rfl::Rename<"lastName", std::string> last_name = "Simpson";
@@ -51,6 +57,8 @@ struct Person {
rfl::TaggedUnion<"shape", Rectangle, Square, Circle>>
tagged_union;
rfl::Rename<"fieldVariant", FieldVariant> field_variant;
rfl::Generic generic;
WithExtraFields with_extra_fields;
};
TEST(json, test_json_schema) {
@@ -60,7 +68,7 @@ TEST(json, test_json_schema) {
Person>>();
const std::string expected =
R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/definitions/test_json_schema__Person","description":"JSON schema that describes the required attributes for the person class.","definitions":{"test_json_schema__Circle":{"type":"object","properties":{"radius":{"type":"number"}},"required":["radius"]},"test_json_schema__Circle__tagged":{"type":"object","properties":{"radius":{"type":"number"},"shape":{"type":"string","enum":["Circle"]}},"required":["radius","shape"]},"test_json_schema__Person":{"type":"object","properties":{"age":{"allOf":[{"minimum":0,"type":"integer"},{"maximum":130,"type":"integer"}]},"children":{"type":"array","description":"The person's children. Pass an empty array for no children.","items":{"$ref":"#/definitions/test_json_schema__Person"}},"color":{"type":"string","enum":["red","green","blue"]},"email":{"type":"string","description":"Must be a proper email in the form xxx@xxx.xxx.","pattern":"^[a-zA-Z0-9._%+\\-]+@[a-zA-Z0-9.\\-]+\\.[a-zA-Z]{2,}$"},"fieldVariant":{"anyOf":[{"type":"object","properties":{"rectangle":{"$ref":"#/definitions/test_json_schema__Rectangle"}},"required":["rectangle"]},{"type":"object","properties":{"square":{"$ref":"#/definitions/test_json_schema__Square"}},"required":["square"]},{"type":"object","properties":{"circle":{"$ref":"#/definitions/test_json_schema__Circle"}},"required":["circle"]}]},"firstName":{"type":"string"},"lastName":{"type":"string"},"salary":{"type":"number"},"taggedUnion":{"anyOf":[{"$ref":"#/definitions/test_json_schema__Rectangle__tagged"},{"$ref":"#/definitions/test_json_schema__Square__tagged"},{"$ref":"#/definitions/test_json_schema__Circle__tagged"}]},"town":{"type":"string"},"tuple":{"type":"array","prefixItems":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/definitions/test_json_schema__Person"}},{"type":"integer"}],"items":false},"variant":{"anyOf":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/definitions/test_json_schema__Person"}},{"type":"integer"}]}},"required":["age","children","color","email","fieldVariant","firstName","lastName","salary","taggedUnion","town","tuple","variant"]},"test_json_schema__Rectangle":{"type":"object","properties":{"height":{"type":"number"},"width":{"type":"number"}},"required":["height","width"]},"test_json_schema__Rectangle__tagged":{"type":"object","properties":{"height":{"type":"number"},"shape":{"type":"string","enum":["Rectangle"]},"width":{"type":"number"}},"required":["height","shape","width"]},"test_json_schema__Square":{"type":"object","properties":{"width":{"type":"number"}},"required":["width"]},"test_json_schema__Square__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Square"]},"width":{"type":"number"}},"required":["shape","width"]}}})";
R"({"$schema":"https://json-schema.org/draft/2020-12/schema","$ref":"#/definitions/test_json_schema__Person","description":"JSON schema that describes the required attributes for the person class.","definitions":{"rfl__Generic":{"anyOf":[{"type":"boolean"},{"type":"integer"},{"type":"number"},{"type":"string"},{"type":"object","additionalProperties":{"$ref":"#/definitions/rfl__Generic"}},{"type":"array","items":{"$ref":"#/definitions/rfl__Generic"}}]},"test_json_schema__Circle":{"type":"object","properties":{"radius":{"type":"number"}},"required":["radius"]},"test_json_schema__Circle__tagged":{"type":"object","properties":{"radius":{"type":"number"},"shape":{"type":"string","enum":["Circle"]}},"required":["radius","shape"]},"test_json_schema__Person":{"type":"object","properties":{"age":{"allOf":[{"minimum":0,"type":"integer"},{"maximum":130,"type":"integer"}]},"children":{"type":"array","description":"The person's children. Pass an empty array for no children.","items":{"$ref":"#/definitions/test_json_schema__Person"}},"color":{"type":"string","enum":["red","green","blue"]},"email":{"type":"string","description":"Must be a proper email in the form xxx@xxx.xxx.","pattern":"^[a-zA-Z0-9._%+\\-]+@[a-zA-Z0-9.\\-]+\\.[a-zA-Z]{2,}$"},"fieldVariant":{"anyOf":[{"type":"object","properties":{"rectangle":{"$ref":"#/definitions/test_json_schema__Rectangle"}},"required":["rectangle"]},{"type":"object","properties":{"square":{"$ref":"#/definitions/test_json_schema__Square"}},"required":["square"]},{"type":"object","properties":{"circle":{"$ref":"#/definitions/test_json_schema__Circle"}},"required":["circle"]}]},"firstName":{"type":"string"},"generic":{"$ref":"#/definitions/rfl__Generic"},"lastName":{"type":"string"},"salary":{"type":"number"},"taggedUnion":{"anyOf":[{"$ref":"#/definitions/test_json_schema__Rectangle__tagged"},{"$ref":"#/definitions/test_json_schema__Square__tagged"},{"$ref":"#/definitions/test_json_schema__Circle__tagged"}]},"town":{"type":"string"},"tuple":{"type":"array","prefixItems":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/definitions/test_json_schema__Person"}},{"type":"integer"}],"items":false},"variant":{"anyOf":[{"type":"string","enum":["red","green","blue"]},{"type":"array","items":{"$ref":"#/definitions/test_json_schema__Person"}},{"type":"integer"}]},"with_extra_fields":{"$ref":"#/definitions/test_json_schema__WithExtraFields"}},"required":["age","children","color","email","fieldVariant","firstName","generic","lastName","salary","taggedUnion","town","tuple","variant","with_extra_fields"]},"test_json_schema__Rectangle":{"type":"object","properties":{"height":{"type":"number"},"width":{"type":"number"}},"required":["height","width"]},"test_json_schema__Rectangle__tagged":{"type":"object","properties":{"height":{"type":"number"},"shape":{"type":"string","enum":["Rectangle"]},"width":{"type":"number"}},"required":["height","shape","width"]},"test_json_schema__Square":{"type":"object","properties":{"width":{"type":"number"}},"required":["width"]},"test_json_schema__Square__tagged":{"type":"object","properties":{"shape":{"type":"string","enum":["Square"]},"width":{"type":"number"}},"required":["shape","width"]},"test_json_schema__WithExtraFields":{"type":"object","properties":{"f1":{"type":"string"},"f2":{"type":"string"}},"required":["f1","f2"],"additionalProperties":{"type":"string"}}}})";
EXPECT_EQ(json_schema, expected);
}
+26
View File
@@ -0,0 +1,26 @@
#include <iostream>
#include <rfl.hpp>
#include <source_location>
#include <string>
#include <vector>
#include "write_and_read.hpp"
namespace test_extra_fields {
struct Person {
rfl::Rename<"firstName", std::string> first_name;
rfl::Rename<"lastName", std::string> last_name = "Simpson";
rfl::ExtraFields<rfl::Generic> extra_fields;
};
TEST(msgpack, test_extra_fields) {
auto homer = Person{.first_name = "Homer"};
homer.extra_fields["age"] = 45;
homer.extra_fields["email"] = "homer@simpson.com";
homer.extra_fields["town"] = "Springfield";
write_and_read(homer);
}
} // namespace test_extra_fields