diff --git a/docs/rfl_ref.md b/docs/rfl_ref.md index 02ea28f5..2f517f19 100644 --- a/docs/rfl_ref.md +++ b/docs/rfl_ref.md @@ -1,4 +1,4 @@ -# `rfl::Box` and `rfl::Ref` +# `rfl::Box` and `rfl::Ref` In previous sections, we have defined the `Person` class recursively: @@ -76,11 +76,11 @@ struct DecisionTree { ``` This will compile, but the design is less than ideal. We know for a fact that a `Node` must have -exactly two subtrees. But this is not reflected in the type system. In this encoding, the fields +exactly two subtrees. But this is not reflected in the type system. In this encoding, the fields "lesser" and "greater" are marked optional and you will have to check at runtime that they are indeed set. But this violates the principles of reflection. Reflection is all about validating as much of our assumptions -upfront as we possibly can. For a great theoretical discussion of this topic, check out +upfront as we possibly can. For a great theoretical discussion of this topic, check out [Parse, don't validate](https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/) by Alexis King. @@ -109,7 +109,7 @@ struct DecisionTree { `rfl::Box` is a thin wrapper around `std::unique_ptr`, but it is guaranteed to **never be null** (unless you do something egregious such as trying to access it after calling `std::move`). It is a `std::unique_ptr` without the `nullptr`. -If you want to learn more about the evils of null references, check out the +If you want to learn more about the evils of null references, check out the [Null References: The Billion Dollar Mistake](https://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare/) by Tony Hoare, who invented the concept in the first place. @@ -145,10 +145,10 @@ auto ptr = std::make_unique("Hello World!"); const rfl::Result> box = rfl::make_box(std::move(ptr)); ``` -Note that `box` is wrapped in a `Result`. That is, because we cannot guarantee at compile time +Note that `box` is wrapped in a `Result`. That is, because we cannot guarantee at compile time that `ptr` is not `nullptr`, therefore we need to account for that. -If you want to use reference-counted pointers, instead of unique pointers, you can use `rfl::Ref`. +If you want to use reference-counted pointers, instead of unique pointers, you can use `rfl::Ref`. `rfl::Ref` is the same concept as `rfl::Box`, but using `std::shared_ptr` under-the-hood. ```cpp @@ -190,5 +190,51 @@ The resulting JSON string is identical: {"leafOrNode":{"type":"Node","criticalValue":10.0,"lesser":{"leafOrNode":{"type":"Leaf","value":3.0}},"greater":{"leafOrNode":{"type":"Leaf","value":5.0}}}} ``` +## Deep Copying + +The default `rfl::Box` implementation behaves the same as `std::unique_ptr` in relation to copying, disabling the copy assignment operator and the copy constructor. + +An opt-in box implementation, `rfl::CopyableBox`, bypasses the `std::unique_ptr` operators and allows copying by calling +the contained type's copy constructor and copy assignment operator directly, but otherwise +behaves the same as `rfl::Box`. + +When using `rfl::CopyableBox`, `rfl::make_box<...>(...)` must be replaced with `rfl::make_copyable_box<...>(...)`. + +This allows for deep-copying of arbitrary-complexity types that contain nested recursive elements: + +```cpp +struct DecisionTree { + struct Leaf { + using Tag = rfl::Literal<"Leaf">; + double prediction; + }; + + struct Node { + using Tag = rfl::Literal<"Node">; + rfl::Rename<"criticalValue", double> critical_value; + rfl::CopyableBox lesser; + rfl::CopyableBox 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_copyable_box(leaf1), + .greater = rfl::make_copyable_box(leaf2)}; + +const DecisionTree tree{.leaf_or_node = std::move(node)}; + +auto different_leaf = DecisionTree::Leaf{.value = 1.0}; +DecisionTree copy = tree; + +rfl::get(copy.leaf_or_node.get().variant()).lesser = rfl::make_copyable_box(different_leaf); +``` diff --git a/include/rfl/Box.hpp b/include/rfl/Box.hpp index 140f0af1..b8c90340 100644 --- a/include/rfl/Box.hpp +++ b/include/rfl/Box.hpp @@ -8,37 +8,55 @@ namespace rfl { + +enum class Copyability { + COPYABLE, + NON_COPYABLE +}; + /// The Box class behaves very similarly to the unique_ptr, but unlike the /// unique_ptr, it is 100% guaranteed to be filled at all times (unless the user /// tries to access it after calling std::move does something else that is /// clearly bad practice). -template +/// +/// By default Box behaves like a unique_ptr in relation to copying, but it can be +/// configured to add copy constructor and assignment operators that call the +/// same function of the contained type T. + +template class Box { public: /// The only way of creating new boxes is /// Box::make(...). template - static Box make(Args&&... _args) { - return Box(std::make_unique(std::forward(_args)...)); + static Box make(Args&&... _args) { + return Box(std::make_unique(std::forward(_args)...)); } /// You can generate them from unique_ptrs as well, in which case it will /// return an Error, if the unique_ptr is not set. - static Result> make(std::unique_ptr&& _ptr) { + static Result> make(std::unique_ptr&& _ptr) { if (!_ptr) { return error("std::unique_ptr was a nullptr."); } - return Box(std::move(_ptr)); + return Box(std::move(_ptr)); } Box() : ptr_(std::make_unique()) {} - Box(const Box& _other) = delete; + /// Copy constructor if copyable + Box(const Box& _other) requires (C == Copyability::COPYABLE) + { + ptr_ = std::make_unique(*_other); + } - Box(Box&& _other) = default; + /// Copy constructor if not copyable + Box(const Box& _other) requires (C == Copyability::NON_COPYABLE) = delete; - template - Box(Box&& _other) noexcept + Box(Box&& _other) = default; + + template + Box(Box&& _other) noexcept : ptr_(std::forward>(_other.ptr())) {} ~Box() = default; @@ -46,15 +64,23 @@ class Box { /// Returns a pointer to the underlying object T* get() const { return ptr_.get(); } - /// Copy assignment operator - Box& operator=(const Box& _other) = delete; + /// Copy assignment operator if copyable + Box& operator=(const Box& other) requires (C == Copyability::COPYABLE) { + if(this != &other) { + ptr_ = std::make_unique(*other); + } + return *this; + } + + /// Copy assignment operator if not copyable + Box& operator=(const Box& _other) requires (C == Copyability::NON_COPYABLE) = delete; /// Move assignment operator - Box& operator=(Box&& _other) noexcept = default; + Box& operator=(Box&& _other) noexcept = default; /// Move assignment operator template - Box& operator=(Box&& _other) noexcept { + Box& operator=(Box&& _other) noexcept { ptr_ = std::forward>(_other.ptr()); return *this; } @@ -92,6 +118,15 @@ auto make_box(Args&&... _args) { return Box::make(std::forward(_args)...); } +/// Template specialization for a box that is copyable. +template +using CopyableBox = Box; + +template +auto make_copyable_box(Args&&... _args) { + return CopyableBox::make(std::forward(_args)...); +} + template inline auto operator<=>(const Box& _b1, const Box& _b2) { return _b1.ptr() <=> _b2.ptr(); diff --git a/include/rfl/parsing/Parser_box.hpp b/include/rfl/parsing/Parser_box.hpp index 590e1eee..33e17880 100644 --- a/include/rfl/parsing/Parser_box.hpp +++ b/include/rfl/parsing/Parser_box.hpp @@ -12,19 +12,19 @@ namespace rfl { namespace parsing { -template -requires AreReaderAndWriter> -struct Parser, ProcessorsType> { +template +requires AreReaderAndWriter> +struct Parser, ProcessorsType> { using InputVarType = typename R::InputVarType; - static Result> read(const R& _r, const InputVarType& _var) noexcept { - const auto to_box = [](auto&& _t) { return Box::make(std::move(_t)); }; + static Result> read(const R& _r, const InputVarType& _var) noexcept { + const auto to_box = [](auto&& _t) { return Box::make(std::move(_t)); }; return Parser, ProcessorsType>::read(_r, _var) .transform(to_box); } template - static void write(const W& _w, const Box& _box, + static void write(const W& _w, const Box& _box, const P& _parent) noexcept { Parser, ProcessorsType>::write(_w, *_box, _parent); diff --git a/tests/generic/test_box.cpp b/tests/generic/test_box.cpp index 2e819e8d..bfa1eb8d 100644 --- a/tests/generic/test_box.cpp +++ b/tests/generic/test_box.cpp @@ -26,6 +26,7 @@ struct DecisionTree { rfl::Field<"leafOrNode", LeafOrNode> leaf_or_node; }; + TEST(generic, test_box) { auto leaf1 = DecisionTree::Leaf{.value = 3.0}; @@ -42,3 +43,49 @@ TEST(generic, test_box) { } } // namespace test_box + + +namespace test_copyable_box +{ +struct DecisionTree { + struct Leaf { + using Tag = rfl::Literal<"Leaf">; + double value; + }; + + struct Node { + using Tag = rfl::Literal<"Node">; + rfl::Rename<"criticalValue", double> critical_value; + rfl::CopyableBox lesser; + rfl::CopyableBox greater; + }; + + using LeafOrNode = rfl::TaggedUnion<"type", Leaf, Node>; + + rfl::Field<"leafOrNode", LeafOrNode> leaf_or_node; +}; +TEST(generic, copyable_box) { + 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 tree1{.leaf_or_node = std::move(node)}; + + write_and_read(tree1); + + const DecisionTree tree2 = tree1; + + auto lesser_leaf_tree2 = rfl::get(rfl::get(tree2.leaf_or_node.get().variant()).lesser.get()->leaf_or_node.get().variant()); + lesser_leaf_tree2.value = 1.0; + + + auto lesser_leaf_tree1 = rfl::get(rfl::get(tree1.leaf_or_node.get().variant()).lesser.get()->leaf_or_node.get().variant()); + EXPECT_NE(lesser_leaf_tree1.value, lesser_leaf_tree2.value); + +} +} // namespace test_copyable_box