Merge branch 'f/flexbuffers'

This commit is contained in:
Patrick Urbanke
2023-11-13 18:30:38 +01:00
120 changed files with 2878 additions and 244 deletions
+5
View File
@@ -38,3 +38,8 @@
**/CMakeFiles/**
**/reflect-cpp-tests
**/build/**
**/build_clang/**
# Output files
*.json
*.fb
+1 -1
View File
@@ -60,6 +60,6 @@ struct API_v_1_1 {
...
using APIs = std::variant<rfl::Field<"v1.0", API_v_1_0>, rfl::Field<"v1.1", API_v_1_1>, ...>;
using APIs = rfl::Variant<rfl::Field<"v1.0", API_v_1_0>, rfl::Field<"v1.1", API_v_1_1>, ...>;
```
+285
View File
@@ -0,0 +1,285 @@
# Flexbuffers
For flexbuffers support, you must also include the header `<rfl/flexbuf.hpp>` and link to the flatbuffers library (https://github.com/google/flatbuffers).
Flexbuffers is part of the flatbuffers library, which is a binary format developed by Google.
reflect-cpp can be used on top of flexbuffers. To see how this is advantageous, consider the following example:
## Simple example
```cpp
#include <rfl.hpp>
#include <rfl/flexbuf.hpp>
using Color = rfl::Literal<"Red", "Green", "Blue">;
struct Weapon {
std::string name;
short damage;
};
using Equipment = rfl::Variant<rfl::Field<"weapon", Weapon>>;
struct Vec3 {
float x;
float y;
float z;
};
struct Monster {
Vec3 pos;
short mana = 150;
short hp = 100;
std::string name;
bool friendly = false;
std::vector<std::uint8_t> inventory;
Color color = Color::make<"Blue">();
std::vector<Weapon> weapons;
Equipment equipped;
std::vector<Vec3> path;
};
const auto sword = Weapon{.name = "Sword", .damage = 3};
const auto axe = Weapon{.name = "Axe", .damage = 5};
const auto weapons = std::vector<Weapon>({sword, axe});
const auto position = Vec3{1.0f, 2.0f, 3.0f};
const auto inventory =
std::vector<std::uint8_t>({0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
const auto orc = Monster{.pos = position,
.mana = 150,
.hp = 80,
.name = "MyMonster",
.inventory = inventory,
.color = Color::make<"Red">(),
.weapons = weapons,
.equipped = rfl::make_field<"weapon">(axe)};
const auto bytes = rfl::flexbuf::write(orc);
const auto res = rfl::flexbuf::read<Monster>(bytes);
```
## For comparison: Standard flatbuffers
Let's talk about what normal flatbuffers would make you do to set up this example.
First of all, you would have to set up your `Monster.fbs`:
```
namespace MyGame.Sample;
enum Color:byte { Red = 0, Green, Blue = 2 }
union Equipment { Weapon } // Optionally add more tables.
struct Vec3 {
x:float;
y:float;
z:float;
}
table Monster {
pos:Vec3;
mana:short = 150;
hp:short = 100;
name:string;
friendly:bool = false (deprecated);
inventory:[ubyte];
color:Color = Blue;
weapons:[Weapon];
equipped:Equipment;
path:[Vec3];
}
table Weapon {
name:string;
damage:short;
}
root_type Monster;
```
Then you would have to generate the C++ code using the flatbuffers compiler.
Finally, here is the code that you would then write afterwards:
```cpp
// Build up a serialized buffer algorithmically:
flatbuffers::FlatBufferBuilder builder;
// First, lets serialize some weapons for the Monster: A 'sword' and an 'axe'.
auto weapon_one_name = builder.CreateString("Sword");
short weapon_one_damage = 3;
auto weapon_two_name = builder.CreateString("Axe");
short weapon_two_damage = 5;
// Use the `CreateWeapon` shortcut to create Weapons with all fields set.
auto sword = CreateWeapon(builder, weapon_one_name, weapon_one_damage);
auto axe = CreateWeapon(builder, weapon_two_name, weapon_two_damage);
// Create a FlatBuffer's `vector` from the `std::vector`.
std::vector<flatbuffers::Offset<Weapon>> weapons_vector;
weapons_vector.push_back(sword);
weapons_vector.push_back(axe);
auto weapons = builder.CreateVector(weapons_vector);
// Second, serialize the rest of the objects needed by the Monster.
auto position = Vec3(1.0f, 2.0f, 3.0f);
auto name = builder.CreateString("MyMonster");
unsigned char inv_data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
auto inventory = builder.CreateVector(inv_data, 10);
// Shortcut for creating monster with all fields set:
auto orc = CreateMonster(builder, &position, 150, 80, name, inventory,
Color_Red, weapons, Equipment_Weapon, axe.Union());
builder.Finish(orc); // Serialize the root of the object.
```
I think it should be fairly obvious that using reflect-cpp on top drastically reduces the amount of boilerplate code.
## Adding field names
But what it more, unlike "normal" flatbuffers, flexbuffers also supports field names. Field names make it a lot easier to maintain backwards compatability.
```cpp
#include <rfl.hpp>
#include <rfl/flexbuf.hpp>
using Color = rfl::Literal<"Red", "Green", "Blue">;
struct Weapon {
rfl::Field<"name", std::string> name;
rfl::Field<"damage", short> damage;
};
using Equipment = rfl::Variant<rfl::Field<"weapon", Weapon>>;
struct Vec3 {
rfl::Field<"x", float> x;
rfl::Field<"y", float> y;
rfl::Field<"z", float> z;
};
struct Monster {
rfl::Field<"pos", Vec3> pos;
rfl::Field<"mana", short> mana = 150;
rfl::Field<"hp", short> hp = 100;
rfl::Field<"name", std::string> name;
rfl::Field<"friendly", bool> friendly = false;
rfl::Field<"inventory", std::vector<std::uint8_t>> inventory;
rfl::Field<"color", Color> color = Color::make<"Blue">();
rfl::Field<"weapons", std::vector<Weapon>> weapons;
rfl::Field<"equipped", Equipment> equipped;
rfl::Field<"path", std::vector<Vec3>> path;
};
const auto sword = Weapon{.name = "Sword", .damage = 3};
const auto axe = Weapon{.name = "Axe", .damage = 5};
const auto weapons = std::vector<Weapon>({sword, axe});
const auto position = Vec3{1.0f, 2.0f, 3.0f};
const auto inventory =
std::vector<std::uint8_t>({0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
const auto orc = Monster{.pos = position,
.mana = 150,
.hp = 80,
.name = "MyMonster",
.inventory = inventory,
.color = Color::make<"Red">(),
.weapons = weapons,
.equipped = rfl::make_field<"weapon">(axe),
.path = rfl::default_value};
const auto bytes = rfl::flexbuf::write(orc);
const auto res = rfl::flexbuf::read<Monster>(bytes);
```
## Reading and writing
Suppose you have a struct like this:
```cpp
struct Person {
std::string first_name;
std::string last_name;
rfl::Timestamp<"%Y-%m-%d"> birthday;
std::vector<Person> children;
};
```
A `person` can be turned into a bytes vector like this:
```cpp
const auto person = Person{...};
const auto bytes = rfl::flexbuf::write(person);
```
You can parse bytes like this:
```cpp
const rfl::Result<Person> result = rfl::flexbuf::read<Person>(bytes);
```
## Loading and saving
You can also load and save to disc using a very similar syntax:
```cpp
const rfl::Result<Person> result = rfl::flexbuf::load<Person>("/path/to/file.fb");
const auto person = Person{...};
rfl::flexbuf::save("/path/to/file.fb", person);
```
## Custom constructors
One of the great things about C++ is that it gives you control over
when and how you code is compiled.
For large and complex systems of structs, it is often a good idea to split up
your code into smaller compilation units. You can do so using custom constructors.
For the flexbuffers format, these must be a static function on your struct or class called
`from_flexbuf` that take a `rfl::flexbuf::Reader::InputVarType` as input and return
the class or the class wrapped in `rfl::Result`.
In your header file you can write something like this:
```cpp
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name;
rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">> birthday;
using InputVarType = typename rfl::flexbuf::Reader::InputVarType;
static rfl::Result<Person> from_flexbuf(const InputVarType& _obj);
};
```
And in your source file, you implement `from_flexbuf` as follows:
```cpp
rfl::Result<Person> Person::from_flexbuf(const InputVarType& _obj) {
const auto from_nt = [](auto&& _nt) {
return rfl::from_named_tuple<Person>(std::move(_nt));
};
return rfl::flexbuf::read<rfl::named_tuple_t<Person>>(_obj)
.transform(from_nt);
}
```
This will force the compiler to only compile the flexbuffers parsing when the
source file is compiled.
+7 -5
View File
@@ -1,6 +1,6 @@
# `std::variant` and `rfl::TaggedUnion`
# `std::variant`, `rfl::Variant` and `rfl::TaggedUnion`
## `std::variant` (untagged)
## `std::variant` or `rfl::Variant` (untagged)
Sometimes you know that the JSON object can be one of several alternatives. For example,
you might have several shapes like `Circle`, `Rectangle` or `Square`. For these kind of
@@ -20,6 +20,8 @@ struct Square {
rfl::Field<"width", double> width;
};
// NOTE: If you are using anonymous fields,
// you would probably have to use `rfl::Variant` instead.
using Shapes = std::variant<Circle, Rectangle, Square>;
const Shapes r = Rectangle{.height = 10, .width = 5};
@@ -36,14 +38,14 @@ several problems with this:
2) It leads to confusing error messages: If none of the alternatives can be matched, you will get an error message telling you why each of the alternatives couldn't be matched. Such error messages are very long-winding and hard to read.
3) It is dangerous. Imagine we had written `std::variant<Circle, Square, Rectangle>` instead of `std::variant<Circle, Rectangle, Square>`. This would mean that `Rectangle` could never be matched, because the fields in `Square` are a subset of `Rectangle`. This leads to very confusing bugs.
## `std::variant` (externally tagged)
## `std::variant` or `rfl::Variant` (externally tagged)
From a functional programming point-of-view, the most straightforward way to handle these problems is to add tags.
You can do that using `rfl::Field`:
```cpp
using TaggedVariant = std::variant<rfl::Field<"option1", Type1>, rfl::Field<"option2", Type2>, ...>;
using TaggedVariant = rfl::Variant<rfl::Field<"option1", Type1>, rfl::Field<"option2", Type2>, ...>;
```
The parser can now figure this out and will only try to parse the field that was indicated by the field name.
@@ -54,7 +56,7 @@ We can rewrite the example from above:
```cpp
// Circle, Rectangle and Square are the same as above.
using Shapes = std::variant<rfl::Field<"circle", Circle>,
using Shapes = rfl::Variant<rfl::Field<"circle", Circle>,
rfl::Field<"rectangle", Rectangle>,
rfl::Field<"square", Square>>;
+1
View File
@@ -16,6 +16,7 @@
#include "rfl/TaggedUnion.hpp"
#include "rfl/Timestamp.hpp"
#include "rfl/Validator.hpp"
#include "rfl/Variant.hpp"
#include "rfl/always_false.hpp"
#include "rfl/as.hpp"
#include "rfl/comparisons.hpp"
+7 -6
View File
@@ -26,10 +26,9 @@ class Box {
Box(Box<T>&& _other) = default;
template <class U, typename std::enable_if<std::is_convertible_v<U, T>,
bool>::type = true>
template <class U>
Box(Box<U>&& _other) noexcept
: ptr_(std::make_unique<T>(std::forward<U>(*_other))) {}
: ptr_(std::forward<std::unique_ptr<U>>(_other.ptr())) {}
~Box() = default;
@@ -43,10 +42,9 @@ class Box {
Box<T>& operator=(Box<T>&& _other) noexcept = default;
/// Move assignment operator
template <class U, typename std::enable_if<std::is_convertible_v<U, T>,
bool>::type = true>
template <class U>
Box<T>& operator=(Box<U>&& _other) noexcept {
ptr_ = std::make_unique<T>(std::forward<U>(*_other));
ptr_ = std::forward<std::unique_ptr<U>>(_other.ptr());
return *this;
}
@@ -62,6 +60,9 @@ class Box {
/// Returns the underlying object.
T* operator->() const { return ptr_.get(); }
/// Returns the underlying unique_ptr
std::unique_ptr<T>& ptr() { return ptr_; }
/// Returns the underlying unique_ptr
const std::unique_ptr<T>& ptr() const { return ptr_; }
+9 -10
View File
@@ -26,14 +26,12 @@ class Ref {
Ref(Ref<T>&& _other) = default;
template <class U, typename std::enable_if<std::is_convertible_v<U, T>,
bool>::type = true>
template <class U>
Ref(const Ref<U>& _other) : ptr_(_other.ptr()) {}
template <class U, typename std::enable_if<std::is_convertible_v<U, T>,
bool>::type = true>
template <class U>
Ref(Ref<U>&& _other) noexcept
: ptr_(std::make_shared<T>(std::forward<U>(*_other))) {}
: ptr_(std::forward<std::shared_ptr<U>>(_other.ptr())) {}
~Ref() = default;
@@ -52,22 +50,23 @@ class Ref {
/// Returns the underlying object.
T* operator->() const { return ptr_.get(); }
/// Returns the underlying shared_ptr
std::shared_ptr<T>& ptr() { return ptr_; }
/// Returns the underlying shared_ptr
const std::shared_ptr<T>& ptr() const { return ptr_; }
/// Copy assignment operator.
template <class U, typename std::enable_if<std::is_convertible_v<U, T>,
bool>::type = true>
template <class U>
Ref<T>& operator=(const Ref<U>& _other) {
ptr_ = _other.ptr();
return *this;
}
/// Move assignment operator
template <class U, typename std::enable_if<std::is_convertible_v<U, T>,
bool>::type = true>
template <class U>
Ref<T>& operator=(Ref<U>&& _other) noexcept {
ptr_ = std::make_shared<T>(std::forward<U>(*_other));
ptr_ = std::forward<std::shared_ptr<U>>(_other.ptr());
return *this;
}
+84
View File
@@ -0,0 +1,84 @@
#ifndef RFL_VARIANT_HPP_
#define RFL_VARIANT_HPP_
#include <variant>
namespace rfl {
template <class... AlternativeTypes>
struct Variant {
/// The type of the underlying variant.
using VariantType = std::variant<AlternativeTypes...>;
Variant(const VariantType& _variant) : variant_(_variant) {}
Variant(VariantType&& _variant) noexcept : variant_(std::move(_variant)) {}
Variant(const Variant<AlternativeTypes...>& _variant) = default;
Variant(Variant<AlternativeTypes...>&& _variant) noexcept = default;
template <class T,
typename std::enable_if<std::is_convertible_v<T, VariantType>,
bool>::type = true>
Variant(const T& _t) : variant_(_t) {}
template <class T,
typename std::enable_if<std::is_convertible_v<T, VariantType>,
bool>::type = true>
Variant(T&& _t) noexcept : variant_(std::forward<T>(_t)) {}
~Variant() = default;
/// Assigns the underlying object.
Variant<AlternativeTypes...>& operator=(const VariantType& _variant) {
variant_ = _variant;
return *this;
}
/// Assigns the underlying object.
Variant<AlternativeTypes...>& operator=(VariantType&& _variant) {
variant_ = std::move(_variant);
return *this;
}
/// Assigns the underlying object.
template <class T,
typename std::enable_if<std::is_convertible_v<T, VariantType>,
bool>::type = true>
Variant<AlternativeTypes...>& operator=(T&& _variant) {
variant_ = std::forward<T>(_variant);
return *this;
}
/// Assigns the underlying object.
template <class T,
typename std::enable_if<std::is_convertible_v<T, VariantType>,
bool>::type = true>
Variant<AlternativeTypes...>& operator=(const T& _variant) {
variant_ = _variant;
return *this;
}
/// Assigns the underlying object.
Variant<AlternativeTypes...>& operator=(
const Variant<AlternativeTypes...>& _other) = default;
/// Assigns the underlying object.
Variant<AlternativeTypes...>& operator=(
Variant<AlternativeTypes...>&& _other) = default;
/// Returns the underlying variant.
VariantType& variant() { return variant_; }
/// Returns the underlying variant.
const VariantType& variant() const { return variant_; }
/// The underlying variant - a Variant is a thin wrapper
/// around a variant that is mainly used for parsing.
VariantType variant_;
};
} // namespace rfl
#endif
+12
View File
@@ -0,0 +1,12 @@
#ifndef FLEXBUF_FLEXBUF_HPP_
#define FLEXBUF_FLEXBUF_HPP_
#include "rfl/flexbuf/Parser.hpp"
#include "rfl/flexbuf/Reader.hpp"
#include "rfl/flexbuf/Writer.hpp"
#include "rfl/flexbuf/load.hpp"
#include "rfl/flexbuf/read.hpp"
#include "rfl/flexbuf/save.hpp"
#include "rfl/flexbuf/write.hpp"
#endif
+59
View File
@@ -0,0 +1,59 @@
#ifndef FLEXBUF_OUTPUTARRAY_HPP_
#define FLEXBUF_OUTPUTARRAY_HPP_
#include <flatbuffers/flexbuffers.h>
#include <optional>
#include <string>
#include "rfl/Ref.hpp"
#include "rfl/flexbuf/OutputVar.hpp"
namespace rfl {
namespace flexbuf {
class OutputArray : public OutputVar {
public:
OutputArray() {}
~OutputArray() = default;
/// Inserts all elements into the builder.
void insert(const std::optional<std::string>& _key,
flexbuffers::Builder* _fbb) final {
/// We have to catch the edge case of an empty vector,
/// because flexbuf ignores empty vectors/maps.
if (vars_.size() == 0) {
if (_key) {
_fbb->Null(_key->c_str());
} else {
_fbb->Null();
}
return;
}
const auto start =
_key ? _fbb->StartVector(_key->c_str()) : _fbb->StartVector();
for (const auto& var : vars_) {
var->insert(std::nullopt, _fbb);
}
_fbb->EndVector(start, false, false);
};
/// Whether this is null.
bool is_null() const final { return false; }
/// Adds a new element to the vector.
void push_back(const Ref<OutputVar>& _var) { vars_.push_back(_var); }
private:
/// The underlying variables.
std::vector<Ref<OutputVar>> vars_;
};
} // namespace flexbuf
} // namespace rfl
#endif
+38
View File
@@ -0,0 +1,38 @@
#ifndef FLEXBUF_OUTPUTNULL_HPP_
#define FLEXBUF_OUTPUTNULL_HPP_
#include <flatbuffers/flexbuffers.h>
#include <optional>
#include <string>
#include "rfl/Ref.hpp"
#include "rfl/flexbuf/OutputVar.hpp"
namespace rfl {
namespace flexbuf {
class OutputNull : public OutputVar {
public:
OutputNull() {}
~OutputNull() = default;
/// Inserts all elements into the builder.
void insert(const std::optional<std::string>& _key,
flexbuffers::Builder* _fbb) final {
if (_key) {
_fbb->Null(_key->c_str());
} else {
_fbb->Null();
}
}
/// Whether this is null.
bool is_null() const final { return true; }
};
} // namespace flexbuf
} // namespace rfl
#endif
+61
View File
@@ -0,0 +1,61 @@
#ifndef FLEXBUF_OUTPUTOBJECT_HPP_
#define FLEXBUF_OUTPUTOBJECT_HPP_
#include <flatbuffers/flexbuffers.h>
#include <optional>
#include <string>
#include <utility>
#include "rfl/Ref.hpp"
#include "rfl/flexbuf/OutputVar.hpp"
namespace rfl {
namespace flexbuf {
class OutputObject : public OutputVar {
public:
OutputObject() {}
~OutputObject() = default;
/// Inserts all elements into the builder.
void insert(const std::optional<std::string>& _key,
flexbuffers::Builder* _fbb) final {
/// We have to catch the edge case of an empty map,
/// because flexbuf ignores empty vectors/maps.
if (vars_.size() == 0) {
if (_key) {
_fbb->Null(_key->c_str());
} else {
_fbb->Null();
}
return;
}
const auto start = _key ? _fbb->StartMap(_key->c_str()) : _fbb->StartMap();
for (const auto& [name, elem] : vars_) {
elem->insert(name, _fbb);
}
_fbb->EndMap(start);
};
/// Whether this is null.
bool is_null() const final { return false; }
/// Adds a new element to the vector.
void push_back(const std::string& _name, const Ref<OutputVar>& _var) {
vars_.push_back(std::make_pair(_name, _var));
}
private:
/// The underlying variables.
std::vector<std::pair<std::string, Ref<OutputVar>>> vars_;
};
} // namespace flexbuf
} // namespace rfl
#endif
+67
View File
@@ -0,0 +1,67 @@
#ifndef FLEXBUF_OUTPUTVALUE_HPP_
#define FLEXBUF_OUTPUTVALUE_HPP_
#include <flatbuffers/flexbuffers.h>
#include <optional>
#include <string>
#include <utility>
#include "rfl/Ref.hpp"
#include "rfl/always_false.hpp"
#include "rfl/flexbuf/OutputVar.hpp"
namespace rfl {
namespace flexbuf {
template <class T>
class OutputValue : public OutputVar {
public:
OutputValue(T _val) : val_(_val) {}
~OutputValue() = default;
/// Inserts all elements into the builder.
void insert(const std::optional<std::string>& _key,
flexbuffers::Builder* _fbb) final {
if constexpr (std::is_same<std::decay_t<T>, std::string>()) {
if (_key) {
_fbb->String(_key->c_str(), val_);
} else {
_fbb->String(val_);
}
} else if constexpr (std::is_same<std::decay_t<T>, bool>()) {
if (_key) {
_fbb->Bool(_key->c_str(), val_);
} else {
_fbb->Bool(val_);
}
} else if constexpr (std::is_floating_point<std::decay_t<T>>()) {
if (_key) {
_fbb->Double(_key->c_str(), val_);
} else {
_fbb->Double(val_);
}
} else if constexpr (std::is_integral<std::decay_t<T>>()) {
if (_key) {
_fbb->Int(_key->c_str(), val_);
} else {
_fbb->Int(val_);
}
} else {
static_assert(always_false_v<T>, "Unsupported type");
}
};
/// Whether this is null.
bool is_null() const final { return false; }
private:
/// The underlying value.
T val_;
};
} // namespace flexbuf
} // namespace rfl
#endif
+25
View File
@@ -0,0 +1,25 @@
#ifndef FLEXBUF_OUTPUTVAR_HPP_
#define FLEXBUF_OUTPUTVAR_HPP_
#include <flatbuffers/flexbuffers.h>
#include <optional>
#include <string>
namespace rfl {
namespace flexbuf {
class OutputVar {
public:
/// Inserts the value into the buffer.
virtual void insert(const std::optional<std::string>& _key,
flexbuffers::Builder* _fbb) = 0;
/// Whether this is null.
virtual bool is_null() const = 0;
};
} // namespace flexbuf
} // namespace rfl
#endif
+17
View File
@@ -0,0 +1,17 @@
#ifndef FLEXBUF_PARSER_HPP_
#define FLEXBUF_PARSER_HPP_
#include "rfl/flexbuf/Reader.hpp"
#include "rfl/flexbuf/Writer.hpp"
#include "rfl/parsing/Parser.hpp"
namespace rfl {
namespace flexbuf {
template <class T>
using Parser = rfl::parsing::Parser<Reader, Writer, T>;
}
} // namespace rfl
#endif
+169
View File
@@ -0,0 +1,169 @@
#ifndef FLEXBUF_READER_HPP_
#define FLEXBUF_READER_HPP_
#include <flatbuffers/flexbuffers.h>
#include <exception>
#include <map>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <type_traits>
#include <vector>
#include "rfl/Result.hpp"
#include "rfl/always_false.hpp"
namespace rfl {
namespace flexbuf {
struct Reader {
using InputArrayType = flexbuffers::Vector;
using InputObjectType = flexbuffers::Map;
using InputVarType = flexbuffers::Reference;
template <class T, class = void>
struct has_from_flexbuf : std::false_type {};
template <class T>
struct has_from_flexbuf<
T, std::enable_if_t<std::is_invocable_r<T, decltype(T::from_flexbuf),
InputVarType>::value>>
: std::true_type {};
template <class T>
struct has_from_flexbuf<
T, std::enable_if_t<std::is_invocable_r<
rfl::Result<T>, decltype(T::from_flexbuf), InputVarType>::value>>
: std::true_type {};
template <class T>
static constexpr bool has_custom_constructor = has_from_flexbuf<T>::value;
rfl::Result<InputVarType> get_field(
const std::string& _name, const InputObjectType& _obj) const noexcept {
const auto keys = _obj.Keys();
for (size_t i = 0; i < keys.size(); ++i) {
if (_name == keys[i].AsString().c_str()) {
return _obj.Values()[i];
}
}
return rfl::Error("Map does not contain any element called '" + _name +
"'.");
}
bool is_empty(const InputVarType& _var) const noexcept {
return _var.IsNull();
}
template <class T>
rfl::Result<T> to_basic_type(const InputVarType& _var) const noexcept {
if constexpr (std::is_same<std::decay_t<T>, std::string>()) {
if (!_var.IsString()) {
return rfl::Error("Could not cast to string.");
}
return std::string(_var.AsString().c_str());
} else if constexpr (std::is_same<std::decay_t<T>, bool>()) {
if (!_var.IsBool()) {
return rfl::Error("Could not cast to boolean.");
}
return _var.AsBool();
} else if constexpr (std::is_floating_point<std::decay_t<T>>()) {
if (!_var.IsNumeric()) {
return rfl::Error("Could not cast to double.");
}
return static_cast<T>(_var.AsDouble());
} else if constexpr (std::is_integral<std::decay_t<T>>()) {
if (!_var.IsNumeric()) {
return rfl::Error("Could not cast to int.");
}
return static_cast<T>(_var.AsInt64());
} else {
static_assert(rfl::always_false_v<T>, "Unsupported type.");
}
}
template <size_t size, class FunctionType>
std::array<std::optional<InputVarType>, size> to_fields_array(
const FunctionType& _fct, const InputObjectType& _obj) const noexcept {
std::array<std::optional<InputVarType>, size> f_arr;
const auto keys = _obj.Keys();
const auto values = _obj.Values();
const auto num_values = std::min(keys.size(), values.size());
for (size_t i = 0; i < num_values; ++i) {
const auto ix = _fct(std::string_view(keys[i].AsString().c_str()));
if (ix != -1) {
f_arr[ix] = values[i];
}
}
return f_arr;
}
rfl::Result<InputArrayType> to_array(
const InputVarType& _var) const noexcept {
// Necessary, because we write empty vectors as null.
if (_var.IsNull()) {
return flexbuffers::Vector::EmptyVector();
}
if (!_var.IsVector()) {
return rfl::Error("Could not cast to Vector.");
}
return _var.AsVector();
}
std::vector<std::pair<std::string, InputVarType>> to_map(
const InputObjectType& _obj) const noexcept {
std::vector<std::pair<std::string, InputVarType>> m;
const auto keys = _obj.Keys();
const auto values = _obj.Values();
const auto size = std::min(keys.size(), values.size());
for (size_t i = 0; i < size; ++i) {
m.emplace_back(
std::make_pair(std::string(keys[i].AsString().c_str()), values[i]));
}
return m;
}
rfl::Result<InputObjectType> to_object(
const InputVarType& _var) const noexcept {
// Necessary, because we write empty maps as null.
if (_var.IsNull()) {
return flexbuffers::Map::EmptyMap();
}
if (!_var.IsMap()) {
return rfl::Error("Could not cast to Map!");
}
return _var.AsMap();
}
std::vector<InputVarType> to_vec(const InputArrayType& _arr) const noexcept {
const auto size = _arr.size();
std::vector<InputVarType> vec;
for (size_t i = 0; i < size; ++i) {
vec.push_back(_arr[i]);
}
return vec;
}
template <class T>
rfl::Result<T> use_custom_constructor(
const InputVarType& _var) const noexcept {
try {
return T::from_flexbuf(_var);
} catch (std::exception& e) {
return rfl::Error(e.what());
}
}
};
} // namespace flexbuf
} // namespace rfl
#endif
+69
View File
@@ -0,0 +1,69 @@
#ifndef FLEXBUF_WRITER_HPP_
#define FLEXBUF_WRITER_HPP_
#include <flatbuffers/flexbuffers.h>
#include <exception>
#include <functional>
#include <map>
#include <optional>
#include <sstream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <type_traits>
#include <vector>
#include "rfl/Ref.hpp"
#include "rfl/Result.hpp"
#include "rfl/flexbuf/OutputArray.hpp"
#include "rfl/flexbuf/OutputNull.hpp"
#include "rfl/flexbuf/OutputObject.hpp"
#include "rfl/flexbuf/OutputValue.hpp"
#include "rfl/flexbuf/OutputVar.hpp"
namespace rfl {
namespace flexbuf {
struct Writer {
using OutputArrayType = Ref<OutputArray>;
using OutputObjectType = Ref<OutputObject>;
using OutputVarType = Ref<OutputVar>;
Writer() {}
~Writer() = default;
void add(const OutputVarType& _var, OutputArrayType* _arr) const noexcept {
(*_arr)->push_back(_var);
}
OutputVarType empty_var() const noexcept { return Ref<OutputNull>::make(); }
template <class T>
OutputVarType from_basic_type(const T& _var) const noexcept {
return Ref<OutputValue<T>>::make(_var);
}
OutputArrayType new_array() const noexcept {
return Ref<OutputArray>::make();
}
OutputObjectType new_object() const noexcept {
return Ref<OutputObject>::make();
}
bool is_empty(const OutputVarType& _var) const noexcept {
return _var->is_null();
}
void set_field(const std::string& _name, const OutputVarType& _var,
OutputObjectType* _obj) const noexcept {
(*_obj)->push_back(_name, _var);
}
};
} // namespace flexbuf
} // namespace rfl
#endif
+20
View File
@@ -0,0 +1,20 @@
#ifndef RFL_FLEXBUF_LOAD_HPP_
#define RFL_FLEXBUF_LOAD_HPP_
#include "rfl/Result.hpp"
#include "rfl/flexbuf/read.hpp"
#include "rfl/io/load_bytes.hpp"
namespace rfl {
namespace flexbuf {
template <class T>
Result<T> load(const std::string& _fname) {
const auto read_bytes = [](const auto& _bytes) { return read<T>(_bytes); };
return rfl::io::load_bytes(_fname).and_then(read_bytes);
}
} // namespace flexbuf
} // namespace rfl
#endif
+40
View File
@@ -0,0 +1,40 @@
#ifndef FLEXBUF_READ_HPP_
#define FLEXBUF_READ_HPP_
#include <flatbuffers/flexbuffers.h>
#include <vector>
#include "rfl/Result.hpp"
#include "rfl/flexbuf/Parser.hpp"
namespace rfl {
namespace flexbuf {
using InputVarType = typename Reader::InputVarType;
/// Parses an object from flexbuf var.
template <class T>
Result<T> read(const InputVarType& _obj) {
const auto r = Reader();
return Parser<T>::read(r, _obj);
}
/// Parses an object from flexbuf using reflection.
template <class T>
Result<T> read(const unsigned char* _bytes, const size_t _size) {
const InputVarType root =
flexbuffers::GetRoot(reinterpret_cast<const uint8_t*>(_bytes), _size);
return read<T>(root);
}
/// Parses an object from flexbuf using reflection.
template <class T>
Result<T> read(const std::vector<unsigned char>& _bytes) {
return read<T>(_bytes.data(), _bytes.size());
}
} // namespace flexbuf
} // namespace rfl
#endif
+23
View File
@@ -0,0 +1,23 @@
#ifndef RFL_FLEXBUF_SAVE_HPP_
#define RFL_FLEXBUF_SAVE_HPP_
#include <fstream>
#include <iostream>
#include <string>
#include "rfl/Result.hpp"
#include "rfl/flexbuf/write.hpp"
#include "rfl/io/save_bytes.hpp"
namespace rfl {
namespace flexbuf {
template <class T>
Result<Nothing> save(const std::string& _fname, const T& _obj) {
return rfl::io::save_bytes(_fname, write(_obj));
}
} // namespace flexbuf
} // namespace rfl
#endif
+31
View File
@@ -0,0 +1,31 @@
#ifndef FLEXBUF_WRITE_HPP_
#define FLEXBUF_WRITE_HPP_
#include <flatbuffers/flexbuffers.h>
#include <cstddef>
#include <sstream>
#include <vector>
#include "rfl/flexbuf/Parser.hpp"
namespace rfl {
namespace flexbuf {
/// Writes an object to flexbuf.
template <class T>
std::vector<unsigned char> write(const T& _obj) {
auto w = Writer();
const auto flexbuf_obj = Parser<T>::write(w, _obj);
flexbuffers::Builder fbb;
flexbuf_obj->insert(std::nullopt, &fbb);
fbb.Finish();
const auto vec = fbb.GetBuffer();
const auto data = reinterpret_cast<const unsigned char*>(vec.data());
return std::vector<unsigned char>(data, data + vec.size());
}
} // namespace flexbuf
} // namespace rfl
#endif
+22
View File
@@ -5,6 +5,7 @@
#include "rfl/Field.hpp"
#include "rfl/Flatten.hpp"
#include "rfl/always_false.hpp"
#include "rfl/internal/StringLiteral.hpp"
namespace rfl {
@@ -12,18 +13,39 @@ namespace internal {
template <internal::StringLiteral _name, class Type>
inline auto to_ptr_field(Field<_name, Type>& _field) {
if constexpr (std::is_pointer_v<Type>) {
static_assert(always_false_v<Type>,
"Writing from raw pointers is dangerous and "
"therefore unsupported. "
"Please consider using std::unique_ptr, rfl::Box, "
"std::shared_ptr, rfl::Ref or std::optional instead.");
}
using T = std::remove_reference_t<Type>;
return Field<_name, T*>(&_field.value_);
}
template <internal::StringLiteral _name, class Type>
inline auto to_ptr_field(const Field<_name, Type>& _field) {
if constexpr (std::is_pointer_v<Type>) {
static_assert(always_false_v<Type>,
"Writing from raw pointers is dangerous and "
"therefore unsupported. "
"Please consider using std::unique_ptr, rfl::Box, "
"std::shared_ptr, rfl::Ref or std::optional instead.");
}
using T = std::remove_cvref_t<Type>;
return Field<_name, const T*>(&_field.value_);
}
template <class Type>
inline auto to_ptr_field(Flatten<Type>& _field) {
if constexpr (std::is_pointer_v<Type>) {
static_assert(always_false_v<Type>,
"Writing from raw pointers is dangerous and "
"therefore unsupported. "
"Please consider using std::unique_ptr, rfl::Box, "
"std::shared_ptr, rfl::Ref or std::optional instead.");
}
using T = std::remove_reference_t<Type>;
return Flatten<T*>(&_field.value_);
}
+29
View File
@@ -0,0 +1,29 @@
#ifndef RFL_IO_LOAD_BYTES_HPP_
#define RFL_IO_LOAD_BYTES_HPP_
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include "rfl/Result.hpp"
namespace rfl {
namespace io {
Result<std::vector<unsigned char>> load_bytes(const std::string& _fname) {
std::ifstream input(_fname, std::ios::binary);
if (input.is_open()) {
std::istreambuf_iterator<char> begin(input), end;
const auto bytes = std::vector<unsigned char>(begin, end);
input.close();
return bytes;
} else {
return rfl::Error("File '" + _fname + "' not found!");
}
}
} // namespace io
} // namespace rfl
#endif
+29
View File
@@ -0,0 +1,29 @@
#ifndef RFL_IO_SAVE_BYTES_HPP_
#define RFL_IO_SAVE_BYTES_HPP_
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include "rfl/Result.hpp"
namespace rfl {
namespace io {
Result<Nothing> save_bytes(const std::string& _fname,
const std::vector<unsigned char>& _bytes) {
try {
std::ofstream output(_fname, std::ios::out | std::ios::binary);
output.write(reinterpret_cast<const char*>(_bytes.data()), _bytes.size());
output.close();
} catch (std::exception& e) {
return Error(e.what());
}
return Nothing{};
}
} // namespace io
} // namespace rfl
#endif
+122 -123
View File
@@ -22,153 +22,152 @@ namespace rfl {
namespace json {
struct Reader {
struct YYJSONInputArray {
YYJSONInputArray(yyjson_val* _val) : val_(_val) {}
yyjson_val* val_;
};
struct YYJSONInputArray {
YYJSONInputArray(yyjson_val* _val) : val_(_val) {}
yyjson_val* val_;
};
struct YYJSONInputObject {
YYJSONInputObject(yyjson_val* _val) : val_(_val) {}
yyjson_val* val_;
};
struct YYJSONInputObject {
YYJSONInputObject(yyjson_val* _val) : val_(_val) {}
yyjson_val* val_;
};
struct YYJSONInputVar {
YYJSONInputVar() : val_(nullptr) {}
YYJSONInputVar(yyjson_val* _val) : val_(_val) {}
yyjson_val* val_;
};
struct YYJSONInputVar {
YYJSONInputVar() : val_(nullptr) {}
YYJSONInputVar(yyjson_val* _val) : val_(_val) {}
yyjson_val* val_;
};
using InputArrayType = YYJSONInputArray;
using InputObjectType = YYJSONInputObject;
using InputVarType = YYJSONInputVar;
using InputArrayType = YYJSONInputArray;
using InputObjectType = YYJSONInputObject;
using InputVarType = YYJSONInputVar;
template <class T, class = void>
struct has_from_json_obj : std::false_type {};
template <class T, class = void>
struct has_from_json_obj : std::false_type {};
template <class T>
struct has_from_json_obj<T, std::enable_if_t<std::is_invocable_r<
T, decltype(T::from_json_obj),
typename Reader::InputVarType>::value>>
: std::true_type {};
template <class T>
struct has_from_json_obj<
T,
std::enable_if_t<std::is_invocable_r<
T, decltype(T::from_json_obj), typename Reader::InputVarType>::value>>
: std::true_type {};
template <class T>
struct has_from_json_obj<T, std::enable_if_t<std::is_invocable_r<
rfl::Result<T>, decltype(T::from_json_obj),
typename Reader::InputVarType>::value>>
: std::true_type {};
template <class T>
struct has_from_json_obj<T, std::enable_if_t<std::is_invocable_r<
rfl::Result<T>, decltype(T::from_json_obj),
typename Reader::InputVarType>::value>>
: std::true_type {};
template <class T>
static constexpr bool has_custom_constructor = has_from_json_obj<T>::value;
template <class T>
static constexpr bool has_custom_constructor = has_from_json_obj<T>::value;
rfl::Result<InputVarType> get_field(
const std::string& _name, const InputObjectType _obj) const noexcept {
const auto var = InputVarType(yyjson_obj_get(_obj.val_, _name.c_str()));
if (!var.val_) {
return rfl::Error("Object contains no field named '" + _name +
"'.");
}
return var;
rfl::Result<InputVarType> get_field(
const std::string& _name, const InputObjectType _obj) const noexcept {
const auto var = InputVarType(yyjson_obj_get(_obj.val_, _name.c_str()));
if (!var.val_) {
return rfl::Error("Object contains no field named '" + _name + "'.");
}
return var;
}
bool is_empty(const InputVarType _var) const noexcept {
return !_var.val_ || yyjson_is_null(_var.val_);
}
bool is_empty(const InputVarType _var) const noexcept {
return !_var.val_ || yyjson_is_null(_var.val_);
}
template <class T>
rfl::Result<T> to_basic_type(const InputVarType _var) const noexcept {
if constexpr (std::is_same<std::decay_t<T>, std::string>()) {
const auto r = yyjson_get_str(_var.val_);
if (r == NULL) {
return rfl::Error("Could not cast to string.");
}
return std::string(r);
} else if constexpr (std::is_same<std::decay_t<T>, bool>()) {
if (!yyjson_is_bool(_var.val_)) {
return rfl::Error("Could not cast to boolean.");
}
return yyjson_get_bool(_var.val_);
} else if constexpr (std::is_floating_point<std::decay_t<T>>()) {
if (!yyjson_is_num(_var.val_)) {
return rfl::Error("Could not cast to double.");
}
return static_cast<T>(yyjson_get_num(_var.val_));
} else if constexpr (std::is_integral<std::decay_t<T>>()) {
if (!yyjson_is_int(_var.val_)) {
return rfl::Error("Could not cast to int.");
}
return static_cast<T>(yyjson_get_int(_var.val_));
} else {
static_assert(rfl::always_false_v<T>, "Unsupported type.");
}
template <class T>
rfl::Result<T> to_basic_type(const InputVarType _var) const noexcept {
if constexpr (std::is_same<std::decay_t<T>, std::string>()) {
const auto r = yyjson_get_str(_var.val_);
if (r == NULL) {
return rfl::Error("Could not cast to string.");
}
return std::string(r);
} else if constexpr (std::is_same<std::decay_t<T>, bool>()) {
if (!yyjson_is_bool(_var.val_)) {
return rfl::Error("Could not cast to boolean.");
}
return yyjson_get_bool(_var.val_);
} else if constexpr (std::is_floating_point<std::decay_t<T>>()) {
if (!yyjson_is_num(_var.val_)) {
return rfl::Error("Could not cast to double.");
}
return static_cast<T>(yyjson_get_num(_var.val_));
} else if constexpr (std::is_integral<std::decay_t<T>>()) {
if (!yyjson_is_int(_var.val_)) {
return rfl::Error("Could not cast to int.");
}
return static_cast<T>(yyjson_get_int(_var.val_));
} else {
static_assert(rfl::always_false_v<T>, "Unsupported type.");
}
}
rfl::Result<InputArrayType> to_array(
const InputVarType _var) const noexcept {
if (!yyjson_is_arr(_var.val_)) {
return rfl::Error("Could not cast to array!");
}
return InputArrayType(_var.val_);
rfl::Result<InputArrayType> to_array(const InputVarType _var) const noexcept {
if (!yyjson_is_arr(_var.val_)) {
return rfl::Error("Could not cast to array!");
}
return InputArrayType(_var.val_);
}
template <size_t size, class FunctionType>
std::array<InputVarType, size> to_fields_array(
const FunctionType _fct, const InputObjectType _obj) const noexcept {
std::array<InputVarType, size> f_arr;
yyjson_obj_iter iter;
yyjson_obj_iter_init(_obj.val_, &iter);
yyjson_val* key;
while ((key = yyjson_obj_iter_next(&iter))) {
const char* k = yyjson_get_str(key);
const auto ix = _fct(std::string_view(k));
if (ix != -1) {
f_arr[ix] = InputVarType(yyjson_obj_iter_get_val(key));
}
}
return f_arr;
template <size_t size, class FunctionType>
std::array<std::optional<InputVarType>, size> to_fields_array(
const FunctionType _fct, const InputObjectType _obj) const noexcept {
std::array<std::optional<InputVarType>, size> f_arr;
yyjson_obj_iter iter;
yyjson_obj_iter_init(_obj.val_, &iter);
yyjson_val* key;
while ((key = yyjson_obj_iter_next(&iter))) {
const char* k = yyjson_get_str(key);
const auto ix = _fct(std::string_view(k));
if (ix != -1) {
f_arr[ix] = InputVarType(yyjson_obj_iter_get_val(key));
}
}
return f_arr;
}
std::vector<std::pair<std::string, InputVarType>> to_map(
const InputObjectType _obj) const noexcept {
std::vector<std::pair<std::string, InputVarType>> m;
yyjson_obj_iter iter;
yyjson_obj_iter_init(_obj.val_, &iter);
yyjson_val* key;
while ((key = yyjson_obj_iter_next(&iter))) {
auto p = std::make_pair(yyjson_get_str(key),
InputVarType(yyjson_obj_iter_get_val(key)));
m.emplace_back(std::move(p));
}
return m;
std::vector<std::pair<std::string, InputVarType>> to_map(
const InputObjectType _obj) const noexcept {
std::vector<std::pair<std::string, InputVarType>> m;
yyjson_obj_iter iter;
yyjson_obj_iter_init(_obj.val_, &iter);
yyjson_val* key;
while ((key = yyjson_obj_iter_next(&iter))) {
auto p = std::make_pair(yyjson_get_str(key),
InputVarType(yyjson_obj_iter_get_val(key)));
m.emplace_back(std::move(p));
}
return m;
}
rfl::Result<InputObjectType> to_object(
const InputVarType _var) const noexcept {
if (!yyjson_is_obj(_var.val_)) {
return rfl::Error("Could not cast to object!");
}
return InputObjectType(_var.val_);
rfl::Result<InputObjectType> to_object(
const InputVarType _var) const noexcept {
if (!yyjson_is_obj(_var.val_)) {
return rfl::Error("Could not cast to object!");
}
return InputObjectType(_var.val_);
}
std::vector<InputVarType> to_vec(const InputArrayType _arr) const noexcept {
std::vector<InputVarType> vec;
yyjson_val* val;
yyjson_arr_iter iter;
yyjson_arr_iter_init(_arr.val_, &iter);
while ((val = yyjson_arr_iter_next(&iter))) {
vec.push_back(InputVarType(val));
}
return vec;
std::vector<InputVarType> to_vec(const InputArrayType _arr) const noexcept {
std::vector<InputVarType> vec;
yyjson_val* val;
yyjson_arr_iter iter;
yyjson_arr_iter_init(_arr.val_, &iter);
while ((val = yyjson_arr_iter_next(&iter))) {
vec.push_back(InputVarType(val));
}
return vec;
}
template <class T>
rfl::Result<T> use_custom_constructor(
const InputVarType _var) const noexcept {
try {
return T::from_json_obj(_var);
} catch (std::exception& e) {
return rfl::Error(e.what());
}
template <class T>
rfl::Result<T> use_custom_constructor(
const InputVarType _var) const noexcept {
try {
return T::from_json_obj(_var);
} catch (std::exception& e) {
return rfl::Error(e.what());
}
}
};
} // namespace json
+2 -1
View File
@@ -10,7 +10,8 @@ namespace json {
template <class T>
Result<T> load(const std::string& _fname) {
return rfl::io::load_string(_fname).and_then(read<T>);
const auto read_string = [](const auto& _str) { return read<T>(_str); };
return rfl::io::load_string(_fname).and_then(read_string);
}
} // namespace json
+1 -1
View File
@@ -14,7 +14,7 @@ namespace json {
template <class T>
Result<Nothing> save(const std::string& _fname, const T& _obj) {
return rfl::io::save_string(write(_obj));
return rfl::io::save_string(_fname, write(_obj));
}
} // namespace json
+44 -47
View File
@@ -5,6 +5,7 @@
#include <concepts>
#include <cstdint>
#include <functional>
#include <optional>
#include <string>
#include <string_view>
@@ -19,62 +20,58 @@ concept IsReader = requires(R r, std::string name,
typename R::InputArrayType arr,
typename R::InputObjectType obj,
typename R::InputVarType var) {
/// Any Reader needs to define the following:
///
/// 1) An InputArrayType, which must be an array-like data structure.
/// 2) An InputObjectType, which must contain key-value pairs.
/// 3) An InputVarType, which must be able to represent either
/// InputArrayType, InputObjectType or a basic type (bool, integral,
/// floating point, std::string).
/// 4) A static constexpr bool has_custom_constructor, that determines
/// whether the class in question as a custom constructor, which might
/// be called something like from_json_obj(...).
/// Any Reader needs to define the following:
///
/// 1) An InputArrayType, which must be an array-like data structure.
/// 2) An InputObjectType, which must contain key-value pairs.
/// 3) An InputVarType, which must be able to represent either
/// InputArrayType, InputObjectType or a basic type (bool, integral,
/// floating point, std::string).
/// 4) A static constexpr bool has_custom_constructor, that determines
/// whether the class in question as a custom constructor, which might
/// be called something like from_json_obj(...).
/// Retrieves a particular field from an object.
{
r.get_field(name, obj)
} -> std::same_as<rfl::Result<typename R::InputVarType>>;
/// Retrieves a particular field from an object.
{
r.get_field(name, obj)
} -> std::same_as<rfl::Result<typename R::InputVarType>>;
/// Determines whether a variable is empty (the NULL type).
{ r.is_empty(var) } -> std::same_as<bool>;
/// Determines whether a variable is empty (the NULL type).
{ r.is_empty(var) } -> std::same_as<bool>;
/// Transforms var to a basic type (bool, integral,
/// floating point, std::string)
{ r.template to_basic_type<T>(var) } -> std::same_as<rfl::Result<T>>;
/// Transforms var to a basic type (bool, integral,
/// floating point, std::string)
{ r.template to_basic_type<T>(var) } -> std::same_as<rfl::Result<T>>;
/// fct is a function that turns the field name into the field index of the
/// struct. It returns -1, if the fields does not exist on the struct. This
/// returns an std::array that can be used to build up the struct.
{
r.template to_fields_array<6>(fct, obj)
} -> std::same_as<std::array<typename R::InputVarType, 6>>;
/// fct is a function that turns the field name into the field index of the
/// struct. It returns -1, if the fields does not exist on the struct. This
/// returns an std::array that can be used to build up the struct.
{
r.template to_fields_array<6>(fct, obj)
} -> std::same_as<std::array<std::optional<typename R::InputVarType>, 6>>;
/// Casts var as an InputArrayType.
{
r.to_array(var)
} -> std::same_as<rfl::Result<typename R::InputArrayType>>;
/// Casts var as an InputArrayType.
{ r.to_array(var) } -> std::same_as<rfl::Result<typename R::InputArrayType>>;
/// Iterates through an object and writes the contained key-value pairs into
/// a vector.
{
r.to_map(obj)
} -> std::same_as<
std::vector<std::pair<std::string, typename R::InputVarType>>>;
/// Iterates through an object and writes the contained key-value pairs into
/// a vector.
{
r.to_map(obj)
} -> std::same_as<
std::vector<std::pair<std::string, typename R::InputVarType>>>;
/// Casts var as an InputObjectType.
{
r.to_object(var)
} -> std::same_as<rfl::Result<typename R::InputObjectType>>;
/// Casts var as an InputObjectType.
{
r.to_object(var)
} -> std::same_as<rfl::Result<typename R::InputObjectType>>;
/// Iterates through an array and writes the contained vars into
/// a vector.
{ r.to_vec(arr) } -> std::same_as<std::vector<typename R::InputVarType>>;
/// Iterates through an array and writes the contained vars into
/// a vector.
{ r.to_vec(arr) } -> std::same_as<std::vector<typename R::InputVarType>>;
/// Uses the custom constructor, if it has been determined that T has one
/// (see above).
{
r.template use_custom_constructor<T>(var)
} -> std::same_as<rfl::Result<T>>;
/// Uses the custom constructor, if it has been determined that T has one
/// (see above).
{ r.template use_custom_constructor<T>(var) } -> std::same_as<rfl::Result<T>>;
};
} // namespace parsing
+42 -14
View File
@@ -370,7 +370,8 @@ struct Parser<R, W, NamedTuple<FieldTypes...>> {
template <class... Args>
static Result<NamedTuple<FieldTypes...>> build_named_tuple_recursively(
const R& _r,
const std::array<InputVarType, sizeof...(FieldTypes)>& _fields_vec,
const std::array<std::optional<InputVarType>, sizeof...(FieldTypes)>&
_fields_arr,
Args&&... _args) noexcept {
constexpr auto i = sizeof...(Args);
@@ -382,32 +383,32 @@ struct Parser<R, W, NamedTuple<FieldTypes...>> {
using ValueType = std::decay_t<typename FieldType::Type>;
const auto& f = std::get<i>(_fields_vec);
const auto& f = std::get<i>(_fields_arr);
if (_r.is_empty(f)) {
if (!f) {
if constexpr (is_required<ValueType>()) {
const auto key = FieldType::name_.str();
return collect_errors<i + 1>(
_r, _fields_vec,
_r, _fields_arr,
std::vector<Error>(
{Error("Field named '" + key + "' not found!")}));
} else {
return build_named_tuple_recursively(
_r, _fields_vec, std::move(_args)..., FieldType(ValueType()));
_r, _fields_arr, std::move(_args)..., FieldType(ValueType()));
}
}
const auto build = [&](auto&& _value) {
return build_named_tuple_recursively(
_r, _fields_vec, std::move(_args)..., FieldType(std::move(_value)));
_r, _fields_arr, std::move(_args)..., FieldType(std::move(_value)));
};
const auto handle_error = [&](Error&& _error) {
return collect_errors<i + 1>(_r, _fields_vec,
return collect_errors<i + 1>(_r, _fields_arr,
std::vector<Error>({std::move(_error)}));
};
return get_value<FieldType>(_r, f).or_else(handle_error).and_then(build);
return get_value<FieldType>(_r, *f).or_else(handle_error).and_then(build);
}
}
@@ -416,7 +417,8 @@ struct Parser<R, W, NamedTuple<FieldTypes...>> {
template <int _i>
static Error collect_errors(
const R& _r,
const std::array<InputVarType, sizeof...(FieldTypes)>& _fields_vec,
const std::array<std::optional<InputVarType>, sizeof...(FieldTypes)>&
_fields_arr,
std::vector<Error> _errors) noexcept {
if constexpr (_i == sizeof...(FieldTypes)) {
if (_errors.size() == 1) {
@@ -435,14 +437,14 @@ struct Parser<R, W, NamedTuple<FieldTypes...>> {
using ValueType = std::decay_t<typename FieldType::Type>;
const auto& f = std::get<_i>(_fields_vec);
const auto& f = std::get<_i>(_fields_arr);
if (_r.is_empty(f)) {
if (!f) {
if constexpr (is_required<ValueType>()) {
const auto key = FieldType::name_.str();
_errors.emplace_back(Error("Field named '" + key + "' not found."));
}
return collect_errors<_i + 1>(_r, _fields_vec, std::move(_errors));
return collect_errors<_i + 1>(_r, _fields_arr, std::move(_errors));
}
const auto add_error_if_applicable =
@@ -451,9 +453,9 @@ struct Parser<R, W, NamedTuple<FieldTypes...>> {
return _error;
};
get_value<FieldType>(_r, f).or_else(add_error_if_applicable);
get_value<FieldType>(_r, *f).or_else(add_error_if_applicable);
return collect_errors<_i + 1>(_r, _fields_vec, std::move(_errors));
return collect_errors<_i + 1>(_r, _fields_arr, std::move(_errors));
}
}
@@ -1008,6 +1010,32 @@ struct FieldVariantParser {
// ----------------------------------------------------------------------------
template <class R, class W, class... FieldTypes>
requires AreReaderAndWriter<R, W, rfl::Variant<FieldTypes...>>
struct Parser<R, W, rfl::Variant<FieldTypes...>> {
using InputVarType = typename R::InputVarType;
using OutputVarType = typename W::OutputVarType;
/// Expresses the variables as type T.
static Result<rfl::Variant<FieldTypes...>> read(
const R& _r, const InputVarType& _var) noexcept {
const auto to_rfl_variant = [](auto&& _var) {
return rfl::Variant<FieldTypes...>(
std::forward<std::variant<FieldTypes...>>(_var));
};
return Parser<R, W, std::variant<FieldTypes...>>::read(_r, _var).transform(
to_rfl_variant);
}
static OutputVarType write(
const W& _w, const rfl::Variant<FieldTypes...>& _variant) noexcept {
return Parser<R, W, std::variant<FieldTypes...>>::write(_w,
_variant.variant());
}
};
// ----------------------------------------------------------------------------
template <class R, class W, class... FieldTypes>
requires AreReaderAndWriter<R, W, std::variant<FieldTypes...>>
struct Parser<R, W, std::variant<FieldTypes...>> {
+23
View File
@@ -0,0 +1,23 @@
cmake_minimum_required(VERSION 3.4)
project(reflect-cpp-tests)
include_directories(
"../../include"
"../../../flatbuffers/include"
)
add_executable(
reflect-cpp-tests
"tests.cpp"
"../../src/yyjson.c"
)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -O2")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++20 -Wall -Wno-sign-compare -Wno-missing-braces -Wno-psabi -pthread -fno-strict-aliasing -fwrapv -O2 -ftemplate-backtrace-limit=0")
target_link_libraries(
reflect-cpp-tests
/home/reflectcpp/flatbuffers/build/libflatbuffers.a
)
+25
View File
@@ -0,0 +1,25 @@
FROM ubuntu:22.04
ENV TZ=Europe/Berlin
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
RUN useradd reflectcpp
RUN apt-get update
RUN apt-get install -y git cmake
RUN apt install gcc-11 g++-11
WORKDIR /home/reflectcpp
RUN git clone https://github.com/google/flatbuffers.git
WORKDIR /home/reflectcpp/flatbuffers
RUN git checkout v23.5.26
RUN mkdir build
WORKDIR /home/reflectcpp/flatbuffers/build
RUN cmake .. -DCMAKE_C_COMPILER=gcc-11 -DCMAKE_CXX_COMPILER=g++-11
RUN make
WORKDIR /home/reflectcpp
COPY compile_on_docker.sh .
USER reflectcpp
+3
View File
@@ -0,0 +1,3 @@
#!/bin/bash
docker build --tag=reflectcpp_test_flexbuffers .
+3
View File
@@ -0,0 +1,3 @@
#!/bin/bash
docker run -v $PWD/../../:"/home/reflectcpp/reflect-cpp" --rm -it -t reflectcpp_test_flexbuffers bash compile_on_docker.sh
+5
View File
@@ -0,0 +1,5 @@
cd reflect-cpp/tests/flexbuffers
mkdir build
cd build
cmake .. -DCMAKE_C_COMPILER=gcc-11 -DCMAKE_CXX_COMPILER=g++-11
make
+25
View File
@@ -0,0 +1,25 @@
#include <iostream>
#include <rfl.hpp>
#include <rfl/flexbuf.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
void test_all_of() {
std::cout << "test_all_of" << std::endl;
using Age = rfl::Validator<unsigned int,
rfl::AllOf<rfl::Minimum<0>, rfl::Maximum<130>>>;
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name;
rfl::Field<"age", Age> age;
};
const auto homer =
Person{.first_name = "Homer", .last_name = "Simpson", .age = 45};
write_and_read(homer);
}
@@ -0,0 +1,51 @@
#include <iostream>
#include <rfl.hpp>
#include <rfl/flexbuf.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
void test_anonymous_fields() {
std::cout << "test_anonymous_fields" << std::endl;
using Age = rfl::Validator<unsigned int,
rfl::AllOf<rfl::Minimum<0>, rfl::Maximum<130>>>;
struct Person {
std::string first_name;
std::string last_name;
rfl::Timestamp<"%Y-%m-%d"> birthday;
Age age;
rfl::Email email;
std::vector<Person> children;
};
const auto bart = Person{.first_name = "Bart",
.last_name = "Simpson",
.birthday = "1987-04-19",
.age = 10,
.email = "bart@simpson.com"};
const auto lisa = Person{.first_name = "Lisa",
.last_name = "Simpson",
.birthday = "1987-04-19",
.age = 8,
.email = "lisa@simpson.com"};
const auto maggie = Person{.first_name = "Maggie",
.last_name = "Simpson",
.birthday = "1987-04-19",
.age = 0,
.email = "maggie@simpson.com"};
const auto homer =
Person{.first_name = "Homer",
.last_name = "Simpson",
.birthday = "1987-04-19",
.age = 45,
.email = "homer@simpson.com",
.children = std::vector<Person>({bart, lisa, maggie})};
write_and_read(homer);
}
+43
View File
@@ -0,0 +1,43 @@
#include <cassert>
#include <iostream>
#include <rfl.hpp>
#include <rfl/flexbuf.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
void test_box() {
std::cout << "test_box" << std::endl;
struct DecisionTree {
struct Leaf {
rfl::Field<"type", rfl::Literal<"Leaf">> type = rfl::default_value;
rfl::Field<"value", double> value;
};
struct Node {
rfl::Field<"type", rfl::Literal<"Node">> type = rfl::default_value;
rfl::Field<"criticalValue", double> critical_value;
rfl::Field<"left", rfl::Box<DecisionTree>> lesser;
rfl::Field<"right", rfl::Box<DecisionTree>> greater;
};
using LeafOrNode = rfl::TaggedUnion<"type", Leaf, Node>;
rfl::Field<"leafOrNode", LeafOrNode> leaf_or_node;
};
auto leaf1 = DecisionTree::Leaf{.value = 3.0};
auto leaf2 = DecisionTree::Leaf{.value = 5.0};
auto node = DecisionTree::Node{
.critical_value = 10.0,
.lesser = rfl::make_box<DecisionTree>(DecisionTree{leaf1}),
.greater = rfl::make_box<DecisionTree>(DecisionTree{leaf2})};
const DecisionTree tree{.leaf_or_node = std::move(node)};
write_and_read(tree);
}
+37
View File
@@ -0,0 +1,37 @@
#include <cassert>
#include <iostream>
#include <rfl.hpp>
#include <rfl/flexbuf.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
void test_custom_class1() {
std::cout << "test_custom_class1" << std::endl;
struct Person {
struct PersonImpl {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name = "Simpson";
rfl::Field<"children", std::vector<Person>> children =
rfl::default_value;
};
using ReflectionType = PersonImpl;
Person(const PersonImpl& _impl) : impl(_impl) {}
Person(const std::string& _first_name)
: impl(PersonImpl{.first_name = _first_name}) {}
const ReflectionType& reflection() const { return impl; };
private:
PersonImpl impl;
};
const auto bart = Person("Bart");
write_and_read(bart);
}
+62
View File
@@ -0,0 +1,62 @@
#include <cassert>
#include <iostream>
#include <rfl.hpp>
#include <rfl/flexbuf.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
namespace tcc2 {
struct Person {
Person(const std::string& _first_name, const std::string& _last_name,
const int _age)
: first_name_(_first_name), last_name_(_last_name), age_(_age) {}
const auto& first_name() const { return first_name_; }
const auto& last_name() const { return last_name_; }
auto age() const { return age_; }
private:
std::string first_name_;
std::string last_name_;
int age_;
};
struct PersonImpl {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name;
rfl::Field<"age", int> age;
static PersonImpl from_class(const Person& _p) noexcept {
return PersonImpl{.first_name = _p.first_name(),
.last_name = _p.last_name(),
.age = _p.age()};
}
Person to_class() const { return Person(first_name(), last_name(), age()); }
};
} // namespace tcc2
namespace rfl {
namespace parsing {
template <class ReaderType, class WriterType>
struct Parser<ReaderType, WriterType, tcc2::Person>
: public CustomParser<ReaderType, WriterType, tcc2::Person,
tcc2::PersonImpl> {};
} // namespace parsing
} // namespace rfl
void test_custom_class2() {
std::cout << "test_custom_class2" << std::endl;
const auto bart = tcc2::Person("Bart", "Simpson", 10);
write_and_read(bart);
}
+63
View File
@@ -0,0 +1,63 @@
#include <cassert>
#include <iostream>
#include <rfl.hpp>
#include <rfl/flexbuf.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
namespace tcc3 {
struct Person {
Person(const std::string& _first_name,
const rfl::Box<std::string>& _last_name, int _age)
: first_name_(_first_name),
last_name_(rfl::make_box<std::string>(*_last_name)),
age_(_age) {}
const auto& first_name() const { return first_name_; }
const auto& last_name() const { return last_name_; }
auto age() const { return age_; }
private:
std::string first_name_;
rfl::Box<std::string> last_name_;
int age_;
};
struct PersonImpl {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", rfl::Box<std::string>> last_name;
rfl::Field<"age", int> age;
static PersonImpl from_class(const Person& _p) noexcept {
return PersonImpl{.first_name = _p.first_name(),
.last_name = rfl::make_box<std::string>(*_p.last_name()),
.age = _p.age()};
}
};
} // namespace tcc3
namespace rfl {
namespace parsing {
template <class ReaderType, class WriterType>
struct Parser<ReaderType, WriterType, tcc3::Person>
: public CustomParser<ReaderType, WriterType, tcc3::Person,
tcc3::PersonImpl> {};
} // namespace parsing
} // namespace rfl
void test_custom_class3() {
std::cout << "test_custom_class3" << std::endl;
const auto bart =
tcc3::Person("Bart", rfl::make_box<std::string>("Simpson"), 10);
write_and_read(bart);
}
@@ -0,0 +1,55 @@
#include <iostream>
#include <rfl.hpp>
#include <rfl/flexbuf.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
// Makes sure that the example in the README works as expected.
// It would be embarrassing if it didn't...
void test_custom_constructor() {
std::cout << "test_custom_constructor" << std::endl;
struct Person {
static rfl::Result<Person> from_flexbuf(
typename rfl::flexbuf::Reader::InputVarType _obj) {
/// This only exists for the purpose of the test.
const auto change_first_name = [](auto&& _person) {
return rfl::replace(std::move(_person),
rfl::Field<"firstName", std::string>("Bart"));
};
const auto from_nt = [](auto&& _nt) {
return rfl::from_named_tuple<Person>(std::move(_nt));
};
return rfl::flexbuf::read<rfl::named_tuple_t<Person>>(_obj)
.transform(from_nt)
.transform(change_first_name);
}
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name;
rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">> birthday;
};
const auto person1 = Person{
.first_name = "Homer", .last_name = "Simpson", .birthday = "1987-04-19"};
const auto bytes = rfl::flexbuf::write(person1);
const auto res = rfl::flexbuf::read<Person>(bytes);
if (!res) {
std::cout << "Test failed on read. Error: " << res.error().value().what()
<< std::endl;
return;
}
if (res.value().first_name() != "Bart") {
std::cout << "Expected 'Bart', got '" << res.value().first_name() << "'"
<< std::endl
<< std::endl;
} else {
std::cout << "OK" << std::endl << std::endl;
}
}
+28
View File
@@ -0,0 +1,28 @@
#include <iostream>
#include <rfl.hpp>
#include <rfl/flexbuf.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
void test_deque() {
std::cout << "test_deque" << std::endl;
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name = "Simpson";
rfl::Field<"children", std::unique_ptr<std::deque<Person>>> children =
rfl::default_value;
};
auto children = std::make_unique<std::deque<Person>>();
children->emplace_back(Person{.first_name = "Bart"});
children->emplace_back(Person{.first_name = "Lisa"});
children->emplace_back(Person{.first_name = "Maggie"});
const auto homer =
Person{.first_name = "Homer", .children = std::move(children)};
write_and_read(homer);
}
+34
View File
@@ -0,0 +1,34 @@
#include <cassert>
#include <iostream>
#include <rfl.hpp>
#include <rfl/flexbuf.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
void test_field_variant() {
std::cout << "test_field_variant" << std::endl;
struct Circle {
rfl::Field<"radius", double> radius;
};
struct Rectangle {
rfl::Field<"height", double> height;
rfl::Field<"width", double> width;
};
struct Square {
rfl::Field<"width", double> width;
};
using Shapes = rfl::Variant<rfl::Field<"circle", Circle>,
rfl::Field<"rectangle", Rectangle>,
rfl::Field<"square", rfl::Box<Square>>>;
const Shapes r =
rfl::make_field<"rectangle">(Rectangle{.height = 10, .width = 5});
write_and_read(r);
}
+28
View File
@@ -0,0 +1,28 @@
#include <iostream>
#include <rfl.hpp>
#include <rfl/flexbuf.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
void test_forward_list() {
std::cout << "test_forward_list" << std::endl;
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name = "Simpson";
rfl::Field<"children", std::unique_ptr<std::forward_list<Person>>>
children = rfl::default_value;
};
auto children = std::make_unique<std::forward_list<Person>>();
children->emplace_front(Person{.first_name = "Maggie"});
children->emplace_front(Person{.first_name = "Lisa"});
children->emplace_front(Person{.first_name = "Bart"});
const auto homer =
Person{.first_name = "Homer", .children = std::move(children)};
write_and_read(homer);
}
+28
View File
@@ -0,0 +1,28 @@
#include <iostream>
#include <rfl.hpp>
#include <rfl/flexbuf.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
void test_list() {
std::cout << "test_list" << std::endl;
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name = "Simpson";
rfl::Field<"children", std::unique_ptr<std::list<Person>>> children =
rfl::default_value;
};
auto children = std::make_unique<std::list<Person>>();
children->emplace_back(Person{.first_name = "Bart"});
children->emplace_back(Person{.first_name = "Lisa"});
children->emplace_back(Person{.first_name = "Maggie"});
const auto homer =
Person{.first_name = "Homer", .children = std::move(children)};
write_and_read(homer);
}
+26
View File
@@ -0,0 +1,26 @@
#include <cassert>
#include <iostream>
#include <rfl.hpp>
#include <rfl/flexbuf.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
// Makes sure that we can set default values.
void test_literal() {
std::cout << "test_literal" << std::endl;
using FirstName = rfl::Literal<"Homer", "Marge", "Bart", "Lisa", "Maggie">;
using LastName = rfl::Literal<"Simpson">;
struct Person {
rfl::Field<"firstName", FirstName> first_name;
rfl::Field<"lastName", LastName> last_name = rfl::default_value;
rfl::Field<"children", std::vector<Person>> children = rfl::default_value;
};
const auto bart = Person{.first_name = FirstName::make<"Bart">()};
write_and_read(bart);
}
+28
View File
@@ -0,0 +1,28 @@
#include <iostream>
#include <map>
#include <rfl.hpp>
#include <rfl/flexbuf.hpp>
#include <string>
#include "write_and_read.hpp"
void test_map() {
std::cout << "test_map" << std::endl;
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name = "Simpson";
rfl::Field<"children", std::unique_ptr<std::map<int, Person>>>
children = rfl::default_value;
};
auto children = std::make_unique<std::map<int, Person>>();
children->insert(std::make_pair(1, Person{.first_name = "Bart"}));
children->insert(std::make_pair(2, Person{.first_name = "Lisa"}));
children->insert(std::make_pair(3, Person{.first_name = "Maggie"}));
const auto homer =
Person{.first_name = "Homer", .children = std::move(children)};
write_and_read(homer);
}
@@ -0,0 +1,61 @@
#include <iostream>
#include <rfl.hpp>
#include <rfl/flexbuf.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
void test_monster_example1() {
std::cout << "test_monster_example1" << std::endl;
using Color = rfl::Literal<"Red", "Green", "Blue">;
struct Weapon {
std::string name;
short damage;
};
using Equipment = rfl::Variant<rfl::Field<"weapon", Weapon>>;
struct Vec3 {
float x;
float y;
float z;
};
struct Monster {
Vec3 pos;
short mana = 150;
short hp = 100;
std::string name;
bool friendly = false;
std::vector<std::uint8_t> inventory;
Color color = Color::make<"Blue">();
std::vector<Weapon> weapons;
Equipment equipped;
std::vector<Vec3> path;
};
const auto sword = Weapon{.name = "Sword", .damage = 3};
const auto axe = Weapon{.name = "Axe", .damage = 5};
const auto weapons = std::vector<Weapon>({sword, axe});
const auto position = Vec3{1.0f, 2.0f, 3.0f};
const auto inventory =
std::vector<std::uint8_t>({0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
const auto orc = Monster{.pos = position,
.mana = 150,
.hp = 80,
.name = "MyMonster",
.inventory = inventory,
.color = Color::make<"Red">(),
.weapons = weapons,
.equipped = rfl::make_field<"weapon">(axe)};
write_and_read(orc);
}
@@ -0,0 +1,62 @@
#include <iostream>
#include <rfl.hpp>
#include <rfl/flexbuf.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
void test_monster_example2() {
std::cout << "test_monster_example2" << std::endl;
using Color = rfl::Literal<"Red", "Green", "Blue">;
struct Weapon {
rfl::Field<"name", std::string> name;
rfl::Field<"damage", short> damage;
};
using Equipment = rfl::Variant<rfl::Field<"weapon", Weapon>>;
struct Vec3 {
rfl::Field<"x", float> x;
rfl::Field<"y", float> y;
rfl::Field<"z", float> z;
};
struct Monster {
rfl::Field<"pos", Vec3> pos;
rfl::Field<"mana", short> mana = 150;
rfl::Field<"hp", short> hp = 100;
rfl::Field<"name", std::string> name;
rfl::Field<"friendly", bool> friendly = false;
rfl::Field<"inventory", std::vector<std::uint8_t>> inventory;
rfl::Field<"color", Color> color = Color::make<"Blue">();
rfl::Field<"weapons", std::vector<Weapon>> weapons;
rfl::Field<"equipped", Equipment> equipped;
rfl::Field<"path", std::vector<Vec3>> path;
};
const auto sword = Weapon{.name = "Sword", .damage = 3};
const auto axe = Weapon{.name = "Axe", .damage = 5};
const auto weapons = std::vector<Weapon>({sword, axe});
const auto position = Vec3{1.0f, 2.0f, 3.0f};
const auto inventory =
std::vector<std::uint8_t>({0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
const auto orc = Monster{.pos = position,
.mana = 150,
.hp = 80,
.name = "MyMonster",
.inventory = inventory,
.color = Color::make<"Red">(),
.weapons = weapons,
.equipped = rfl::make_field<"weapon">(axe),
.path = rfl::default_value};
write_and_read(orc);
}
+28
View File
@@ -0,0 +1,28 @@
#include <iostream>
#include <map>
#include <rfl.hpp>
#include <rfl/flexbuf.hpp>
#include <string>
#include "write_and_read.hpp"
void test_multimap() {
std::cout << "test_multimap" << std::endl;
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name = "Simpson";
rfl::Field<"children", std::unique_ptr<std::multimap<int, Person>>>
children = rfl::default_value;
};
auto children = std::make_unique<std::multimap<int, Person>>();
children->insert(std::make_pair(1, Person{.first_name = "Bart"}));
children->insert(std::make_pair(2, Person{.first_name = "Lisa"}));
children->insert(std::make_pair(3, Person{.first_name = "Maggie"}));
const auto homer =
Person{.first_name = "Homer", .children = std::move(children)};
write_and_read(homer);
}
+26
View File
@@ -0,0 +1,26 @@
#include <iostream>
#include <rfl.hpp>
#include <rfl/flexbuf.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
void test_multiset() {
std::cout << "test_multiset" << std::endl;
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name = "Simpson";
rfl::Field<"children", std::unique_ptr<std::multiset<std::string>>>
children = rfl::default_value;
};
auto children = std::make_unique<std::multiset<std::string>>(
std::multiset<std::string>({"Bart", "Lisa", "Maggie"}));
const auto homer =
Person{.first_name = "Homer", .children = std::move(children)};
write_and_read(homer);
}
@@ -0,0 +1,30 @@
#include <iostream>
#include <rfl.hpp>
#include <rfl/flexbuf.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
void test_optional_fields() {
std::cout << "test_optional_fields" << std::endl;
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name = "Simpson";
rfl::Field<"children", std::optional<std::vector<Person>>> children =
rfl::default_value;
};
const auto bart = Person{.first_name = "Bart"};
const auto lisa = Person{.first_name = "Lisa"};
const auto maggie = Person{.first_name = "Maggie"};
const auto homer =
Person{.first_name = "Homer",
.children = std::vector<Person>({bart, lisa, maggie})};
write_and_read(homer);
}
+54
View File
@@ -0,0 +1,54 @@
#include <iostream>
#include <rfl.hpp>
#include <rfl/flexbuf.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
void test_readme_example() {
std::cout << "test_readme_example" << std::endl;
using Age = rfl::Validator<unsigned int,
rfl::AllOf<rfl::Minimum<0>, rfl::Maximum<130>>>;
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name;
rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">> birthday;
rfl::Field<"age", Age> age;
rfl::Field<"email", rfl::Email> email;
rfl::Field<"children", std::vector<Person>> children;
};
const auto bart = Person{.first_name = "Bart",
.last_name = "Simpson",
.birthday = "1987-04-19",
.age = 10,
.email = "bart@simpson.com",
.children = std::vector<Person>()};
const auto lisa = Person{
.first_name = "Lisa",
.last_name = "Simpson",
.birthday = "1987-04-19",
.age = 8,
.email = "lisa@simpson.com",
.children = rfl::default_value // same as std::vector<Person>()
};
const auto maggie =
rfl::replace(lisa, rfl::make_field<"firstName">(std::string("Maggie")),
rfl::make_field<"email">(std::string("maggie@simpson.com")),
rfl::make_field<"age">(0));
const auto homer =
Person{.first_name = "Homer",
.last_name = "Simpson",
.birthday = "1987-04-19",
.age = 45,
.email = "homer@simpson.com",
.children = std::vector<Person>({bart, lisa, maggie})};
write_and_read(homer);
}
+43
View File
@@ -0,0 +1,43 @@
#include <cassert>
#include <iostream>
#include <rfl.hpp>
#include <rfl/flexbuf.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
void test_ref() {
std::cout << "test_ref" << std::endl;
struct DecisionTree {
struct Leaf {
rfl::Field<"type", rfl::Literal<"Leaf">> type = rfl::default_value;
rfl::Field<"value", double> value;
};
struct Node {
rfl::Field<"type", rfl::Literal<"Node">> type = rfl::default_value;
rfl::Field<"criticalValue", double> critical_value;
rfl::Field<"left", rfl::Ref<DecisionTree>> lesser;
rfl::Field<"right", rfl::Ref<DecisionTree>> greater;
};
using LeafOrNode = rfl::TaggedUnion<"type", Leaf, Node>;
rfl::Field<"leafOrNode", LeafOrNode> leaf_or_node;
};
const auto leaf1 = DecisionTree::Leaf{.value = 3.0};
const auto leaf2 = DecisionTree::Leaf{.value = 5.0};
auto node = DecisionTree::Node{
.critical_value = 10.0,
.lesser = rfl::make_ref<DecisionTree>(DecisionTree{leaf1}),
.greater = rfl::make_ref<DecisionTree>(DecisionTree{leaf2})};
const DecisionTree tree{.leaf_or_node = std::move(node)};
write_and_read(tree);
}
+68
View File
@@ -0,0 +1,68 @@
#include <cassert>
#include <iostream>
#include <rfl.hpp>
#include <rfl/flexbuf.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
void test_save_load() {
std::cout << "test_save_load" << std::endl;
using Age = rfl::Validator<unsigned int,
rfl::AllOf<rfl::Minimum<0>, rfl::Maximum<130>>>;
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name;
rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">> birthday;
rfl::Field<"age", Age> age;
rfl::Field<"email", rfl::Email> email;
rfl::Field<"children", std::vector<Person>> children;
};
const auto bart = Person{.first_name = "Bart",
.last_name = "Simpson",
.birthday = "1987-04-19",
.age = 10,
.email = "bart@simpson.com",
.children = std::vector<Person>()};
const auto lisa = Person{
.first_name = "Lisa",
.last_name = "Simpson",
.birthday = "1987-04-19",
.age = 8,
.email = "lisa@simpson.com",
.children = rfl::default_value // same as std::vector<Person>()
};
const auto maggie =
rfl::replace(lisa, rfl::make_field<"firstName">(std::string("Maggie")),
rfl::make_field<"email">(std::string("maggie@simpson.com")),
rfl::make_field<"age">(0));
const auto homer1 =
Person{.first_name = "Homer",
.last_name = "Simpson",
.birthday = "1987-04-19",
.age = 45,
.email = "homer@simpson.com",
.children = std::vector<Person>({bart, lisa, maggie})};
rfl::flexbuf::save("homer.fb", homer1);
const auto homer2 = rfl::flexbuf::load<Person>("homer.fb").value();
const auto bytes1 = rfl::flexbuf::write(homer1);
const auto bytes2 = rfl::flexbuf::write(homer2);
if (bytes1 != bytes2) {
std::cout << "Test failed. Content was not identical." << std::endl
<< std::endl;
return;
}
std::cout << "OK" << std::endl << std::endl;
}
+26
View File
@@ -0,0 +1,26 @@
#include <iostream>
#include <rfl.hpp>
#include <rfl/flexbuf.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
void test_set() {
std::cout << "test_set" << std::endl;
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name = "Simpson";
rfl::Field<"children", std::unique_ptr<std::set<std::string>>>
children = rfl::default_value;
};
auto children = std::make_unique<std::set<std::string>>(
std::set<std::string>({"Bart", "Lisa", "Maggie"}));
const auto homer =
Person{.first_name = "Homer", .children = std::move(children)};
write_and_read(homer);
}
+20
View File
@@ -0,0 +1,20 @@
#include <iostream>
#include <map>
#include <memory>
#include <rfl.hpp>
#include <rfl/flexbuf.hpp>
#include <string>
#include "write_and_read.hpp"
void test_string_map() {
std::cout << "test_string_map" << std::endl;
std::map<std::string, std::unique_ptr<std::string>> homer;
homer.insert(
std::make_pair("firstName", std::make_unique<std::string>("Homer")));
homer.insert(
std::make_pair("lastName", std::make_unique<std::string>("Simpson")));
write_and_read(homer);
}
@@ -0,0 +1,25 @@
#include <iostream>
#include <memory>
#include <rfl.hpp>
#include <rfl/flexbuf.hpp>
#include <string>
#include <unordered_map>
#include "write_and_read.hpp"
void test_string_unordered_map() {
std::cout << "test_string_unordered_map" << std::endl;
using Map = std::unordered_map<std::string, std::unique_ptr<std::string>>;
Map homer;
homer.insert(
std::make_pair("firstName", std::make_unique<std::string>("Homer")));
homer.insert(
std::make_pair("lastName", std::make_unique<std::string>("Simpson")));
// Unordered maps are unpredictable. We therefore only make sure that this
// compiles.
const auto json_string = rfl::flexbuf::write(homer);
const auto homer2 = rfl::flexbuf::read<Map>(json_string);
std::cout << "OK" << std::endl << std::endl;
}
+35
View File
@@ -0,0 +1,35 @@
#include <cassert>
#include <iostream>
#include <rfl.hpp>
#include <rfl/flexbuf.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
// Makes sure that we can set default values.
void test_tagged_union() {
std::cout << "test_tagged_union" << std::endl;
struct Circle {
rfl::Field<"shape", rfl::Literal<"Circle">> shape = rfl::default_value;
rfl::Field<"radius", double> radius;
};
struct Rectangle {
rfl::Field<"shape", rfl::Literal<"Rectangle">> shape = rfl::default_value;
rfl::Field<"height", double> height;
rfl::Field<"width", double> width;
};
struct Square {
rfl::Field<"shape", rfl::Literal<"Square">> shape = rfl::default_value;
rfl::Field<"width", double> width;
};
using Shapes = rfl::TaggedUnion<"shape", Circle, Square, Rectangle>;
const Shapes r = Rectangle{.height = 10, .width = 5};
write_and_read(r);
}
+29
View File
@@ -0,0 +1,29 @@
#include <iostream>
#include <memory>
#include <rfl.hpp>
#include <rfl/flexbuf.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
void test_unique_ptr() {
std::cout << "test_unique_ptr" << std::endl;
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name = "Simpson";
rfl::Field<"children", std::unique_ptr<std::vector<Person>>> children =
rfl::default_value;
};
auto children = std::make_unique<std::vector<Person>>();
children->emplace_back(Person{.first_name = "Bart"});
children->emplace_back(Person{.first_name = "Lisa"});
children->emplace_back(Person{.first_name = "Maggie"});
const auto homer =
Person{.first_name = "Homer", .children = std::move(children)};
write_and_read(homer);
}
+43
View File
@@ -0,0 +1,43 @@
#include <cassert>
#include <iostream>
#include <rfl.hpp>
#include <rfl/flexbuf.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
void test_unique_ptr2() {
std::cout << "test_unique_ptr2" << std::endl;
struct DecisionTree {
struct Leaf {
rfl::Field<"type", rfl::Literal<"Leaf">> type = rfl::default_value;
rfl::Field<"value", double> value;
};
struct Node {
rfl::Field<"type", rfl::Literal<"Node">> type = rfl::default_value;
rfl::Field<"criticalValue", double> critical_value;
rfl::Field<"left", std::unique_ptr<DecisionTree>> lesser;
rfl::Field<"right", std::unique_ptr<DecisionTree>> greater;
};
using LeafOrNode = rfl::TaggedUnion<"type", Leaf, Node>;
rfl::Field<"leafOrNode", LeafOrNode> leaf_or_node;
};
auto leaf1 = DecisionTree::Leaf{.value = 3.0};
auto leaf2 = DecisionTree::Leaf{.value = 5.0};
auto node = DecisionTree::Node{
.critical_value = 10.0,
.lesser = std::make_unique<DecisionTree>(DecisionTree{leaf1}),
.greater = std::make_unique<DecisionTree>(DecisionTree{leaf2})};
const DecisionTree tree{.leaf_or_node = std::move(node)};
write_and_read(tree);
}
+32
View File
@@ -0,0 +1,32 @@
#include <iostream>
#include <rfl.hpp>
#include <rfl/flexbuf.hpp>
#include <string>
#include <unordered_map>
#include "write_and_read.hpp"
void test_unordered_map() {
std::cout << "test_unordered_map" << std::endl;
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name = "Simpson";
rfl::Field<"children", std::unique_ptr<std::unordered_map<int, Person>>>
children = rfl::default_value;
};
auto children = std::make_unique<std::unordered_map<int, Person>>();
children->insert(std::make_pair(1, Person{.first_name = "Bart"}));
children->insert(std::make_pair(2, Person{.first_name = "Lisa"}));
children->insert(std::make_pair(3, Person{.first_name = "Maggie"}));
const auto homer =
Person{.first_name = "Homer", .children = std::move(children)};
// Unordered maps are unpredictable. We therefore only make sure that this
// compiles.
const auto json_string = rfl::flexbuf::write(homer);
const auto homer2 = rfl::flexbuf::read<Person>(json_string);
std::cout << "OK" << std::endl << std::endl;
}
@@ -0,0 +1,33 @@
#include <iostream>
#include <map>
#include <rfl.hpp>
#include <rfl/flexbuf.hpp>
#include <string>
#include "write_and_read.hpp"
void test_unordered_multimap() {
std::cout << "test_unordered_multimap" << std::endl;
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name = "Simpson";
rfl::Field<"children",
std::unique_ptr<std::unordered_multimap<int, Person>>>
children = rfl::default_value;
};
auto children = std::make_unique<std::unordered_multimap<int, Person>>();
children->insert(std::make_pair(1, Person{.first_name = "Bart"}));
children->insert(std::make_pair(2, Person{.first_name = "Lisa"}));
children->insert(std::make_pair(3, Person{.first_name = "Maggie"}));
const auto homer =
Person{.first_name = "Homer", .children = std::move(children)};
// Unordered maps are unpredictable. We therefore only make sure that this
// compiles.
const auto json_string = rfl::flexbuf::write(homer);
const auto homer2 = rfl::flexbuf::read<Person>(json_string);
std::cout << "OK" << std::endl << std::endl;
}
@@ -0,0 +1,31 @@
#include <iostream>
#include <rfl.hpp>
#include <rfl/flexbuf.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
void test_unordered_multiset() {
std::cout << "test_unordered_multiset" << std::endl;
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name = "Simpson";
rfl::Field<"children",
std::unique_ptr<std::unordered_multiset<std::string>>>
children = rfl::default_value;
};
auto children = std::make_unique<std::unordered_multiset<std::string>>(
std::unordered_multiset<std::string>({"Bart", "Lisa", "Maggie"}));
const auto homer =
Person{.first_name = "Homer", .children = std::move(children)};
// Unordered multisets are unpredictable. We therefore only make sure that
// this compiles.
const auto json_string = rfl::flexbuf::write(homer);
const auto homer2 = rfl::flexbuf::read<Person>(json_string);
std::cout << "OK" << std::endl << std::endl;
}
+30
View File
@@ -0,0 +1,30 @@
#include <iostream>
#include <rfl.hpp>
#include <rfl/flexbuf.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
void test_unordered_set() {
std::cout << "test_unordered_set" << std::endl;
struct Person {
rfl::Field<"firstName", std::string> first_name;
rfl::Field<"lastName", std::string> last_name = "Simpson";
rfl::Field<"children", std::unique_ptr<std::unordered_set<std::string>>>
children = rfl::default_value;
};
auto children = std::make_unique<std::unordered_set<std::string>>(
std::unordered_set<std::string>({"Bart", "Lisa", "Maggie"}));
const auto homer =
Person{.first_name = "Homer", .children = std::move(children)};
// Unordered sets are unpredictable. We therefore only make sure that this
// compiles.
const auto json_string = rfl::flexbuf::write(homer);
const auto homer2 = rfl::flexbuf::read<Person>(json_string);
std::cout << "OK" << std::endl << std::endl;
}
+32
View File
@@ -0,0 +1,32 @@
#include <cassert>
#include <iostream>
#include <rfl.hpp>
#include <rfl/flexbuf.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
// Makes sure that we can set default values.
void test_variant() {
std::cout << "test_variant" << std::endl;
struct Circle {
rfl::Field<"radius", double> radius;
};
struct Rectangle {
rfl::Field<"height", double> height;
rfl::Field<"width", double> width;
};
struct Square {
rfl::Field<"width", double> width;
};
using Shapes = std::variant<Circle, Rectangle, std::unique_ptr<Square>>;
const Shapes r = Rectangle{.height = 10, .width = 5};
write_and_read(r);
}
+73
View File
@@ -0,0 +1,73 @@
#include "test_all_of.hpp"
#include "test_anonymous_fields.hpp"
#include "test_box.hpp"
#include "test_custom_class1.hpp"
#include "test_custom_class2.hpp"
#include "test_custom_class3.hpp"
#include "test_custom_constructor.hpp"
#include "test_deque.hpp"
#include "test_field_variant.hpp"
#include "test_forward_list.hpp"
#include "test_list.hpp"
#include "test_literal.hpp"
#include "test_map.hpp"
#include "test_monster_example1.hpp"
#include "test_monster_example2.hpp"
#include "test_multimap.hpp"
#include "test_multiset.hpp"
#include "test_optional_fields.hpp"
#include "test_readme_example.hpp"
#include "test_ref.hpp"
#include "test_save_load.hpp"
#include "test_set.hpp"
#include "test_string_map.hpp"
#include "test_string_unordered_map.hpp"
#include "test_tagged_union.hpp"
#include "test_unique_ptr.hpp"
#include "test_unique_ptr2.hpp"
#include "test_unordered_map.hpp"
#include "test_unordered_multimap.hpp"
#include "test_unordered_multiset.hpp"
#include "test_unordered_set.hpp"
#include "test_variant.hpp"
int main() {
test_readme_example();
test_monster_example1();
test_monster_example2();
test_anonymous_fields();
test_optional_fields();
test_unique_ptr();
test_unique_ptr2();
test_literal();
test_variant();
test_field_variant();
test_tagged_union();
test_custom_class1();
test_custom_class2();
test_custom_class3();
test_box();
test_ref();
test_deque();
test_forward_list();
test_list();
test_map();
test_multimap();
test_multiset();
test_set();
test_string_map();
test_string_unordered_map();
test_unordered_map();
test_unordered_multimap();
test_unordered_multiset();
test_unordered_set();
test_custom_constructor();
test_all_of();
test_save_load();
return 0;
}
+39
View File
@@ -0,0 +1,39 @@
#ifndef WRITE_AND_READ_
#define WRITE_AND_READ_
#include <iostream>
#include <rfl/flexbuf.hpp>
#include <string>
template <class T>
void write_and_read(const T& _struct) {
const auto bytes1 = rfl::flexbuf::write(_struct);
const auto res = rfl::flexbuf::read<T>(bytes1);
if (!res) {
std::cout << "Test failed on read. Error: " << res.error().value().what()
<< std::endl
<< std::endl;
return;
}
const auto bytes2 = rfl::flexbuf::write(res.value());
if (bytes1.size() != bytes2.size()) {
std::cout << "Test failed on write. Number of bytes was different."
<< std::endl
<< std::endl;
return;
}
if (bytes1 != bytes2) {
std::cout << "Test failed on write. Content was not identical." << std::endl
<< std::endl;
return;
}
std::cout << "OK" << std::endl << std::endl;
}
#endif
@@ -3,13 +3,13 @@ cmake_minimum_required(VERSION 3.4)
project(reflect-cpp-tests)
include_directories(
"../include"
"../../include"
)
add_executable(
reflect-cpp-tests
"tests.cpp"
"../src/yyjson.c"
"../../src/yyjson.c"
)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -O2")
+34
View File
@@ -0,0 +1,34 @@
#include <cassert>
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
void test_field_variant() {
std::cout << "test_field_variant" << std::endl;
struct Circle {
rfl::Field<"radius", double> radius;
};
struct Rectangle {
rfl::Field<"height", double> height;
rfl::Field<"width", double> width;
};
struct Square {
rfl::Field<"width", double> width;
};
using Shapes = rfl::Variant<rfl::Field<"circle", Circle>,
rfl::Field<"rectangle", Rectangle>,
rfl::Field<"square", rfl::Box<Square>>>;
const Shapes r =
rfl::make_field<"rectangle">(Rectangle{.height = 10, .width = 5});
write_and_read(r, R"({"rectangle":{"height":10.0,"width":5.0}})");
}
+63
View File
@@ -0,0 +1,63 @@
#include <iostream>
#include <rfl.hpp>
#include <rfl/json.hpp>
#include <string>
#include <vector>
#include "write_and_read.hpp"
void test_monster_example() {
std::cout << "test_monster_example" << std::endl;
using Color = rfl::Literal<"Red", "Green", "Blue">;
struct Weapon {
std::string name;
short damage;
};
using Equipment = rfl::Variant<rfl::Field<"weapon", Weapon>>;
struct Vec3 {
float x;
float y;
float z;
};
struct Monster {
Vec3 pos;
short mana = 150;
short hp = 100;
std::string name;
bool friendly = false;
std::vector<std::uint8_t> inventory;
Color color = Color::make<"Blue">();
std::vector<Weapon> weapons;
Equipment equipped;
std::vector<Vec3> path;
};
const auto sword = Weapon{.name = "Sword", .damage = 3};
const auto axe = Weapon{.name = "Axe", .damage = 5};
const auto weapons = std::vector<Weapon>({sword, axe});
const auto position = Vec3{1.0f, 2.0f, 3.0f};
const auto inventory =
std::vector<std::uint8_t>({0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
const auto orc = Monster{.pos = position,
.mana = 150,
.hp = 80,
.name = "MyMonster",
.inventory = inventory,
.color = Color::make<"Red">(),
.weapons = weapons,
.equipped = rfl::make_field<"weapon">(axe)};
write_and_read(
orc,
R"([[1.0,2.0,3.0],150,80,"MyMonster",false,[0,1,2,3,4,5,6,7,8,9],"Red",[["Sword",3],["Axe",5]],{"weapon":["Axe",5]},[]])");
}

Some files were not shown because too many files have changed in this diff Show More