Allow Boxes to conditionally be copyable with an explicit option (#397) (#398)

This commit is contained in:
Joel McKenzie
2025-03-30 14:45:11 +08:00
committed by GitHub
parent 74738ed131
commit 0530379830
4 changed files with 153 additions and 25 deletions
+46
View File
@@ -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}}}} {"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<DecisionTree> lesser;
rfl::CopyableBox<DecisionTree> greater;
};
using LeafOrNode = rfl::TaggedUnion<"type", Leaf, Node>;
rfl::Field<"leafOrNode", LeafOrNode> leaf_or_node;
};
auto leaf1 = DecisionTree::Leaf{.value = 3.0};
auto leaf2 = DecisionTree::Leaf{.value = 5.0};
auto node =
DecisionTree::Node{.critical_value = 10.0,
.lesser = rfl::make_copyable_box<DecisionTree>(leaf1),
.greater = rfl::make_copyable_box<DecisionTree>(leaf2)};
const DecisionTree tree{.leaf_or_node = std::move(node)};
auto different_leaf = DecisionTree::Leaf{.value = 1.0};
DecisionTree copy = tree;
rfl::get<DecisionTree::Node>(copy.leaf_or_node.get().variant()).lesser = rfl::make_copyable_box<DecisionTree>(different_leaf);
```
+48 -13
View File
@@ -8,37 +8,55 @@
namespace rfl { namespace rfl {
enum class Copyability {
COPYABLE,
NON_COPYABLE
};
/// The Box class behaves very similarly to the unique_ptr, but unlike the /// 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 /// 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 /// tries to access it after calling std::move does something else that is
/// clearly bad practice). /// clearly bad practice).
template <class T> ///
/// 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 T, Copyability C = Copyability::NON_COPYABLE>
class Box { class Box {
public: public:
/// The only way of creating new boxes is /// The only way of creating new boxes is
/// Box<T>::make(...). /// Box<T>::make(...).
template <class... Args> template <class... Args>
static Box<T> make(Args&&... _args) { static Box<T, C> make(Args&&... _args) {
return Box<T>(std::make_unique<T>(std::forward<Args>(_args)...)); return Box<T, C>(std::make_unique<T>(std::forward<Args>(_args)...));
} }
/// You can generate them from unique_ptrs as well, in which case it will /// You can generate them from unique_ptrs as well, in which case it will
/// return an Error, if the unique_ptr is not set. /// return an Error, if the unique_ptr is not set.
static Result<Box<T>> make(std::unique_ptr<T>&& _ptr) { static Result<Box<T, C>> make(std::unique_ptr<T>&& _ptr) {
if (!_ptr) { if (!_ptr) {
return error("std::unique_ptr was a nullptr."); return error("std::unique_ptr was a nullptr.");
} }
return Box<T>(std::move(_ptr)); return Box<T, C>(std::move(_ptr));
} }
Box() : ptr_(std::make_unique<T>()) {} Box() : ptr_(std::make_unique<T>()) {}
Box(const Box<T>& _other) = delete; /// Copy constructor if copyable
Box(const Box<T, C>& _other) requires (C == Copyability::COPYABLE)
{
ptr_ = std::make_unique<T>(*_other);
}
Box(Box<T>&& _other) = default; /// Copy constructor if not copyable
Box(const Box<T, C>& _other) requires (C == Copyability::NON_COPYABLE) = delete;
template <class U> Box(Box<T, C>&& _other) = default;
Box(Box<U>&& _other) noexcept
template <class U, Copyability C2>
Box(Box<U, C2>&& _other) noexcept
: ptr_(std::forward<std::unique_ptr<U>>(_other.ptr())) {} : ptr_(std::forward<std::unique_ptr<U>>(_other.ptr())) {}
~Box() = default; ~Box() = default;
@@ -46,15 +64,23 @@ class Box {
/// Returns a pointer to the underlying object /// Returns a pointer to the underlying object
T* get() const { return ptr_.get(); } T* get() const { return ptr_.get(); }
/// Copy assignment operator /// Copy assignment operator if copyable
Box<T>& operator=(const Box<T>& _other) = delete; Box<T, C>& operator=(const Box<T>& other) requires (C == Copyability::COPYABLE) {
if(this != &other) {
ptr_ = std::make_unique<T>(*other);
}
return *this;
}
/// Copy assignment operator if not copyable
Box<T, C>& operator=(const Box<T>& _other) requires (C == Copyability::NON_COPYABLE) = delete;
/// Move assignment operator /// Move assignment operator
Box<T>& operator=(Box<T>&& _other) noexcept = default; Box<T, C>& operator=(Box<T, C>&& _other) noexcept = default;
/// Move assignment operator /// Move assignment operator
template <class U> template <class U>
Box<T>& operator=(Box<U>&& _other) noexcept { Box<T, C>& operator=(Box<U>&& _other) noexcept {
ptr_ = std::forward<std::unique_ptr<U>>(_other.ptr()); ptr_ = std::forward<std::unique_ptr<U>>(_other.ptr());
return *this; return *this;
} }
@@ -92,6 +118,15 @@ auto make_box(Args&&... _args) {
return Box<T>::make(std::forward<Args>(_args)...); return Box<T>::make(std::forward<Args>(_args)...);
} }
/// Template specialization for a box that is copyable.
template<typename T>
using CopyableBox = Box<T, Copyability::COPYABLE>;
template <class T, class... Args>
auto make_copyable_box(Args&&... _args) {
return CopyableBox<T>::make(std::forward<Args>(_args)...);
}
template <class T1, class T2> template <class T1, class T2>
inline auto operator<=>(const Box<T1>& _b1, const Box<T2>& _b2) { inline auto operator<=>(const Box<T1>& _b1, const Box<T2>& _b2) {
return _b1.ptr() <=> _b2.ptr(); return _b1.ptr() <=> _b2.ptr();
+6 -6
View File
@@ -12,19 +12,19 @@
namespace rfl { namespace rfl {
namespace parsing { namespace parsing {
template <class R, class W, class T, class ProcessorsType> template <class R, class W, class T, Copyability C, class ProcessorsType>
requires AreReaderAndWriter<R, W, Box<T>> requires AreReaderAndWriter<R, W, Box<T, C>>
struct Parser<R, W, Box<T>, ProcessorsType> { struct Parser<R, W, Box<T, C>, ProcessorsType> {
using InputVarType = typename R::InputVarType; using InputVarType = typename R::InputVarType;
static Result<Box<T>> read(const R& _r, const InputVarType& _var) noexcept { static Result<Box<T, C>> read(const R& _r, const InputVarType& _var) noexcept {
const auto to_box = [](auto&& _t) { return Box<T>::make(std::move(_t)); }; const auto to_box = [](auto&& _t) { return Box<T, C>::make(std::move(_t)); };
return Parser<R, W, std::remove_cvref_t<T>, ProcessorsType>::read(_r, _var) return Parser<R, W, std::remove_cvref_t<T>, ProcessorsType>::read(_r, _var)
.transform(to_box); .transform(to_box);
} }
template <class P> template <class P>
static void write(const W& _w, const Box<T>& _box, static void write(const W& _w, const Box<T, C>& _box,
const P& _parent) noexcept { const P& _parent) noexcept {
Parser<R, W, std::remove_cvref_t<T>, ProcessorsType>::write(_w, *_box, Parser<R, W, std::remove_cvref_t<T>, ProcessorsType>::write(_w, *_box,
_parent); _parent);
+47
View File
@@ -26,6 +26,7 @@ struct DecisionTree {
rfl::Field<"leafOrNode", LeafOrNode> leaf_or_node; rfl::Field<"leafOrNode", LeafOrNode> leaf_or_node;
}; };
TEST(generic, test_box) { TEST(generic, test_box) {
auto leaf1 = DecisionTree::Leaf{.value = 3.0}; auto leaf1 = DecisionTree::Leaf{.value = 3.0};
@@ -42,3 +43,49 @@ TEST(generic, test_box) {
} }
} // namespace 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<DecisionTree> lesser;
rfl::CopyableBox<DecisionTree> 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>(DecisionTree{leaf1}),
.greater = rfl::make_box<DecisionTree>(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<DecisionTree::Leaf>(rfl::get<DecisionTree::Node>(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<DecisionTree::Leaf>(rfl::get<DecisionTree::Node>(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