Thoth
A functional, expressive, asynchronous C++26 webdev library
Loading...
Searching...
No Matches
Cow.hpp
Go to the documentation of this file.
1#pragma once
2#include <concepts>
3#include <variant>
4
5namespace Thoth::Dsa {
13 template<class RefT, class OwnT>
14 requires std::constructible_from<OwnT, RefT>
15 struct Cow {
16 using ValueType = std::variant<RefT, OwnT>;
17
18 using RefType = RefT;
19 using OwnType = OwnT;
20
21 // NOLINTBEGIN(*)
22 constexpr Cow() = default;
23 constexpr Cow(RefT) noexcept;
24 constexpr Cow(Cow&&) noexcept = default;
25 constexpr Cow(const Cow& other);
26 // NOLINTEND(*)
27
28 constexpr Cow& operator=(Cow&& other) noexcept = default;
29 constexpr Cow& operator=(const Cow& other);
30
31
33 static constexpr Cow FromRef(RefT ref);
35 constexpr Cow& SetRef(RefT ref);
36
37
39 [[nodiscard]] static constexpr bool IsRefType(const Cow& cow);
41 [[nodiscard]] constexpr bool IsRef() const;
42
43
45 static constexpr Cow FromOwned(const OwnT& own);
47 static constexpr Cow FromOwned(OwnT&& own);
49 constexpr Cow& SetOwned(const OwnT& own);
51 constexpr Cow& SetOwned(OwnT&& own);
52
54 constexpr OwnT& AsOwned();
56 [[nodiscard]] constexpr OwnT AsCopy() const;
57
59 [[nodiscard]] constexpr RefT AsRef() const;
60
62 template<class Callable>
63 constexpr decltype(auto) Visit(Callable&& callable);
64
66 template<class Callable>
67 [[nodiscard]] constexpr decltype(auto) Visit(Callable&& callable) const;
68 private:
69 ValueType _value;
70 };
71
72
73 template<class RefT, class OwnT>
74 requires std::constructible_from<OwnT, RefT>
75 constexpr bool operator==(const Cow<RefT, OwnT>& left, const Cow<RefT, OwnT>& right);
76}
77
78#include <Thoth/Dsa/Cow.tpp>
Definition Cow.hpp:5
Like Rust's cow (copy on write).
Definition Cow.hpp:15
OwnT OwnType
Definition Cow.hpp:19
constexpr Cow & SetOwned(const OwnT &own)
Set value to a new OwnT from another OwnT.
constexpr Cow(Cow &&) noexcept=default
constexpr Cow()=default
constexpr OwnT AsCopy() const
Returns a copy of the value as OwnT without modifying it.
constexpr Cow & SetRef(RefT ref)
Sets the value to a new RefT.
static constexpr Cow FromRef(RefT ref)
Constructs a Cow from a RefT.
constexpr Cow(RefT) noexcept
constexpr decltype(auto) Visit(Callable &&callable)
convenient call to std::visit() on _value.
static constexpr Cow FromOwned(const OwnT &own)
Create a OwnT value from another OwnT.
constexpr OwnT & AsOwned()
Converts the RefT type to a OwnT.
std::variant< RefT, OwnT > ValueType
Definition Cow.hpp:16
constexpr bool IsRef() const
Check if the value is a RefT or OwnT.
RefT RefType
Definition Cow.hpp:18
static constexpr bool IsRefType(const Cow &cow)
Check if the value is a RefT or OwnT.
constexpr RefT AsRef() const
Returns a reference of the value as RefT without modifying it.