diff --git a/.gitignore b/.gitignore index 6407405d..02def0a0 100644 --- a/.gitignore +++ b/.gitignore @@ -38,3 +38,8 @@ **/CMakeFiles/** **/reflect-cpp-tests **/build/** +**/build_clang/** + +# Output files +*.json +*.fb diff --git a/docs/backwards_compatability.md b/docs/backwards_compatability.md index 0348dad5..a86ab058 100644 --- a/docs/backwards_compatability.md +++ b/docs/backwards_compatability.md @@ -60,6 +60,6 @@ struct API_v_1_1 { ... -using APIs = std::variant, rfl::Field<"v1.1", API_v_1_1>, ...>; +using APIs = rfl::Variant, rfl::Field<"v1.1", API_v_1_1>, ...>; ``` diff --git a/docs/flexbuffers.md b/docs/flexbuffers.md new file mode 100644 index 00000000..3da4ec74 --- /dev/null +++ b/docs/flexbuffers.md @@ -0,0 +1,285 @@ +# Flexbuffers + +For flexbuffers support, you must also include the header `` 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 +#include + +using Color = rfl::Literal<"Red", "Green", "Blue">; + +struct Weapon { + std::string name; + short damage; +}; + +using Equipment = rfl::Variant>; + +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 inventory; + Color color = Color::make<"Blue">(); + std::vector weapons; + Equipment equipped; + std::vector path; +}; + +const auto sword = Weapon{.name = "Sword", .damage = 3}; +const auto axe = Weapon{.name = "Axe", .damage = 5}; + +const auto weapons = std::vector({sword, axe}); + +const auto position = Vec3{1.0f, 2.0f, 3.0f}; + +const auto inventory = + std::vector({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(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> 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 +#include + + using Color = rfl::Literal<"Red", "Green", "Blue">; + + struct Weapon { + rfl::Field<"name", std::string> name; + rfl::Field<"damage", short> damage; + }; + + using Equipment = rfl::Variant>; + + 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> inventory; + rfl::Field<"color", Color> color = Color::make<"Blue">(); + rfl::Field<"weapons", std::vector> weapons; + rfl::Field<"equipped", Equipment> equipped; + rfl::Field<"path", std::vector> path; + }; + + const auto sword = Weapon{.name = "Sword", .damage = 3}; + const auto axe = Weapon{.name = "Axe", .damage = 5}; + + const auto weapons = std::vector({sword, axe}); + + const auto position = Vec3{1.0f, 2.0f, 3.0f}; + + const auto inventory = + std::vector({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(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 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 result = rfl::flexbuf::read(bytes); +``` + +## Loading and saving + +You can also load and save to disc using a very similar syntax: + +```cpp +const rfl::Result result = rfl::flexbuf::load("/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 from_flexbuf(const InputVarType& _obj); +}; +``` + +And in your source file, you implement `from_flexbuf` as follows: + +```cpp +rfl::Result Person::from_flexbuf(const InputVarType& _obj) { + const auto from_nt = [](auto&& _nt) { + return rfl::from_named_tuple(std::move(_nt)); + }; + return rfl::flexbuf::read>(_obj) + .transform(from_nt); +} +``` + +This will force the compiler to only compile the flexbuffers parsing when the +source file is compiled. diff --git a/docs/variants_and_tagged_unions.md b/docs/variants_and_tagged_unions.md index a0d25d41..09a7d682 100644 --- a/docs/variants_and_tagged_unions.md +++ b/docs/variants_and_tagged_unions.md @@ -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; 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` instead of `std::variant`. 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<"option2", Type2>, ...>; +using TaggedVariant = rfl::Variant, 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, +using Shapes = rfl::Variant, rfl::Field<"rectangle", Rectangle>, rfl::Field<"square", Square>>; diff --git a/include/rfl.hpp b/include/rfl.hpp index 755270e6..25f50941 100644 --- a/include/rfl.hpp +++ b/include/rfl.hpp @@ -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" diff --git a/include/rfl/Box.hpp b/include/rfl/Box.hpp index 372b1f28..c6eb806d 100644 --- a/include/rfl/Box.hpp +++ b/include/rfl/Box.hpp @@ -26,10 +26,9 @@ class Box { Box(Box&& _other) = default; - template , - bool>::type = true> + template Box(Box&& _other) noexcept - : ptr_(std::make_unique(std::forward(*_other))) {} + : ptr_(std::forward>(_other.ptr())) {} ~Box() = default; @@ -43,10 +42,9 @@ class Box { Box& operator=(Box&& _other) noexcept = default; /// Move assignment operator - template , - bool>::type = true> + template Box& operator=(Box&& _other) noexcept { - ptr_ = std::make_unique(std::forward(*_other)); + ptr_ = std::forward>(_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& ptr() { return ptr_; } + /// Returns the underlying unique_ptr const std::unique_ptr& ptr() const { return ptr_; } diff --git a/include/rfl/Ref.hpp b/include/rfl/Ref.hpp index 6bda2e02..e65217a7 100644 --- a/include/rfl/Ref.hpp +++ b/include/rfl/Ref.hpp @@ -26,14 +26,12 @@ class Ref { Ref(Ref&& _other) = default; - template , - bool>::type = true> + template Ref(const Ref& _other) : ptr_(_other.ptr()) {} - template , - bool>::type = true> + template Ref(Ref&& _other) noexcept - : ptr_(std::make_shared(std::forward(*_other))) {} + : ptr_(std::forward>(_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& ptr() { return ptr_; } + /// Returns the underlying shared_ptr const std::shared_ptr& ptr() const { return ptr_; } /// Copy assignment operator. - template , - bool>::type = true> + template Ref& operator=(const Ref& _other) { ptr_ = _other.ptr(); return *this; } /// Move assignment operator - template , - bool>::type = true> + template Ref& operator=(Ref&& _other) noexcept { - ptr_ = std::make_shared(std::forward(*_other)); + ptr_ = std::forward>(_other.ptr()); return *this; } diff --git a/include/rfl/Variant.hpp b/include/rfl/Variant.hpp new file mode 100644 index 00000000..b9e4b118 --- /dev/null +++ b/include/rfl/Variant.hpp @@ -0,0 +1,84 @@ +#ifndef RFL_VARIANT_HPP_ +#define RFL_VARIANT_HPP_ + +#include + +namespace rfl { + +template +struct Variant { + /// The type of the underlying variant. + using VariantType = std::variant; + + Variant(const VariantType& _variant) : variant_(_variant) {} + + Variant(VariantType&& _variant) noexcept : variant_(std::move(_variant)) {} + + Variant(const Variant& _variant) = default; + + Variant(Variant&& _variant) noexcept = default; + + template , + bool>::type = true> + Variant(const T& _t) : variant_(_t) {} + + template , + bool>::type = true> + Variant(T&& _t) noexcept : variant_(std::forward(_t)) {} + + ~Variant() = default; + + /// Assigns the underlying object. + Variant& operator=(const VariantType& _variant) { + variant_ = _variant; + return *this; + } + + /// Assigns the underlying object. + Variant& operator=(VariantType&& _variant) { + variant_ = std::move(_variant); + return *this; + } + + /// Assigns the underlying object. + template , + bool>::type = true> + Variant& operator=(T&& _variant) { + variant_ = std::forward(_variant); + return *this; + } + + /// Assigns the underlying object. + template , + bool>::type = true> + Variant& operator=(const T& _variant) { + variant_ = _variant; + return *this; + } + + /// Assigns the underlying object. + Variant& operator=( + const Variant& _other) = default; + + /// Assigns the underlying object. + Variant& operator=( + Variant&& _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 diff --git a/include/rfl/flexbuf.hpp b/include/rfl/flexbuf.hpp new file mode 100644 index 00000000..fe201173 --- /dev/null +++ b/include/rfl/flexbuf.hpp @@ -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 diff --git a/include/rfl/flexbuf/OutputArray.hpp b/include/rfl/flexbuf/OutputArray.hpp new file mode 100644 index 00000000..617de58d --- /dev/null +++ b/include/rfl/flexbuf/OutputArray.hpp @@ -0,0 +1,59 @@ +#ifndef FLEXBUF_OUTPUTARRAY_HPP_ +#define FLEXBUF_OUTPUTARRAY_HPP_ + +#include + +#include +#include + +#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& _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& _var) { vars_.push_back(_var); } + + private: + /// The underlying variables. + std::vector> vars_; +}; + +} // namespace flexbuf +} // namespace rfl + +#endif diff --git a/include/rfl/flexbuf/OutputNull.hpp b/include/rfl/flexbuf/OutputNull.hpp new file mode 100644 index 00000000..c81b9ade --- /dev/null +++ b/include/rfl/flexbuf/OutputNull.hpp @@ -0,0 +1,38 @@ +#ifndef FLEXBUF_OUTPUTNULL_HPP_ +#define FLEXBUF_OUTPUTNULL_HPP_ + +#include + +#include +#include + +#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& _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 diff --git a/include/rfl/flexbuf/OutputObject.hpp b/include/rfl/flexbuf/OutputObject.hpp new file mode 100644 index 00000000..54c7c5ff --- /dev/null +++ b/include/rfl/flexbuf/OutputObject.hpp @@ -0,0 +1,61 @@ +#ifndef FLEXBUF_OUTPUTOBJECT_HPP_ +#define FLEXBUF_OUTPUTOBJECT_HPP_ + +#include + +#include +#include +#include + +#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& _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& _var) { + vars_.push_back(std::make_pair(_name, _var)); + } + + private: + /// The underlying variables. + std::vector>> vars_; +}; + +} // namespace flexbuf +} // namespace rfl + +#endif diff --git a/include/rfl/flexbuf/OutputValue.hpp b/include/rfl/flexbuf/OutputValue.hpp new file mode 100644 index 00000000..7aa476bb --- /dev/null +++ b/include/rfl/flexbuf/OutputValue.hpp @@ -0,0 +1,67 @@ +#ifndef FLEXBUF_OUTPUTVALUE_HPP_ +#define FLEXBUF_OUTPUTVALUE_HPP_ + +#include + +#include +#include +#include + +#include "rfl/Ref.hpp" +#include "rfl/always_false.hpp" +#include "rfl/flexbuf/OutputVar.hpp" + +namespace rfl { +namespace flexbuf { + +template +class OutputValue : public OutputVar { + public: + OutputValue(T _val) : val_(_val) {} + + ~OutputValue() = default; + + /// Inserts all elements into the builder. + void insert(const std::optional& _key, + flexbuffers::Builder* _fbb) final { + if constexpr (std::is_same, std::string>()) { + if (_key) { + _fbb->String(_key->c_str(), val_); + } else { + _fbb->String(val_); + } + } else if constexpr (std::is_same, bool>()) { + if (_key) { + _fbb->Bool(_key->c_str(), val_); + } else { + _fbb->Bool(val_); + } + } else if constexpr (std::is_floating_point>()) { + if (_key) { + _fbb->Double(_key->c_str(), val_); + } else { + _fbb->Double(val_); + } + } else if constexpr (std::is_integral>()) { + if (_key) { + _fbb->Int(_key->c_str(), val_); + } else { + _fbb->Int(val_); + } + } else { + static_assert(always_false_v, "Unsupported type"); + } + }; + + /// Whether this is null. + bool is_null() const final { return false; } + + private: + /// The underlying value. + T val_; +}; + +} // namespace flexbuf +} // namespace rfl + +#endif diff --git a/include/rfl/flexbuf/OutputVar.hpp b/include/rfl/flexbuf/OutputVar.hpp new file mode 100644 index 00000000..9ec6d133 --- /dev/null +++ b/include/rfl/flexbuf/OutputVar.hpp @@ -0,0 +1,25 @@ +#ifndef FLEXBUF_OUTPUTVAR_HPP_ +#define FLEXBUF_OUTPUTVAR_HPP_ + +#include + +#include +#include + +namespace rfl { +namespace flexbuf { + +class OutputVar { + public: + /// Inserts the value into the buffer. + virtual void insert(const std::optional& _key, + flexbuffers::Builder* _fbb) = 0; + + /// Whether this is null. + virtual bool is_null() const = 0; +}; + +} // namespace flexbuf +} // namespace rfl + +#endif diff --git a/include/rfl/flexbuf/Parser.hpp b/include/rfl/flexbuf/Parser.hpp new file mode 100644 index 00000000..cd74a78b --- /dev/null +++ b/include/rfl/flexbuf/Parser.hpp @@ -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 +using Parser = rfl::parsing::Parser; + +} +} // namespace rfl + +#endif diff --git a/include/rfl/flexbuf/Reader.hpp b/include/rfl/flexbuf/Reader.hpp new file mode 100644 index 00000000..0b76a076 --- /dev/null +++ b/include/rfl/flexbuf/Reader.hpp @@ -0,0 +1,169 @@ +#ifndef FLEXBUF_READER_HPP_ +#define FLEXBUF_READER_HPP_ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#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 + struct has_from_flexbuf : std::false_type {}; + + template + struct has_from_flexbuf< + T, std::enable_if_t::value>> + : std::true_type {}; + + template + struct has_from_flexbuf< + T, std::enable_if_t, decltype(T::from_flexbuf), InputVarType>::value>> + : std::true_type {}; + + template + static constexpr bool has_custom_constructor = has_from_flexbuf::value; + + rfl::Result 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 + rfl::Result to_basic_type(const InputVarType& _var) const noexcept { + if constexpr (std::is_same, 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, bool>()) { + if (!_var.IsBool()) { + return rfl::Error("Could not cast to boolean."); + } + return _var.AsBool(); + } else if constexpr (std::is_floating_point>()) { + if (!_var.IsNumeric()) { + return rfl::Error("Could not cast to double."); + } + return static_cast(_var.AsDouble()); + } else if constexpr (std::is_integral>()) { + if (!_var.IsNumeric()) { + return rfl::Error("Could not cast to int."); + } + return static_cast(_var.AsInt64()); + } else { + static_assert(rfl::always_false_v, "Unsupported type."); + } + } + + template + std::array, size> to_fields_array( + const FunctionType& _fct, const InputObjectType& _obj) const noexcept { + std::array, 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 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> to_map( + const InputObjectType& _obj) const noexcept { + std::vector> 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 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 to_vec(const InputArrayType& _arr) const noexcept { + const auto size = _arr.size(); + std::vector vec; + for (size_t i = 0; i < size; ++i) { + vec.push_back(_arr[i]); + } + return vec; + } + + template + rfl::Result 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 diff --git a/include/rfl/flexbuf/Writer.hpp b/include/rfl/flexbuf/Writer.hpp new file mode 100644 index 00000000..079d5d84 --- /dev/null +++ b/include/rfl/flexbuf/Writer.hpp @@ -0,0 +1,69 @@ +#ifndef FLEXBUF_WRITER_HPP_ +#define FLEXBUF_WRITER_HPP_ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#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; + using OutputObjectType = Ref; + using OutputVarType = Ref; + + Writer() {} + + ~Writer() = default; + + void add(const OutputVarType& _var, OutputArrayType* _arr) const noexcept { + (*_arr)->push_back(_var); + } + + OutputVarType empty_var() const noexcept { return Ref::make(); } + + template + OutputVarType from_basic_type(const T& _var) const noexcept { + return Ref>::make(_var); + } + + OutputArrayType new_array() const noexcept { + return Ref::make(); + } + + OutputObjectType new_object() const noexcept { + return Ref::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 diff --git a/include/rfl/flexbuf/load.hpp b/include/rfl/flexbuf/load.hpp new file mode 100644 index 00000000..bbe1f5ec --- /dev/null +++ b/include/rfl/flexbuf/load.hpp @@ -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 +Result load(const std::string& _fname) { + const auto read_bytes = [](const auto& _bytes) { return read(_bytes); }; + return rfl::io::load_bytes(_fname).and_then(read_bytes); +} + +} // namespace flexbuf +} // namespace rfl + +#endif diff --git a/include/rfl/flexbuf/read.hpp b/include/rfl/flexbuf/read.hpp new file mode 100644 index 00000000..d84500d3 --- /dev/null +++ b/include/rfl/flexbuf/read.hpp @@ -0,0 +1,40 @@ +#ifndef FLEXBUF_READ_HPP_ +#define FLEXBUF_READ_HPP_ + +#include + +#include + +#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 +Result read(const InputVarType& _obj) { + const auto r = Reader(); + return Parser::read(r, _obj); +} + +/// Parses an object from flexbuf using reflection. +template +Result read(const unsigned char* _bytes, const size_t _size) { + const InputVarType root = + flexbuffers::GetRoot(reinterpret_cast(_bytes), _size); + return read(root); +} + +/// Parses an object from flexbuf using reflection. +template +Result read(const std::vector& _bytes) { + return read(_bytes.data(), _bytes.size()); +} + +} // namespace flexbuf +} // namespace rfl + +#endif diff --git a/include/rfl/flexbuf/save.hpp b/include/rfl/flexbuf/save.hpp new file mode 100644 index 00000000..8d2aa6d6 --- /dev/null +++ b/include/rfl/flexbuf/save.hpp @@ -0,0 +1,23 @@ +#ifndef RFL_FLEXBUF_SAVE_HPP_ +#define RFL_FLEXBUF_SAVE_HPP_ + +#include +#include +#include + +#include "rfl/Result.hpp" +#include "rfl/flexbuf/write.hpp" +#include "rfl/io/save_bytes.hpp" + +namespace rfl { +namespace flexbuf { + +template +Result save(const std::string& _fname, const T& _obj) { + return rfl::io::save_bytes(_fname, write(_obj)); +} + +} // namespace flexbuf +} // namespace rfl + +#endif diff --git a/include/rfl/flexbuf/write.hpp b/include/rfl/flexbuf/write.hpp new file mode 100644 index 00000000..e23f9244 --- /dev/null +++ b/include/rfl/flexbuf/write.hpp @@ -0,0 +1,31 @@ +#ifndef FLEXBUF_WRITE_HPP_ +#define FLEXBUF_WRITE_HPP_ + +#include + +#include +#include +#include + +#include "rfl/flexbuf/Parser.hpp" + +namespace rfl { +namespace flexbuf { + +/// Writes an object to flexbuf. +template +std::vector write(const T& _obj) { + auto w = Writer(); + const auto flexbuf_obj = Parser::write(w, _obj); + flexbuffers::Builder fbb; + flexbuf_obj->insert(std::nullopt, &fbb); + fbb.Finish(); + const auto vec = fbb.GetBuffer(); + const auto data = reinterpret_cast(vec.data()); + return std::vector(data, data + vec.size()); +} + +} // namespace flexbuf +} // namespace rfl + +#endif diff --git a/include/rfl/internal/to_ptr_field.hpp b/include/rfl/internal/to_ptr_field.hpp index 6468d5e4..4570e9fb 100644 --- a/include/rfl/internal/to_ptr_field.hpp +++ b/include/rfl/internal/to_ptr_field.hpp @@ -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 inline auto to_ptr_field(Field<_name, Type>& _field) { + if constexpr (std::is_pointer_v) { + static_assert(always_false_v, + "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; return Field<_name, T*>(&_field.value_); } template inline auto to_ptr_field(const Field<_name, Type>& _field) { + if constexpr (std::is_pointer_v) { + static_assert(always_false_v, + "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; return Field<_name, const T*>(&_field.value_); } template inline auto to_ptr_field(Flatten& _field) { + if constexpr (std::is_pointer_v) { + static_assert(always_false_v, + "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; return Flatten(&_field.value_); } diff --git a/include/rfl/io/load_bytes.hpp b/include/rfl/io/load_bytes.hpp new file mode 100644 index 00000000..bb945094 --- /dev/null +++ b/include/rfl/io/load_bytes.hpp @@ -0,0 +1,29 @@ +#ifndef RFL_IO_LOAD_BYTES_HPP_ +#define RFL_IO_LOAD_BYTES_HPP_ + +#include +#include +#include +#include + +#include "rfl/Result.hpp" + +namespace rfl { +namespace io { + +Result> load_bytes(const std::string& _fname) { + std::ifstream input(_fname, std::ios::binary); + if (input.is_open()) { + std::istreambuf_iterator begin(input), end; + const auto bytes = std::vector(begin, end); + input.close(); + return bytes; + } else { + return rfl::Error("File '" + _fname + "' not found!"); + } +} + +} // namespace io +} // namespace rfl + +#endif diff --git a/include/rfl/io/save_bytes.hpp b/include/rfl/io/save_bytes.hpp new file mode 100644 index 00000000..e97af1a3 --- /dev/null +++ b/include/rfl/io/save_bytes.hpp @@ -0,0 +1,29 @@ +#ifndef RFL_IO_SAVE_BYTES_HPP_ +#define RFL_IO_SAVE_BYTES_HPP_ + +#include +#include +#include +#include + +#include "rfl/Result.hpp" + +namespace rfl { +namespace io { + +Result save_bytes(const std::string& _fname, + const std::vector& _bytes) { + try { + std::ofstream output(_fname, std::ios::out | std::ios::binary); + output.write(reinterpret_cast(_bytes.data()), _bytes.size()); + output.close(); + } catch (std::exception& e) { + return Error(e.what()); + } + return Nothing{}; +} + +} // namespace io +} // namespace rfl + +#endif diff --git a/include/rfl/json/Reader.hpp b/include/rfl/json/Reader.hpp index bb091643..13548036 100644 --- a/include/rfl/json/Reader.hpp +++ b/include/rfl/json/Reader.hpp @@ -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 - struct has_from_json_obj : std::false_type {}; + template + struct has_from_json_obj : std::false_type {}; - template - struct has_from_json_obj::value>> - : std::true_type {}; + template + struct has_from_json_obj< + T, + std::enable_if_t::value>> + : std::true_type {}; - template - struct has_from_json_obj, decltype(T::from_json_obj), - typename Reader::InputVarType>::value>> - : std::true_type {}; + template + struct has_from_json_obj, decltype(T::from_json_obj), + typename Reader::InputVarType>::value>> + : std::true_type {}; - template - static constexpr bool has_custom_constructor = has_from_json_obj::value; + template + static constexpr bool has_custom_constructor = has_from_json_obj::value; - rfl::Result 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 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 - rfl::Result to_basic_type(const InputVarType _var) const noexcept { - if constexpr (std::is_same, 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, 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>()) { - if (!yyjson_is_num(_var.val_)) { - return rfl::Error("Could not cast to double."); - } - return static_cast(yyjson_get_num(_var.val_)); - } else if constexpr (std::is_integral>()) { - if (!yyjson_is_int(_var.val_)) { - return rfl::Error("Could not cast to int."); - } - return static_cast(yyjson_get_int(_var.val_)); - } else { - static_assert(rfl::always_false_v, "Unsupported type."); - } + template + rfl::Result to_basic_type(const InputVarType _var) const noexcept { + if constexpr (std::is_same, 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, 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>()) { + if (!yyjson_is_num(_var.val_)) { + return rfl::Error("Could not cast to double."); + } + return static_cast(yyjson_get_num(_var.val_)); + } else if constexpr (std::is_integral>()) { + if (!yyjson_is_int(_var.val_)) { + return rfl::Error("Could not cast to int."); + } + return static_cast(yyjson_get_int(_var.val_)); + } else { + static_assert(rfl::always_false_v, "Unsupported type."); } + } - rfl::Result 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 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 - std::array to_fields_array( - const FunctionType _fct, const InputObjectType _obj) const noexcept { - std::array 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 + std::array, size> to_fields_array( + const FunctionType _fct, const InputObjectType _obj) const noexcept { + std::array, 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> to_map( - const InputObjectType _obj) const noexcept { - std::vector> 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> to_map( + const InputObjectType _obj) const noexcept { + std::vector> 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 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 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 to_vec(const InputArrayType _arr) const noexcept { - std::vector 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 to_vec(const InputArrayType _arr) const noexcept { + std::vector 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 - rfl::Result 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 + rfl::Result 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 diff --git a/include/rfl/json/load.hpp b/include/rfl/json/load.hpp index 2f34febf..c5fff274 100644 --- a/include/rfl/json/load.hpp +++ b/include/rfl/json/load.hpp @@ -10,7 +10,8 @@ namespace json { template Result load(const std::string& _fname) { - return rfl::io::load_string(_fname).and_then(read); + const auto read_string = [](const auto& _str) { return read(_str); }; + return rfl::io::load_string(_fname).and_then(read_string); } } // namespace json diff --git a/include/rfl/json/save.hpp b/include/rfl/json/save.hpp index 614f3917..433e159e 100644 --- a/include/rfl/json/save.hpp +++ b/include/rfl/json/save.hpp @@ -14,7 +14,7 @@ namespace json { template Result 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 diff --git a/include/rfl/parsing/IsReader.hpp b/include/rfl/parsing/IsReader.hpp index d3db7adc..9e4fa7f4 100644 --- a/include/rfl/parsing/IsReader.hpp +++ b/include/rfl/parsing/IsReader.hpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include @@ -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>; + /// Retrieves a particular field from an object. + { + r.get_field(name, obj) + } -> std::same_as>; - /// Determines whether a variable is empty (the NULL type). - { r.is_empty(var) } -> std::same_as; + /// Determines whether a variable is empty (the NULL type). + { r.is_empty(var) } -> std::same_as; - /// Transforms var to a basic type (bool, integral, - /// floating point, std::string) - { r.template to_basic_type(var) } -> std::same_as>; + /// Transforms var to a basic type (bool, integral, + /// floating point, std::string) + { r.template to_basic_type(var) } -> std::same_as>; - /// 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>; + /// 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, 6>>; - /// Casts var as an InputArrayType. - { - r.to_array(var) - } -> std::same_as>; + /// Casts var as an InputArrayType. + { r.to_array(var) } -> std::same_as>; - /// Iterates through an object and writes the contained key-value pairs into - /// a vector. - { - r.to_map(obj) - } -> std::same_as< - std::vector>>; + /// Iterates through an object and writes the contained key-value pairs into + /// a vector. + { + r.to_map(obj) + } -> std::same_as< + std::vector>>; - /// Casts var as an InputObjectType. - { - r.to_object(var) - } -> std::same_as>; + /// Casts var as an InputObjectType. + { + r.to_object(var) + } -> std::same_as>; - /// Iterates through an array and writes the contained vars into - /// a vector. - { r.to_vec(arr) } -> std::same_as>; + /// Iterates through an array and writes the contained vars into + /// a vector. + { r.to_vec(arr) } -> std::same_as>; - /// Uses the custom constructor, if it has been determined that T has one - /// (see above). - { - r.template use_custom_constructor(var) - } -> std::same_as>; + /// Uses the custom constructor, if it has been determined that T has one + /// (see above). + { r.template use_custom_constructor(var) } -> std::same_as>; }; } // namespace parsing diff --git a/include/rfl/parsing/Parser.hpp b/include/rfl/parsing/Parser.hpp index f8951ab1..1122712a 100644 --- a/include/rfl/parsing/Parser.hpp +++ b/include/rfl/parsing/Parser.hpp @@ -370,7 +370,8 @@ struct Parser> { template static Result> build_named_tuple_recursively( const R& _r, - const std::array& _fields_vec, + const std::array, sizeof...(FieldTypes)>& + _fields_arr, Args&&... _args) noexcept { constexpr auto i = sizeof...(Args); @@ -382,32 +383,32 @@ struct Parser> { using ValueType = std::decay_t; - const auto& f = std::get(_fields_vec); + const auto& f = std::get(_fields_arr); - if (_r.is_empty(f)) { + if (!f) { if constexpr (is_required()) { const auto key = FieldType::name_.str(); return collect_errors( - _r, _fields_vec, + _r, _fields_arr, std::vector( {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(_r, _fields_vec, + return collect_errors(_r, _fields_arr, std::vector({std::move(_error)})); }; - return get_value(_r, f).or_else(handle_error).and_then(build); + return get_value(_r, *f).or_else(handle_error).and_then(build); } } @@ -416,7 +417,8 @@ struct Parser> { template static Error collect_errors( const R& _r, - const std::array& _fields_vec, + const std::array, sizeof...(FieldTypes)>& + _fields_arr, std::vector _errors) noexcept { if constexpr (_i == sizeof...(FieldTypes)) { if (_errors.size() == 1) { @@ -435,14 +437,14 @@ struct Parser> { using ValueType = std::decay_t; - 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()) { 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> { return _error; }; - get_value(_r, f).or_else(add_error_if_applicable); + get_value(_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 +requires AreReaderAndWriter> +struct Parser> { + using InputVarType = typename R::InputVarType; + using OutputVarType = typename W::OutputVarType; + + /// Expresses the variables as type T. + static Result> read( + const R& _r, const InputVarType& _var) noexcept { + const auto to_rfl_variant = [](auto&& _var) { + return rfl::Variant( + std::forward>(_var)); + }; + return Parser>::read(_r, _var).transform( + to_rfl_variant); + } + + static OutputVarType write( + const W& _w, const rfl::Variant& _variant) noexcept { + return Parser>::write(_w, + _variant.variant()); + } +}; + +// ---------------------------------------------------------------------------- + template requires AreReaderAndWriter> struct Parser> { diff --git a/tests/flexbuffers/CMakeLists.txt b/tests/flexbuffers/CMakeLists.txt new file mode 100644 index 00000000..6c65cd8a --- /dev/null +++ b/tests/flexbuffers/CMakeLists.txt @@ -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 +) diff --git a/tests/flexbuffers/Dockerfile b/tests/flexbuffers/Dockerfile new file mode 100644 index 00000000..97f250af --- /dev/null +++ b/tests/flexbuffers/Dockerfile @@ -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 diff --git a/tests/flexbuffers/build_docker.sh b/tests/flexbuffers/build_docker.sh new file mode 100755 index 00000000..3db3c555 --- /dev/null +++ b/tests/flexbuffers/build_docker.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +docker build --tag=reflectcpp_test_flexbuffers . diff --git a/tests/flexbuffers/compile.sh b/tests/flexbuffers/compile.sh new file mode 100755 index 00000000..e182e01f --- /dev/null +++ b/tests/flexbuffers/compile.sh @@ -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 diff --git a/tests/flexbuffers/compile_on_docker.sh b/tests/flexbuffers/compile_on_docker.sh new file mode 100644 index 00000000..6a6277af --- /dev/null +++ b/tests/flexbuffers/compile_on_docker.sh @@ -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 diff --git a/tests/flexbuffers/test_all_of.hpp b/tests/flexbuffers/test_all_of.hpp new file mode 100644 index 00000000..b568c6d0 --- /dev/null +++ b/tests/flexbuffers/test_all_of.hpp @@ -0,0 +1,25 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +void test_all_of() { + std::cout << "test_all_of" << std::endl; + + using Age = rfl::Validator, 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); +} diff --git a/tests/flexbuffers/test_anonymous_fields.hpp b/tests/flexbuffers/test_anonymous_fields.hpp new file mode 100644 index 00000000..0b1e229f --- /dev/null +++ b/tests/flexbuffers/test_anonymous_fields.hpp @@ -0,0 +1,51 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +void test_anonymous_fields() { + std::cout << "test_anonymous_fields" << std::endl; + + using Age = rfl::Validator, 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 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({bart, lisa, maggie})}; + + write_and_read(homer); +} diff --git a/tests/flexbuffers/test_box.hpp b/tests/flexbuffers/test_box.hpp new file mode 100644 index 00000000..2de1b372 --- /dev/null +++ b/tests/flexbuffers/test_box.hpp @@ -0,0 +1,43 @@ +#include +#include +#include +#include +#include +#include + +#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> lesser; + rfl::Field<"right", rfl::Box> 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{leaf1}), + .greater = rfl::make_box(DecisionTree{leaf2})}; + + const DecisionTree tree{.leaf_or_node = std::move(node)}; + + write_and_read(tree); +} diff --git a/tests/flexbuffers/test_custom_class1.hpp b/tests/flexbuffers/test_custom_class1.hpp new file mode 100644 index 00000000..1d8425ba --- /dev/null +++ b/tests/flexbuffers/test_custom_class1.hpp @@ -0,0 +1,37 @@ +#include +#include +#include +#include +#include +#include + +#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> 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); +} diff --git a/tests/flexbuffers/test_custom_class2.hpp b/tests/flexbuffers/test_custom_class2.hpp new file mode 100644 index 00000000..101849f1 --- /dev/null +++ b/tests/flexbuffers/test_custom_class2.hpp @@ -0,0 +1,62 @@ +#include +#include +#include +#include +#include +#include + +#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 +struct Parser + : public CustomParser {}; + +} // 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); +} diff --git a/tests/flexbuffers/test_custom_class3.hpp b/tests/flexbuffers/test_custom_class3.hpp new file mode 100644 index 00000000..06d95c62 --- /dev/null +++ b/tests/flexbuffers/test_custom_class3.hpp @@ -0,0 +1,63 @@ +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +namespace tcc3 { + +struct Person { + Person(const std::string& _first_name, + const rfl::Box& _last_name, int _age) + : first_name_(_first_name), + last_name_(rfl::make_box(*_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 last_name_; + int age_; +}; + +struct PersonImpl { + rfl::Field<"firstName", std::string> first_name; + rfl::Field<"lastName", rfl::Box> 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(*_p.last_name()), + .age = _p.age()}; + } +}; + +} // namespace tcc3 + +namespace rfl { +namespace parsing { + +template +struct Parser + : public CustomParser {}; + +} // namespace parsing +} // namespace rfl + +void test_custom_class3() { + std::cout << "test_custom_class3" << std::endl; + + const auto bart = + tcc3::Person("Bart", rfl::make_box("Simpson"), 10); + + write_and_read(bart); +} diff --git a/tests/flexbuffers/test_custom_constructor.hpp b/tests/flexbuffers/test_custom_constructor.hpp new file mode 100644 index 00000000..08b36c84 --- /dev/null +++ b/tests/flexbuffers/test_custom_constructor.hpp @@ -0,0 +1,55 @@ +#include +#include +#include +#include +#include + +#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 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(std::move(_nt)); + }; + return rfl::flexbuf::read>(_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(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; + } +} diff --git a/tests/flexbuffers/test_deque.hpp b/tests/flexbuffers/test_deque.hpp new file mode 100644 index 00000000..ad0a3311 --- /dev/null +++ b/tests/flexbuffers/test_deque.hpp @@ -0,0 +1,28 @@ +#include +#include +#include +#include +#include + +#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>> children = + rfl::default_value; + }; + + auto children = std::make_unique>(); + 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); +} diff --git a/tests/flexbuffers/test_field_variant.hpp b/tests/flexbuffers/test_field_variant.hpp new file mode 100644 index 00000000..3aa9d305 --- /dev/null +++ b/tests/flexbuffers/test_field_variant.hpp @@ -0,0 +1,34 @@ +#include +#include +#include +#include +#include +#include + +#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<"rectangle", Rectangle>, + rfl::Field<"square", rfl::Box>>; + + const Shapes r = + rfl::make_field<"rectangle">(Rectangle{.height = 10, .width = 5}); + + write_and_read(r); +} diff --git a/tests/flexbuffers/test_forward_list.hpp b/tests/flexbuffers/test_forward_list.hpp new file mode 100644 index 00000000..da8da2da --- /dev/null +++ b/tests/flexbuffers/test_forward_list.hpp @@ -0,0 +1,28 @@ +#include +#include +#include +#include +#include + +#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>> + children = rfl::default_value; + }; + + auto children = std::make_unique>(); + 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); +} diff --git a/tests/flexbuffers/test_list.hpp b/tests/flexbuffers/test_list.hpp new file mode 100644 index 00000000..637bcd70 --- /dev/null +++ b/tests/flexbuffers/test_list.hpp @@ -0,0 +1,28 @@ +#include +#include +#include +#include +#include + +#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>> children = + rfl::default_value; + }; + + auto children = std::make_unique>(); + 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); +} diff --git a/tests/flexbuffers/test_literal.hpp b/tests/flexbuffers/test_literal.hpp new file mode 100644 index 00000000..5bff332a --- /dev/null +++ b/tests/flexbuffers/test_literal.hpp @@ -0,0 +1,26 @@ +#include +#include +#include +#include +#include +#include + +#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> children = rfl::default_value; + }; + + const auto bart = Person{.first_name = FirstName::make<"Bart">()}; + + write_and_read(bart); +} diff --git a/tests/flexbuffers/test_map.hpp b/tests/flexbuffers/test_map.hpp new file mode 100644 index 00000000..afba3d4e --- /dev/null +++ b/tests/flexbuffers/test_map.hpp @@ -0,0 +1,28 @@ +#include +#include +#include +#include +#include + +#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>> + children = rfl::default_value; + }; + + auto children = std::make_unique>(); + 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); +} diff --git a/tests/flexbuffers/test_monster_example1.hpp b/tests/flexbuffers/test_monster_example1.hpp new file mode 100644 index 00000000..c0449005 --- /dev/null +++ b/tests/flexbuffers/test_monster_example1.hpp @@ -0,0 +1,61 @@ +#include +#include +#include +#include +#include + +#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>; + + 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 inventory; + Color color = Color::make<"Blue">(); + std::vector weapons; + Equipment equipped; + std::vector path; + }; + + const auto sword = Weapon{.name = "Sword", .damage = 3}; + const auto axe = Weapon{.name = "Axe", .damage = 5}; + + const auto weapons = std::vector({sword, axe}); + + const auto position = Vec3{1.0f, 2.0f, 3.0f}; + + const auto inventory = + std::vector({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); +} + diff --git a/tests/flexbuffers/test_monster_example2.hpp b/tests/flexbuffers/test_monster_example2.hpp new file mode 100644 index 00000000..2cb79197 --- /dev/null +++ b/tests/flexbuffers/test_monster_example2.hpp @@ -0,0 +1,62 @@ +#include +#include +#include +#include +#include + +#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>; + + 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> inventory; + rfl::Field<"color", Color> color = Color::make<"Blue">(); + rfl::Field<"weapons", std::vector> weapons; + rfl::Field<"equipped", Equipment> equipped; + rfl::Field<"path", std::vector> path; + }; + + const auto sword = Weapon{.name = "Sword", .damage = 3}; + const auto axe = Weapon{.name = "Axe", .damage = 5}; + + const auto weapons = std::vector({sword, axe}); + + const auto position = Vec3{1.0f, 2.0f, 3.0f}; + + const auto inventory = + std::vector({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); +} + diff --git a/tests/flexbuffers/test_multimap.hpp b/tests/flexbuffers/test_multimap.hpp new file mode 100644 index 00000000..7b28ab84 --- /dev/null +++ b/tests/flexbuffers/test_multimap.hpp @@ -0,0 +1,28 @@ +#include +#include +#include +#include +#include + +#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>> + children = rfl::default_value; + }; + + auto children = std::make_unique>(); + 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); +} diff --git a/tests/flexbuffers/test_multiset.hpp b/tests/flexbuffers/test_multiset.hpp new file mode 100644 index 00000000..2bc3455f --- /dev/null +++ b/tests/flexbuffers/test_multiset.hpp @@ -0,0 +1,26 @@ +#include +#include +#include +#include +#include + +#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>> + children = rfl::default_value; + }; + + auto children = std::make_unique>( + std::multiset({"Bart", "Lisa", "Maggie"})); + + const auto homer = + Person{.first_name = "Homer", .children = std::move(children)}; + + write_and_read(homer); +} diff --git a/tests/flexbuffers/test_optional_fields.hpp b/tests/flexbuffers/test_optional_fields.hpp new file mode 100644 index 00000000..fd5c777d --- /dev/null +++ b/tests/flexbuffers/test_optional_fields.hpp @@ -0,0 +1,30 @@ +#include +#include +#include +#include +#include + +#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>> 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({bart, lisa, maggie})}; + + write_and_read(homer); +} diff --git a/tests/flexbuffers/test_readme_example.hpp b/tests/flexbuffers/test_readme_example.hpp new file mode 100644 index 00000000..df31a5a8 --- /dev/null +++ b/tests/flexbuffers/test_readme_example.hpp @@ -0,0 +1,54 @@ +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +void test_readme_example() { + std::cout << "test_readme_example" << std::endl; + + using Age = rfl::Validator, 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> children; + }; + + const auto bart = Person{.first_name = "Bart", + .last_name = "Simpson", + .birthday = "1987-04-19", + .age = 10, + .email = "bart@simpson.com", + .children = std::vector()}; + + 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() + }; + + 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({bart, lisa, maggie})}; + + write_and_read(homer); +} diff --git a/tests/flexbuffers/test_ref.hpp b/tests/flexbuffers/test_ref.hpp new file mode 100644 index 00000000..c9f7e2cf --- /dev/null +++ b/tests/flexbuffers/test_ref.hpp @@ -0,0 +1,43 @@ +#include +#include +#include +#include +#include +#include + +#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> lesser; + rfl::Field<"right", rfl::Ref> 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{leaf1}), + .greater = rfl::make_ref(DecisionTree{leaf2})}; + + const DecisionTree tree{.leaf_or_node = std::move(node)}; + + write_and_read(tree); +} diff --git a/tests/flexbuffers/test_save_load.hpp b/tests/flexbuffers/test_save_load.hpp new file mode 100644 index 00000000..505c1c55 --- /dev/null +++ b/tests/flexbuffers/test_save_load.hpp @@ -0,0 +1,68 @@ +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +void test_save_load() { + std::cout << "test_save_load" << std::endl; + + using Age = rfl::Validator, 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> children; + }; + + const auto bart = Person{.first_name = "Bart", + .last_name = "Simpson", + .birthday = "1987-04-19", + .age = 10, + .email = "bart@simpson.com", + .children = std::vector()}; + + 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() + }; + + 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({bart, lisa, maggie})}; + + rfl::flexbuf::save("homer.fb", homer1); + + const auto homer2 = rfl::flexbuf::load("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; +} diff --git a/tests/flexbuffers/test_set.hpp b/tests/flexbuffers/test_set.hpp new file mode 100644 index 00000000..1dceee01 --- /dev/null +++ b/tests/flexbuffers/test_set.hpp @@ -0,0 +1,26 @@ +#include +#include +#include +#include +#include + +#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>> + children = rfl::default_value; + }; + + auto children = std::make_unique>( + std::set({"Bart", "Lisa", "Maggie"})); + + const auto homer = + Person{.first_name = "Homer", .children = std::move(children)}; + + write_and_read(homer); +} diff --git a/tests/flexbuffers/test_string_map.hpp b/tests/flexbuffers/test_string_map.hpp new file mode 100644 index 00000000..a1d97aed --- /dev/null +++ b/tests/flexbuffers/test_string_map.hpp @@ -0,0 +1,20 @@ +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +void test_string_map() { + std::cout << "test_string_map" << std::endl; + + std::map> homer; + homer.insert( + std::make_pair("firstName", std::make_unique("Homer"))); + homer.insert( + std::make_pair("lastName", std::make_unique("Simpson"))); + + write_and_read(homer); +} diff --git a/tests/flexbuffers/test_string_unordered_map.hpp b/tests/flexbuffers/test_string_unordered_map.hpp new file mode 100644 index 00000000..325277ca --- /dev/null +++ b/tests/flexbuffers/test_string_unordered_map.hpp @@ -0,0 +1,25 @@ +#include +#include +#include +#include +#include +#include + +#include "write_and_read.hpp" + +void test_string_unordered_map() { + std::cout << "test_string_unordered_map" << std::endl; + + using Map = std::unordered_map>; + Map homer; + homer.insert( + std::make_pair("firstName", std::make_unique("Homer"))); + homer.insert( + std::make_pair("lastName", std::make_unique("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(json_string); + std::cout << "OK" << std::endl << std::endl; +} diff --git a/tests/flexbuffers/test_tagged_union.hpp b/tests/flexbuffers/test_tagged_union.hpp new file mode 100644 index 00000000..a33b6fbe --- /dev/null +++ b/tests/flexbuffers/test_tagged_union.hpp @@ -0,0 +1,35 @@ +#include +#include +#include +#include +#include +#include + +#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); +} diff --git a/tests/flexbuffers/test_unique_ptr.hpp b/tests/flexbuffers/test_unique_ptr.hpp new file mode 100644 index 00000000..3f36e5d0 --- /dev/null +++ b/tests/flexbuffers/test_unique_ptr.hpp @@ -0,0 +1,29 @@ +#include +#include +#include +#include +#include +#include + +#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>> children = + rfl::default_value; + }; + + auto children = std::make_unique>(); + 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); +} diff --git a/tests/flexbuffers/test_unique_ptr2.hpp b/tests/flexbuffers/test_unique_ptr2.hpp new file mode 100644 index 00000000..dcfaa060 --- /dev/null +++ b/tests/flexbuffers/test_unique_ptr2.hpp @@ -0,0 +1,43 @@ +#include +#include +#include +#include +#include +#include + +#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> lesser; + rfl::Field<"right", std::unique_ptr> 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{leaf1}), + .greater = std::make_unique(DecisionTree{leaf2})}; + + const DecisionTree tree{.leaf_or_node = std::move(node)}; + + write_and_read(tree); +} diff --git a/tests/flexbuffers/test_unordered_map.hpp b/tests/flexbuffers/test_unordered_map.hpp new file mode 100644 index 00000000..17c02df6 --- /dev/null +++ b/tests/flexbuffers/test_unordered_map.hpp @@ -0,0 +1,32 @@ +#include +#include +#include +#include +#include + +#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>> + children = rfl::default_value; + }; + + auto children = std::make_unique>(); + 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(json_string); + std::cout << "OK" << std::endl << std::endl; +} diff --git a/tests/flexbuffers/test_unordered_multimap.hpp b/tests/flexbuffers/test_unordered_multimap.hpp new file mode 100644 index 00000000..8cf4302c --- /dev/null +++ b/tests/flexbuffers/test_unordered_multimap.hpp @@ -0,0 +1,33 @@ +#include +#include +#include +#include +#include + +#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>> + children = rfl::default_value; + }; + + auto children = std::make_unique>(); + 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(json_string); + std::cout << "OK" << std::endl << std::endl; +} diff --git a/tests/flexbuffers/test_unordered_multiset.hpp b/tests/flexbuffers/test_unordered_multiset.hpp new file mode 100644 index 00000000..2289b8d6 --- /dev/null +++ b/tests/flexbuffers/test_unordered_multiset.hpp @@ -0,0 +1,31 @@ +#include +#include +#include +#include +#include + +#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>> + children = rfl::default_value; + }; + + auto children = std::make_unique>( + std::unordered_multiset({"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(json_string); + std::cout << "OK" << std::endl << std::endl; +} diff --git a/tests/flexbuffers/test_unordered_set.hpp b/tests/flexbuffers/test_unordered_set.hpp new file mode 100644 index 00000000..50ce449b --- /dev/null +++ b/tests/flexbuffers/test_unordered_set.hpp @@ -0,0 +1,30 @@ +#include +#include +#include +#include +#include + +#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>> + children = rfl::default_value; + }; + + auto children = std::make_unique>( + std::unordered_set({"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(json_string); + std::cout << "OK" << std::endl << std::endl; +} diff --git a/tests/flexbuffers/test_variant.hpp b/tests/flexbuffers/test_variant.hpp new file mode 100644 index 00000000..da4e1f70 --- /dev/null +++ b/tests/flexbuffers/test_variant.hpp @@ -0,0 +1,32 @@ +#include +#include +#include +#include +#include +#include + +#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>; + + const Shapes r = Rectangle{.height = 10, .width = 5}; + + write_and_read(r); +} diff --git a/tests/flexbuffers/tests.cpp b/tests/flexbuffers/tests.cpp new file mode 100644 index 00000000..0b2bc4a7 --- /dev/null +++ b/tests/flexbuffers/tests.cpp @@ -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; +} diff --git a/tests/flexbuffers/write_and_read.hpp b/tests/flexbuffers/write_and_read.hpp new file mode 100644 index 00000000..8bf426f3 --- /dev/null +++ b/tests/flexbuffers/write_and_read.hpp @@ -0,0 +1,39 @@ +#ifndef WRITE_AND_READ_ +#define WRITE_AND_READ_ + +#include +#include +#include + +template +void write_and_read(const T& _struct) { + const auto bytes1 = rfl::flexbuf::write(_struct); + + const auto res = rfl::flexbuf::read(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 diff --git a/tests/CMakeLists.txt b/tests/json/CMakeLists.txt similarity index 89% rename from tests/CMakeLists.txt rename to tests/json/CMakeLists.txt index de1f3658..c99b0b84 100644 --- a/tests/CMakeLists.txt +++ b/tests/json/CMakeLists.txt @@ -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") diff --git a/tests/test_all_of.hpp b/tests/json/test_all_of.hpp similarity index 100% rename from tests/test_all_of.hpp rename to tests/json/test_all_of.hpp diff --git a/tests/test_anonymous_fields.hpp b/tests/json/test_anonymous_fields.hpp similarity index 100% rename from tests/test_anonymous_fields.hpp rename to tests/json/test_anonymous_fields.hpp diff --git a/tests/test_any_of.hpp b/tests/json/test_any_of.hpp similarity index 100% rename from tests/test_any_of.hpp rename to tests/json/test_any_of.hpp diff --git a/tests/test_array.hpp b/tests/json/test_array.hpp similarity index 100% rename from tests/test_array.hpp rename to tests/json/test_array.hpp diff --git a/tests/test_as.hpp b/tests/json/test_as.hpp similarity index 100% rename from tests/test_as.hpp rename to tests/json/test_as.hpp diff --git a/tests/test_as_flatten.hpp b/tests/json/test_as_flatten.hpp similarity index 100% rename from tests/test_as_flatten.hpp rename to tests/json/test_as_flatten.hpp diff --git a/tests/test_box.hpp b/tests/json/test_box.hpp similarity index 100% rename from tests/test_box.hpp rename to tests/json/test_box.hpp diff --git a/tests/test_custom_class1.hpp b/tests/json/test_custom_class1.hpp similarity index 100% rename from tests/test_custom_class1.hpp rename to tests/json/test_custom_class1.hpp diff --git a/tests/test_custom_class2.hpp b/tests/json/test_custom_class2.hpp similarity index 100% rename from tests/test_custom_class2.hpp rename to tests/json/test_custom_class2.hpp diff --git a/tests/test_custom_class3.hpp b/tests/json/test_custom_class3.hpp similarity index 100% rename from tests/test_custom_class3.hpp rename to tests/json/test_custom_class3.hpp diff --git a/tests/test_custom_class4.hpp b/tests/json/test_custom_class4.hpp similarity index 100% rename from tests/test_custom_class4.hpp rename to tests/json/test_custom_class4.hpp diff --git a/tests/test_custom_constructor.hpp b/tests/json/test_custom_constructor.hpp similarity index 100% rename from tests/test_custom_constructor.hpp rename to tests/json/test_custom_constructor.hpp diff --git a/tests/test_default_values.hpp b/tests/json/test_default_values.hpp similarity index 100% rename from tests/test_default_values.hpp rename to tests/json/test_default_values.hpp diff --git a/tests/test_deque.hpp b/tests/json/test_deque.hpp similarity index 100% rename from tests/test_deque.hpp rename to tests/json/test_deque.hpp diff --git a/tests/test_email.hpp b/tests/json/test_email.hpp similarity index 100% rename from tests/test_email.hpp rename to tests/json/test_email.hpp diff --git a/tests/test_error_messages.hpp b/tests/json/test_error_messages.hpp similarity index 100% rename from tests/test_error_messages.hpp rename to tests/json/test_error_messages.hpp diff --git a/tests/json/test_field_variant.hpp b/tests/json/test_field_variant.hpp new file mode 100644 index 00000000..ec77300e --- /dev/null +++ b/tests/json/test_field_variant.hpp @@ -0,0 +1,34 @@ +#include +#include +#include +#include +#include +#include + +#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<"rectangle", Rectangle>, + rfl::Field<"square", rfl::Box>>; + + const Shapes r = + rfl::make_field<"rectangle">(Rectangle{.height = 10, .width = 5}); + + write_and_read(r, R"({"rectangle":{"height":10.0,"width":5.0}})"); +} diff --git a/tests/test_flatten.hpp b/tests/json/test_flatten.hpp similarity index 100% rename from tests/test_flatten.hpp rename to tests/json/test_flatten.hpp diff --git a/tests/test_forward_list.hpp b/tests/json/test_forward_list.hpp similarity index 100% rename from tests/test_forward_list.hpp rename to tests/json/test_forward_list.hpp diff --git a/tests/test_list.hpp b/tests/json/test_list.hpp similarity index 100% rename from tests/test_list.hpp rename to tests/json/test_list.hpp diff --git a/tests/test_literal.hpp b/tests/json/test_literal.hpp similarity index 100% rename from tests/test_literal.hpp rename to tests/json/test_literal.hpp diff --git a/tests/test_map.hpp b/tests/json/test_map.hpp similarity index 100% rename from tests/test_map.hpp rename to tests/json/test_map.hpp diff --git a/tests/json/test_monster_example.hpp b/tests/json/test_monster_example.hpp new file mode 100644 index 00000000..a4bdabdc --- /dev/null +++ b/tests/json/test_monster_example.hpp @@ -0,0 +1,63 @@ +#include +#include +#include +#include +#include + +#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>; + + 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 inventory; + Color color = Color::make<"Blue">(); + std::vector weapons; + Equipment equipped; + std::vector path; + }; + + const auto sword = Weapon{.name = "Sword", .damage = 3}; + const auto axe = Weapon{.name = "Axe", .damage = 5}; + + const auto weapons = std::vector({sword, axe}); + + const auto position = Vec3{1.0f, 2.0f, 3.0f}; + + const auto inventory = + std::vector({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]},[]])"); +} + diff --git a/tests/test_move_replace.hpp b/tests/json/test_move_replace.hpp similarity index 100% rename from tests/test_move_replace.hpp rename to tests/json/test_move_replace.hpp diff --git a/tests/test_multimap.hpp b/tests/json/test_multimap.hpp similarity index 100% rename from tests/test_multimap.hpp rename to tests/json/test_multimap.hpp diff --git a/tests/test_multiset.hpp b/tests/json/test_multiset.hpp similarity index 100% rename from tests/test_multiset.hpp rename to tests/json/test_multiset.hpp diff --git a/tests/test_one_of.hpp b/tests/json/test_one_of.hpp similarity index 100% rename from tests/test_one_of.hpp rename to tests/json/test_one_of.hpp diff --git a/tests/test_optional_fields.hpp b/tests/json/test_optional_fields.hpp similarity index 100% rename from tests/test_optional_fields.hpp rename to tests/json/test_optional_fields.hpp diff --git a/tests/test_readme_example.hpp b/tests/json/test_readme_example.hpp similarity index 100% rename from tests/test_readme_example.hpp rename to tests/json/test_readme_example.hpp diff --git a/tests/test_ref.hpp b/tests/json/test_ref.hpp similarity index 100% rename from tests/test_ref.hpp rename to tests/json/test_ref.hpp diff --git a/tests/test_replace.hpp b/tests/json/test_replace.hpp similarity index 100% rename from tests/test_replace.hpp rename to tests/json/test_replace.hpp diff --git a/tests/test_replace_flatten.hpp b/tests/json/test_replace_flatten.hpp similarity index 100% rename from tests/test_replace_flatten.hpp rename to tests/json/test_replace_flatten.hpp diff --git a/tests/test_replace_with_other_struct.hpp b/tests/json/test_replace_with_other_struct.hpp similarity index 100% rename from tests/test_replace_with_other_struct.hpp rename to tests/json/test_replace_with_other_struct.hpp diff --git a/tests/test_result.hpp b/tests/json/test_result.hpp similarity index 100% rename from tests/test_result.hpp rename to tests/json/test_result.hpp diff --git a/tests/json/test_save_load.hpp b/tests/json/test_save_load.hpp new file mode 100644 index 00000000..f47dca18 --- /dev/null +++ b/tests/json/test_save_load.hpp @@ -0,0 +1,66 @@ +#include +#include +#include +#include +#include +#include + +void test_save_load() { + std::cout << "test_save_load" << std::endl; + + using Age = rfl::Validator, 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> children; + }; + + const auto bart = Person{.first_name = "Bart", + .last_name = "Simpson", + .birthday = "1987-04-19", + .age = 10, + .email = "bart@simpson.com", + .children = std::vector()}; + + 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() + }; + + 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({bart, lisa, maggie})}; + + rfl::json::save("homer.json", homer1); + + const auto homer2 = rfl::json::load("homer.json").value(); + + const auto string1 = rfl::json::write(homer1); + const auto string2 = rfl::json::write(homer2); + + if (string1 != string2) { + std::cout << "Test failed. Content was not identical." << std::endl + << std::endl; + return; + } + + std::cout << "OK" << std::endl << std::endl; +} diff --git a/tests/test_set.hpp b/tests/json/test_set.hpp similarity index 100% rename from tests/test_set.hpp rename to tests/json/test_set.hpp diff --git a/tests/test_size.hpp b/tests/json/test_size.hpp similarity index 100% rename from tests/test_size.hpp rename to tests/json/test_size.hpp diff --git a/tests/test_string_map.hpp b/tests/json/test_string_map.hpp similarity index 100% rename from tests/test_string_map.hpp rename to tests/json/test_string_map.hpp diff --git a/tests/test_string_unordered_map.hpp b/tests/json/test_string_unordered_map.hpp similarity index 100% rename from tests/test_string_unordered_map.hpp rename to tests/json/test_string_unordered_map.hpp diff --git a/tests/test_tagged_union.hpp b/tests/json/test_tagged_union.hpp similarity index 100% rename from tests/test_tagged_union.hpp rename to tests/json/test_tagged_union.hpp diff --git a/tests/test_timestamp.hpp b/tests/json/test_timestamp.hpp similarity index 100% rename from tests/test_timestamp.hpp rename to tests/json/test_timestamp.hpp diff --git a/tests/test_unique_ptr.hpp b/tests/json/test_unique_ptr.hpp similarity index 100% rename from tests/test_unique_ptr.hpp rename to tests/json/test_unique_ptr.hpp diff --git a/tests/test_unique_ptr2.hpp b/tests/json/test_unique_ptr2.hpp similarity index 100% rename from tests/test_unique_ptr2.hpp rename to tests/json/test_unique_ptr2.hpp diff --git a/tests/test_unordered_map.hpp b/tests/json/test_unordered_map.hpp similarity index 100% rename from tests/test_unordered_map.hpp rename to tests/json/test_unordered_map.hpp diff --git a/tests/test_unordered_multimap.hpp b/tests/json/test_unordered_multimap.hpp similarity index 100% rename from tests/test_unordered_multimap.hpp rename to tests/json/test_unordered_multimap.hpp diff --git a/tests/test_unordered_multiset.hpp b/tests/json/test_unordered_multiset.hpp similarity index 100% rename from tests/test_unordered_multiset.hpp rename to tests/json/test_unordered_multiset.hpp diff --git a/tests/test_unordered_set.hpp b/tests/json/test_unordered_set.hpp similarity index 100% rename from tests/test_unordered_set.hpp rename to tests/json/test_unordered_set.hpp diff --git a/tests/test_variant.hpp b/tests/json/test_variant.hpp similarity index 100% rename from tests/test_variant.hpp rename to tests/json/test_variant.hpp diff --git a/tests/tests.cpp b/tests/json/tests.cpp similarity index 95% rename from tests/tests.cpp rename to tests/json/tests.cpp index bc7cad46..72e01bca 100644 --- a/tests/tests.cpp +++ b/tests/json/tests.cpp @@ -20,6 +20,7 @@ #include "test_list.hpp" #include "test_literal.hpp" #include "test_map.hpp" +#include "test_monster_example.hpp" #include "test_multimap.hpp" #include "test_multiset.hpp" #include "test_one_of.hpp" @@ -30,6 +31,7 @@ #include "test_replace_flatten.hpp" #include "test_replace_with_other_struct.hpp" #include "test_result.hpp" +#include "test_save_load.hpp" #include "test_set.hpp" #include "test_size.hpp" #include "test_string_map.hpp" @@ -75,6 +77,7 @@ int main() { test_error_messages(); test_result(); test_anonymous_fields(); + test_monster_example(); test_custom_class1(); test_custom_class2(); @@ -95,5 +98,7 @@ int main() { test_email(); test_size(); + test_save_load(); + return 0; } diff --git a/tests/write_and_read.hpp b/tests/json/write_and_read.hpp similarity index 100% rename from tests/write_and_read.hpp rename to tests/json/write_and_read.hpp diff --git a/tests/test_field_variant.hpp b/tests/test_field_variant.hpp deleted file mode 100644 index 4dfb5e49..00000000 --- a/tests/test_field_variant.hpp +++ /dev/null @@ -1,34 +0,0 @@ -#include -#include -#include -#include -#include -#include - -#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 = std::variant, - rfl::Field<"rectangle", Rectangle>, - rfl::Field<"square", rfl::Box>>; - - const Shapes r = - rfl::make_field<"rectangle">(Rectangle{.height = 10, .width = 5}); - - write_and_read(r, R"({"rectangle":{"height":10.0,"width":5.0}})"); -}