diff --git a/README.md b/README.md index fd8dd47c..e923be47 100644 --- a/README.md +++ b/README.md @@ -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 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. diff --git a/docs/README.md b/docs/README.md index 9395d30e..5d47460b 100644 --- a/docs/README.md +++ b/docs/README.md @@ -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. diff --git a/docs/extra_fields.md b/docs/extra_fields.md new file mode 100644 index 00000000..9d389bd9 --- /dev/null +++ b/docs/extra_fields.md @@ -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 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 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. diff --git a/docs/generic.md b/docs/generic.md new file mode 100644 index 00000000..98a62e94 --- /dev/null +++ b/docs/generic.md @@ -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; +``` + +`Object` and `Array` are defined as follows: + +```cpp +using Array = std::vector; +using Object = rfl::Object; +``` + +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 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` 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. diff --git a/docs/object.md b/docs/object.md new file mode 100644 index 00000000..4d27696f --- /dev/null +++ b/docs/object.md @@ -0,0 +1,65 @@ +# `rfl::Object` + +`rfl::Object<...>` behaves similarly to `rfl::map` and `rfl::unordered_map`. + +It will be represented in JSON or other formats as an object: + +```cpp +auto bart = rfl::Object(); +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(); +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. diff --git a/include/rfl.hpp b/include/rfl.hpp index fda238d7..9dc36c7b 100644 --- a/include/rfl.hpp +++ b/include/rfl.hpp @@ -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" diff --git a/include/rfl/ExtraFields.hpp b/include/rfl/ExtraFields.hpp new file mode 100644 index 00000000..dc77983b --- /dev/null +++ b/include/rfl/ExtraFields.hpp @@ -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 ExtraFields : public Object {}; + +} // namespace rfl + +#endif diff --git a/include/rfl/Generic.hpp b/include/rfl/Generic.hpp new file mode 100644 index 00000000..fa4217df --- /dev/null +++ b/include/rfl/Generic.hpp @@ -0,0 +1,181 @@ +#ifndef RFL_GENERIC_HPP_ +#define RFL_GENERIC_HPP_ + +#include +#include +#include + +#include "Object.hpp" +#include "Result.hpp" + +namespace rfl { + +class Generic { + public: + using Array = std::vector; + using Object = rfl::Object; + using ReflectionType = + std::variant; + + 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 , + bool>::type = true> + Generic(const T& _value) : value_(_value) {} + + template , + bool>::type = true> + Generic(T&& _value) noexcept : value_(std::forward(_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 , + 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 to_array() const noexcept { + if (const auto* ptr = std::get_if(&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 to_bool() const noexcept { + if (const auto* ptr = std::get_if(&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 to_double() const noexcept { + if (const auto* ptr = std::get_if(&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 to_int() const noexcept { + if (const auto* ptr = std::get_if(&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 to_object() const noexcept { + if (const auto* ptr = std::get_if(&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 to_string() const noexcept { + if (const auto* ptr = std::get_if(&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 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 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 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 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 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 to_string(const Generic& _g) noexcept { + return _g.to_string(); +} + +} // namespace rfl + +#endif diff --git a/include/rfl/NamedTuple.hpp b/include/rfl/NamedTuple.hpp index 2fffbcaa..25abbb08 100644 --- a/include/rfl/NamedTuple.hpp +++ b/include/rfl/NamedTuple.hpp @@ -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& _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(); + } + } + + /// 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 @@ -409,6 +426,38 @@ class NamedTuple { return std::apply(a, std::forward>(_tuple)); } + /// Unfortunately, MSVC forces us to do this... + template + size_t calc_num_fields() const { + const auto& extra_fields = get<_pos>(); + if constexpr (std::is_pointer_v< + std::remove_cvref_t>) { + 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 + 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; + 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 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::type; + using FieldType = typename std::tuple_element_t; using T = std::remove_cvref_t; return make_fields( FieldType(std::forward(std::get(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; } diff --git a/include/rfl/Object.hpp b/include/rfl/Object.hpp new file mode 100644 index 00000000..16d60986 --- /dev/null +++ b/include/rfl/Object.hpp @@ -0,0 +1,231 @@ +#ifndef RFL_OBJECT_HPP_ +#define RFL_OBJECT_HPP_ + +#include +#include +#include +#include +#include +#include + +#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 Object { + public: + using DataType = std::vector>; + 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; + 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& _f) = default; + + Object(Object&& _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& operator=(const Object& _f) = default; + + Object& operator=(Object&& _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 + 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 + void emplace(Args&&... _args) { + insert(std::forward(_args)...); + } + + /// Alias for insert that primarily exists for compatability with standard + /// containers. + template + 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 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 diff --git a/include/rfl/internal/is_extra_fields.hpp b/include/rfl/internal/is_extra_fields.hpp new file mode 100644 index 00000000..96759992 --- /dev/null +++ b/include/rfl/internal/is_extra_fields.hpp @@ -0,0 +1,25 @@ +#ifndef RFL_INTERNAL_ISEXTRAFIELDS_HPP_ +#define RFL_INTERNAL_ISEXTRAFIELDS_HPP_ + +#include + +#include "../ExtraFields.hpp" + +namespace rfl::internal { + +template +class is_extra_fields; + +template +class is_extra_fields : public std::false_type {}; + +template +class is_extra_fields> : public std::true_type {}; + +template +constexpr bool is_extra_fields_v = + is_extra_fields>>::value; + +} // namespace rfl::internal + +#endif diff --git a/include/rfl/json/schema/Type.hpp b/include/rfl/json/schema/Type.hpp index 7352cad0..533b0b7a 100644 --- a/include/rfl/json/schema/Type.hpp +++ b/include/rfl/json/schema/Type.hpp @@ -88,6 +88,7 @@ struct Type { std::optional description; std::map properties; std::vector required; + std::shared_ptr additionalProperties; }; struct OneOf { diff --git a/include/rfl/json/to_schema.hpp b/include/rfl/json/to_schema.hpp index d88affab..fb61589b 100644 --- a/include/rfl/json/to_schema.hpp +++ b/include/rfl/json/to_schema.hpp @@ -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( + type_to_json_schema_type(*_t.additional_properties_)) + : std::shared_ptr(); return schema::Type{.value = schema::Type::Object{ - .properties = properties, .required = required}}; + .properties = properties, + .required = required, + .additionalProperties = additional_properties}}; } else if constexpr (std::is_same()) { return schema::Type{.value = schema::Type::AnyOf{ diff --git a/include/rfl/parsing/NamedTupleParser.hpp b/include/rfl/parsing/NamedTupleParser.hpp index bc8841b3..1a2b8bcf 100644 --- a/include/rfl/parsing/NamedTupleParser.hpp +++ b/include/rfl/parsing/NamedTupleParser.hpp @@ -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& _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()); _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()); _w.end_object(&obj); } @@ -128,11 +133,17 @@ struct NamedTupleParser { using FieldType = typename std::tuple_element<_i, std::tuple>::type; using ValueType = std::remove_cvref_t; - 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()) { + const auto value = rfl::get<_i>(_tup); + if constexpr (internal::is_extra_fields_v) { + for (const auto& [k, v] : *value) { + const auto new_parent = make_parent(k, _ptr); + Parser, ProcessorsType>::write( + _w, v, new_parent); + } + } else if constexpr (!_all_required && !_no_field_names && + !is_required()) { + 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) { Parser::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) { Parser::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::Fields>; - using U = typename F::Type; - if constexpr (!internal::is_skip_v) { + using U = std::remove_cvref_t; + if constexpr (!internal::is_skip_v && !internal::is_extra_fields_v) { auto s = Parser::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) noexcept { (add_field_to_schema<_is>(_definitions, _schema), ...); + + if constexpr (NamedTupleType::pos_extra_fields() != -1) { + using F = + std::tuple_element_t::Fields>; + using ExtraFieldsType = std::remove_cvref_t; + using U = std::remove_cvref_t; + _schema->additional_properties_ = std::make_shared( + Parser::to_schema(_definitions)); + } } /// Generates error messages for when fields are missing. @@ -193,8 +216,10 @@ struct NamedTupleParser { std::remove_pointer_t>; if (!std::get<_i>(_found)) { - if constexpr (_all_required || - is_required()) { + constexpr bool is_required_field = + !internal::is_extra_fields_v && + (_all_required || is_required()); + if constexpr (is_required_field) { constexpr auto current_name = std::tuple_element_t<_i, typename NamedTupleType::Fields>::name(); _errors->emplace_back(Error( diff --git a/include/rfl/parsing/Parser_default.hpp b/include/rfl/parsing/Parser_default.hpp index f6397507..3c1f7f57 100644 --- a/include/rfl/parsing/Parser_default.hpp +++ b/include/rfl/parsing/Parser_default.hpp @@ -140,8 +140,7 @@ struct Parser { return make_validated(_definitions); } else if constexpr (internal::has_reflection_type_v) { - return Parser::to_schema(_definitions); + return make_reference(_definitions); } else { static_assert(rfl::always_false_v, "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; - (*_definitions)[name] = - Parser::to_schema(_definitions); + if constexpr (internal::has_reflection_type_v) { + (*_definitions)[name] = + Parser::to_schema( + _definitions); + } else { + using NamedTupleType = internal::processed_t; + (*_definitions)[name] = + Parser::to_schema( + _definitions); + } } return Type{Type::Reference{name}}; } diff --git a/include/rfl/parsing/Parser_map_like.hpp b/include/rfl/parsing/Parser_map_like.hpp index 04f34e01..be0a6e6d 100644 --- a/include/rfl/parsing/Parser_map_like.hpp +++ b/include/rfl/parsing/Parser_map_like.hpp @@ -7,6 +7,8 @@ #include #include +#include "../ExtraFields.hpp" +#include "../Object.hpp" #include "../Result.hpp" #include "../always_false.hpp" #include "MapParser.hpp" @@ -28,6 +30,18 @@ struct Parser, ProcessorsType> ProcessorsType> { }; +template +requires AreReaderAndWriter> +struct Parser, ProcessorsType> + : public MapParser, ProcessorsType> { +}; + +template +requires AreReaderAndWriter> +struct Parser, ProcessorsType> + : public MapParser, ProcessorsType> { +}; + } // namespace parsing } // namespace rfl diff --git a/include/rfl/parsing/ViewReader.hpp b/include/rfl/parsing/ViewReader.hpp index d1ba9710..bb77840c 100644 --- a/include/rfl/parsing/ViewReader.hpp +++ b/include/rfl/parsing/ViewReader.hpp @@ -73,6 +73,31 @@ class ViewReader { } } + template + 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>; + using T = std::remove_cvref_t< + std::remove_pointer_t>; + if (!std::get<_pos>(*_set)) { + ::new (extra_fields) ExtraFieldsType(); + std::get<_pos>(*_set) = true; + std::get<_pos>(*_found) = true; + } + auto res = Parser::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 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) { bool already_assigned = false; + (assign_if_field_matches(_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(_r, _current_name, _var, _view, _errors, + _found, _set); + } + } } template diff --git a/include/rfl/parsing/schema/Type.hpp b/include/rfl/parsing/schema/Type.hpp index 0b8bb850..26ce4dd8 100644 --- a/include/rfl/parsing/schema/Type.hpp +++ b/include/rfl/parsing/schema/Type.hpp @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -51,6 +52,7 @@ struct Type { struct Object { std::map types_; + std::shared_ptr additional_properties_; }; /// All values are assumed to be required unless explicitly stated otherwise diff --git a/tests/cbor/test_extra_fields.cpp b/tests/cbor/test_extra_fields.cpp new file mode 100644 index 00000000..8e7f7d87 --- /dev/null +++ b/tests/cbor/test_extra_fields.cpp @@ -0,0 +1,26 @@ +#include +#include +#include +#include +#include + +#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 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 diff --git a/tests/json/test_extra_fields.cpp b/tests/json/test_extra_fields.cpp new file mode 100644 index 00000000..1ad31989 --- /dev/null +++ b/tests/json/test_extra_fields.cpp @@ -0,0 +1,29 @@ +#include +#include +#include +#include +#include +#include + +#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 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 diff --git a/tests/json/test_generic.cpp b/tests/json/test_generic.cpp new file mode 100644 index 00000000..547c624d --- /dev/null +++ b/tests/json/test_generic.cpp @@ -0,0 +1,38 @@ +#include +#include +#include +#include +#include +#include + +#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 diff --git a/tests/json/test_json_schema.cpp b/tests/json/test_json_schema.cpp index 6e816b79..800641f5 100644 --- a/tests/json/test_json_schema.cpp +++ b/tests/json/test_json_schema.cpp @@ -31,6 +31,12 @@ using FieldVariant = rfl::Variant, rfl::Field<"square", Square>, rfl::Field<"circle", Circle>>; +struct WithExtraFields { + std::string f1; + std::string f2; + rfl::ExtraFields 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); } diff --git a/tests/msgpack/test_extra_fields.cpp b/tests/msgpack/test_extra_fields.cpp new file mode 100644 index 00000000..fe43dccf --- /dev/null +++ b/tests/msgpack/test_extra_fields.cpp @@ -0,0 +1,26 @@ +#include +#include +#include +#include +#include + +#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 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